helloworld
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world() :
return 'Hello, World! '
Copy the code
The URL parameter
@app.route('/user/<username>')
def show_user_profile(username) :
# show the user profile for that user
return 'User %s' % escape(username)
@app.route('/post/<int:post_id>')
def show_post(post_id) :
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
@app.route('/path/<path:subpath>')
def show_subpath(subpath) :
# show the subpath after /path/
return 'Subpath %s' % escape(subpath)
Copy the code
routing
The projects URL is regular, with a trailing slash that looks like a folder. Flask automatically redirects a URL that doesn’t end with a slash, and adds a slash to the end.
The ABOUT URL has no trailing slash, so it behaves like a file. If you access this URL with a trailing slash, you get a 404 error. This keeps the URL unique and helps search engines avoid indexing the same page twice.
@app.route('/projects/')
def projects() :
return 'The project page'
@app.route('/about')
def about() :
return 'The about page'
Copy the code
# the route source
def route(self, rule, **options) :
def decorator(f) :
endpoint = options.pop("endpoint".None)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
Copy the code
If an endpoint is provided, use the name of the view function as the endpoint
def _endpoint_from_view_func(view_func) :
"""Internal helper that returns the default endpoint for a given function. This always is the function name. """
assert view_func is not None."expected view func if endpoint is not provided."
return view_func.__name__
Copy the code
URL building
The url_for() function is used to build the URL of the specified function. It takes the function name as its first argument. It can take any keyword argument, and each keyword argument corresponds to a variable in the URL. Unknown variables are added to the URL as query parameters
url_for()
Copy the code
HTTP method
Web applications use different HTTP methods to handle urls. You should be familiar with the HTTP method when using Flask. By default, a route responds only to GET requests. You can use the methods parameter of the route() decorator to handle different HTTP methods:
from flask import request
@app.route('/login', methods=['GET'.'POST'])
def login() :
if request.method == 'POST':
return do_the_login()
else:
return show_the_login_form()
Copy the code
Static files
url_for('static', filename='style.css')
# This static file should be static/style.css in the file system
Copy the code
Apply colours to a drawing template
@app.route('/')
def hello_world() :
return "" "
index hello wolrd
"""
Copy the code
@app.route('/home')
def home() :
return render_template('index.html')
Copy the code
Template to escape
@app.route('/home')
def home() :
label = Markup(")
print(label)
return render_template('index.html', label=label)
Copy the code
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<h1 style="color: green;">hello wolrd</h1>
{{ label }}
</body>
</html>
Copy the code
or
@app.route('/home')
def home() :
label = "
return render_template('index.html', label=label)
Copy the code
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<h1 style="color: green;">hello wolrd</h1>
{{ label | safe }}
</body>
</html>
Copy the code
Jinja2
@app.route('/')
def hello_world() :
a = 1
b = 2
age = 23
name = 'wanghaha'
nums = [1.8.28.33]
info = {'name': 'Wang ha ha'.'age': 23}
users = [
{'name': 'Dilieba'.'age': 27},
{'name': 'Gulinaza'.'age': 26}]return render_template('index.html', * *locals())
Copy the code
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>{# render a variable and do the calculation #}<p>a+b={{ a + b }}</p>{# for loop over list #}<ul>
{% for item in nums %}
<li>{{ item }}</li>
{% endfor %}
</ul>{% if age >=18 and age <=100 %}<p>You of age</p>
{% elif age <18 and age >0 %}
<p>A minor</p>
{% else %}
<p>Age is illegal</p>{% endif %} {# endif %} #} {% for key, val in info.items() %}<p>key: {{ key }} val:{{ val }}</p>{% for user in users %} {% for key, val in user.items() %}<p>key: {{ key }} val: {{ val }}</p>{% endfor %} {% endfor %} {# filter uses case conversion #}<p>{{ name | upper }}</p>
<p>{{ name | upper | lower}}</p>{% macro input(type, name, placeholder) %}<div>
<label for="{{ name }}">{{ name }}</label>
<input type='{{type}}' id="{{ name }}" name="{{ name }}" placeholder="{{ placeholder }}">
</div>{% endmacro %}<p>{{input('text', 'username', 'please enter username')}}</p>
<p>{{input('password', 'password', 'please enter password')}}</p>
</body>
</html>
Copy the code
Template inheritance
@app.route('/')
def hello_world() :
return render_template('index.html')
Copy the code
base.html
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
{% block head_region %}{% endblock %}
</head>
<body>
{% block content %}
<h1>welcome</h1>
{% endblock %}
{% block footer_region %}{% endblock %}
</body>
</html>
Copy the code
public.html
<h1>Public. HTML content</h1>
Copy the code
index.html
{% extends 'base.html' %} {% block title %} {% endBlock %} {% block Content %} {{super()}}<h1>hello world</h1>#} {% include "public. HTML "%} {% endBlock %} {% block footer_region %}<script>
alert('hello');
</script>
{% endblock %}
Copy the code
Custom template function, filter
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world() :
return render_template('index.html')
Define global functions to be used in templates
@app.add_template_global
def my_sum(a, b) :
return a + b
# Custom filters
@app.template_filter()
def my_filter(arg) :
return arg.upper()
if __name__ == '__main__':
app.run(debug=True)
Copy the code
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>1 + 5 = {{ my_sum(1, 5) }}</p>
<p>{{ "hello" | my_filter }}</p>
</body>
</html>
Copy the code
request
@app.route('/home')
def home() :
print('cookies:', request.cookies) # get cookies
print('headers:', request.headers) Get the request header information
print('method:', request.method) # request method
print('url:', request.url) Request address with parameter
print('url_rule:', request.url_rule) The request URL does not contain the request address and parameters
print('url_root:', request.url_root) # request address
print('host_url:', request.host_url) # similar to url_root
print('base_url:', request.base_url) # request address and URL and no parameters
print('path:', request.path) # request URL
print('values:', request.values) # contains parameters for GET and POST requests
print('args:', request.args) Get URL parameters
print('form:', request.form) Get the parameters of the POST submission formData
print('files:', request.files) Get the submitted file
print('json:', request.json) # fetch data submitted for appliciton /json with header
return 'home page'
Copy the code
The response
from flask import Flask, render_template, make_response, abort, Response, send_file, redirect, url_for
app = Flask(__name__)
@app.route('/page1')
def page1() :
return 'page1'
@app.route('/page2')
def page2() :
return render_template('index.html')
@app.route('/page3')
def page3() :
resp = make_response('<h1>hello world</h1>')
resp.headers['name'] = 'hello'
return resp
@app.route('/page4')
def page4() :
resp = make_response(render_template('index.html'))
return resp
@app.route('/page5')
def page5() :
info = {'name': 'wanghaha'.'age': 23}
resp = make_response(info)
resp.headers['Content-Type'] = 'application/json'
return resp
@app.route('/page6')
def page6() :
abort(403)
@app.route('/page7')
def page7() :
return Response('Hello World! ', status=200, mimetype='text/html')
@app.route('/page8')
def page8() :
return send_file('mn.jpg')
@app.route('/page9')
def page9() :
return redirect(url_for('page8'))
if __name__ == '__main__':
app.run(debug=True)
Copy the code
File upload
from flask import Flask, request
app = Flask(__name__)
@app.route('/upload', methods=['GET'.'POST'])
def upload() :
if request.method == 'GET':
return "" "
index
"""
elif request.method == 'POST':
file = request.files['file']
file.save(file.filename)
return 'upload successful'
if __name__ == '__main__':
app.run(debug=True)
Copy the code
cookies
from flask import Flask, request, make_response
app = Flask(__name__)
@app.route('/page1')
def page1() :
resp = make_response('<h1>hello world</h1>')
resp.set_cookie('name'.'wanghaha')
return resp
@app.route('/page2')
def page2() :
name = request.cookies.get('name')
return f'cookies name: {name}'
if __name__ == '__main__':
app.run(debug=True)
Copy the code
Redirects and errors
from flask import Flask, redirect, url_for, abort
app = Flask(__name__)
@app.route('/index')
def index() :
return 'index page'
@app.route('/page1')
def page1() :
return redirect(url_for('index'))
Permanent redirection, which is cached by the browser without being processed by the server
@app.route('/page2')
def page2() :
return redirect(url_for('index')), 301
@app.route('/abort500')
def abort500() :
abort(500)
@app.errorhandler(404)
def not_found_page(code_or_exception) :
return 'Page not found'.404
@app.errorhandler(500)
def server_error(code_or_exception) :
return 'Server error error'.500
if __name__ == '__main__':
app.run()
Copy the code
JSON API
from flask import Flask, jsonify, json, make_response
app = Flask(__name__)
@app.route('/page1')
def page1() :
info = {'name': 'wanghaha'.'age': 23}
resp = make_response(info)
resp.headers['Content-Type'] = 'application/json'
return resp
@app.route('/page2')
def page2() :
info = {'name': 'wanghaha'.'age': 23}
return jsonify(info)
if __name__ == '__main__':
app.run()
Copy the code
session
from flask import Flask, session
from os import urandom
app = Flask(__name__)
app.secret_key = urandom(25)
@app.route('/page1')
def page1() :
session['u'] = 'admin'
return 'page1 page'
@app.route('/page2')
def page2() :
return f"session u:{session.get('u')}"
if __name__ == '__main__':
app.run()
Copy the code
flash
from flask import Flask, flash, get_flashed_messages
from os import urandom
app = Flask(__name__)
app.secret_key = urandom(25)
@app.route('/page1')
def page1() :
flash('hello')
flash('world')
flash('welcome'.'success')
return 'page1 page'
@app.route('/page2')
def page2() :
print(get_flashed_messages())
return 'page2 page'
@app.route('/page3')
def page3() :
print(get_flashed_messages(with_categories=True))
return 'page3 page'
if __name__ == '__main__':
app.run()
Copy the code
The log
The blueprint
from flask import Flask, Blueprint
api = Blueprint('api'.'api')
admin = Blueprint('admin'.'admin')
@api.route('/page1')
def page1() :
return 'api page1'
@admin.route('/page2')
def page2() :
return 'admin page2'
app = Flask(__name__)
app.register_blueprint(api)
app.register_blueprint(admin)
@app.route('/')
def hello_world() :
return 'Hello World! '
if __name__ == '__main__':
app.run()
Copy the code
Hook function
from flask import Flask
app = Flask(__name__)
@app.route('/page1')
def page1() :
return 'page1'
@app.route('/page2')
def page2() :
return 'page2'
@app.before_request
def first_request() :
print('Before requesting access to view function')
@app.after_request
def after_request(response) :
print('Call before view function ends')
return response
if __name__ == '__main__':
app.run()
Copy the code
CBV
from flask import Flask, views, request
app = Flask(__name__)
class Index(views.MethodView) :
def get(self) :
return 'get method page'
def post(self) :
return 'post method page'
class Upload(views.MethodView) :
methods = ['GET'.'POST']
def get(self) :
return "" "
index
"""
def post(self) :
file = request.files['file']
file.save(file.filename)
return 'upload successful'
app.add_url_rule('/index', view_func=Index.as_view(name='index'))
app.add_url_rule('/upload', view_func=Upload.as_view(name='upload'))
if __name__ == '__main__':
app.run(debug=True)
Copy the code
configuration
# default configuration
default_config = ImmutableDict(
{
"ENV": None."DEBUG": None."TESTING": False."PROPAGATE_EXCEPTIONS": None."PRESERVE_CONTEXT_ON_EXCEPTION": None."SECRET_KEY": None."PERMANENT_SESSION_LIFETIME": timedelta(days=31),
"USE_X_SENDFILE": False."SERVER_NAME": None."APPLICATION_ROOT": "/"."SESSION_COOKIE_NAME": "session"."SESSION_COOKIE_DOMAIN": None."SESSION_COOKIE_PATH": None."SESSION_COOKIE_HTTPONLY": True."SESSION_COOKIE_SECURE": False."SESSION_COOKIE_SAMESITE": None."SESSION_REFRESH_EACH_REQUEST": True."MAX_CONTENT_LENGTH": None."SEND_FILE_MAX_AGE_DEFAULT": timedelta(hours=12),
"TRAP_BAD_REQUEST_ERRORS": None."TRAP_HTTP_EXCEPTIONS": False."EXPLAIN_TEMPLATE_LOADING": False."PREFERRED_URL_SCHEME": "http"."JSON_AS_ASCII": True."JSON_SORT_KEYS": True."JSONIFY_PRETTYPRINT_REGULAR": False."JSONIFY_MIMETYPE": "application/json"."TEMPLATES_AUTO_RELOAD": None."MAX_COOKIE_SIZE": 4093,})Copy the code
class Config(object) :
DEBUG = False
TESTING = False
DATABASE_URI = 'sqlite:///:memory:'
class ProductionConfig(Config) :
DATABASE_URI = 'mysql://user@localhost/foo'
class DevelopmentConfig(Config) :
DEBUG = True
class TestingConfig(Config) :
TESTING = True
Copy the code
app.config.from_object('configmodule.ProductionConfig')
Copy the code
Project layout
The deployment of
uwsgi.ini
[uwsgi]
http=0.0.0.0:5000
socket=0.0.0.0:8001
chdir = /root
wsgi-file = main.py
stats = 127.0.0.1:9191
callable = app
processes = 4
threads = 10
Copy the code
location / {
include uwsgi_params;
uwsgi_pass 127.0.0.1:8001;
}
Copy the code
extension
Flask-session
flask-migrate
from flask import Flask
from api import api as api_blueprint
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from models import db
import config
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(api_blueprint)
db.init_app(app)
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
Copy the code
python3 manage.py db init
python3 manage.py db migrate
python3 manage.py db upgrade
Copy the code
flask-sqlalchemy
Convert the result set to JSON format
# sqlalchemy results to JSON
from sqlalchemy.orm import class_mapper
Convert sqlAlchemy results to JSON
def mapper(model) :
columns = [c.key for c in class_mapper(model.__class__).columns]
return dict((c, getattr(model, c)) for c in columns)
# determine whether the result is multiple or one
def to_json(model) :
if isinstance(model, list):
data = []
[data.append(mapper(item)) for item in model]
return data
return mapper(model)
Copy the code
flask-script
flask-login
flask-rbac
Flask-debugToolbar
flask-restful
flask-admin
flask-cli
flask-mail
flask-cors
from flask_cors import CORS
app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
Copy the code
# Separate blueprint configuration
api_v1 = Blueprint('API_v1', __name__)
CORS(api_v1)
Copy the code
Return the SQLAlchemy object
Add the following methods to the model
def to_json(self) :
dict = self.__dict__
if "_sa_instance_state" in dict:
del dict["_sa_instance_state"]
return dict
Copy the code
The returned data is placed in the list using the to_JSON method
@app.route('/comments', methods=['GET'])
def comments() :
comments = db.session.query(Comment).all()
result = []
for comment in comments:
result.append(comment.to_json())
return jsonify(result), 200
Copy the code