Flask framework of small note
Flask examples
Create a code sample
from flask import Flask # __name__ 是模块名, 用于反射导入模块 app = Flask(__name__, import_name, static_url_path=None, static_folder='static', static_host=None, host_matching=False, subdomain_matching=False, template_folder='templates', instance_path=None, instance_relative_config=False, root_path=None) # 其中 Flask 实例, debug=True 将实施热更新 app.run('0.0.0.0', 8080, debug=True)
- The most common configuration is
static_folder
,static_url_path
,template_folder
wherestatic_folder
andstatic_url_path
for reverse lookup Useful configuration
static_host
specified static server,host_matching
specify the host can be put to the service,root_path
for the project's root directory, which generally does not amend
view
The return value of a view
'returned string'
: ReturnResponse
redirect
: Redirectrender_template
: Return jinja2 template file,render_template
willtemplates
look for files in the directoryjsonify
: Returns a string serialization good jsonsendfile
: File server sent directly to the client, plus functions
The request object
- Introducing
from flask import request
, where thisrequest
object is notrequest
an object, it is anLocalProxy
object inside the package therequest
object, reflecting the acquisitionrequest
of each of the properties and methods - Attributes
method
: Request method initiated by the clientform
: The client sends theform
forms, it is aImmutableMultiDict
dictionary object, byget()
obtaining; bykeys()
acquiring all of the keys, byvalues()
acquiring all of the values;to_dict()
converted to Python dictionaryargs
: Url through?
all the parameters passedvalues
: As long as the parameters are put there, whether it isform
orars
, the return ofCombinedMultiDict
objectsheaders
: Request message header, a dictionary, throughget()
direct access to a corresponding value, andheaders
the__str__
well, Django humane than the format of the returned stringfiles
: Object file upload, a dictionary, throughget()
out value, you can directlysave()
to a local, plus functiondata
: When themimetype
data type is not identifiable Flask time, there would putjson
: Whenmimetype
isapplication/json
the time to store dataurl
: Url full pathpath
: Resource Pathurl_root
: The level url, for examplehttp://127.0.0.1/home
, theurl_root
returnhttp://127.0.0.1/
Routing System
@app.route('/', endpoint=None, **options)
endpoint
: Means for generating a reverse route, and in a similar Django urlpartten in the path name, unexpected errors are generally assigned to the endpoint prevent
options
includemethods=['GET', 'POST']
Other requests allowedstrict_slashes
: It isTrue
indicative of a strict mode, adding/home/
at the end added/
, but also add in the browser address bar; otherwise it can be with and withoutredirect_to
: Function without entering the view, redirect the direct route
Dynamic routing parameters
- Sample Code
@app.router('/user/<int:age>/', endpoint='user', methods=['GET']) def user(age): ...
blueprint
- Similar blueprint in Django
- Blueprint directory structure
.
├── app # 存放 app, 和 django 不同, 这里所有的东西都放到 app 里面
│ ├── __init__.py # 在 __init__.py 有 create_app() 方法, 用于创建 Flask 实例, 并注册蓝图, 最后返回 app
│ ├── __pycache__
│ │ └── __init__.cpython-36.pyc
│ ├── models # 存放 ORM
│ └── views # 存放各个模块的 views, 就是蓝图书写的地方
│ ├── __pycache__
│ │ └── users.cpython-36.pyc
│ └── users.py # 蓝图文件, 在 users.py 中, 和 之前没有蓝图使用 app 一样, 先创建蓝图对象, 在使用 @bp.route 添加路由
├── manage.py # 程序启动文件, 调用 app 获取 app 实例, 启动 app
├── static
└── templates
7 directories, 5 files
- Create a blueprint
from flask import Blueprint
# __name__ 是模块名, 用于反射导入模块
bp = Blueprint('my_bp', __name___, templates_folder=..., static_folder=...)
- Registration blueprint,
app.register_blueprint(bp, url_prefix='/users')
Special decorator (middleware flask in)
@app.before_requset
In view before calling the function call, if by then returns None
Session
- Use flask comes session needs to be configured
app.config['SECRET_KEY'] = 'your key'
from flask import session
session['username'] = 'jack'
- flask in the session exists in the browser, decrypted by the algorithm when the browser returns
Flask configuration
- If you configure more content, written config.py module will be configured, re-use
app.config.from_object(config)
Flask-Script
- Django achieve similar in
python manage.py runserver
function - Used in manage.py
from flask_script import Manager
manager = Manager(app)
manager.run()
Flask-Migrate
- Django realization of
migrate
functions - Used in manage.py
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
main_app = create_app()
manager = Manager(main_app)
Migrate(main_app, app.db)
manager.add_command('db', MigrateCommand)
manager.run()
- command
python manage.py init
python manage.py migrate
# django 中 makemigrationspython manage.py upgrade
# django 中 migrate
Flask-SQLAlchemy
# app/__init__.py
from flask_sqlalchemy import SQAlchemy
# 要在蓝图导入之前
db = SQLAlchemy()
def create_app():
...
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://username:[email protected]:3306/dbname?charset=utf8'
app.config['SQLALCHEMY_POOL_SIZE'] = 6
app.config['SQLALCHEMY_POOL_TIMEOUT'] = 10
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
...
# models/user.py
from app import db
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
# 使用和 django 类似
User.query(...)
# 支持原生 SQL
User.query(text('SELECT * FROM user;'))
# 如果直接打印, 输出的是原生 SQL 语句, 在 for 中迭代取出数据