Flask framework of small note

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_folderwhere static_folderand static_url_pathfor reverse lookup
  • Useful configuration static_hostspecified static server, host_matchingspecify the host can be put to the service, root_pathfor the project's root directory, which generally does not amend

view

The return value of a view

  • 'returned string': Return Response
  • redirect: Redirect
  • render_template: Return jinja2 template file, render_templatewill templateslook for files in the directory
  • jsonify: Returns a string serialization good json
  • sendfile: File server sent directly to the client, plus functions

The request object

  • Introducing from flask import request, where this requestobject is not requestan object, it is an LocalProxyobject inside the package the requestobject, reflecting the acquisition requestof each of the properties and methods
  • Attributes
    • method: Request method initiated by the client
    • form: The client sends the formforms, it is a ImmutableMultiDictdictionary object, by get()obtaining; by keys()acquiring all of the keys, by values()acquiring all of the values; to_dict()converted to Python dictionary
    • args: Url through ?all the parameters passed
    • values: As long as the parameters are put there, whether it is formor ars, the return of CombinedMultiDictobjects
    • headers: Request message header, a dictionary, through get()direct access to a corresponding value, and headersthe __str__well, Django humane than the format of the returned string
    • files: Object file upload, a dictionary, through get()out value, you can directly save()to a local, plus function
    • data: When the mimetypedata type is not identifiable Flask time, there would put
    • json: When mimetypeis application/jsonthe time to store data
    • url: Url full path
    • path: Resource Path
    • url_root: The level url, for example http://127.0.0.1/home, the url_rootreturnhttp://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 include
    1. methods=['GET', 'POST'] Other requests allowed
    2. strict_slashes: It is Trueindicative of a strict mode, adding /home/at the end added /, but also add in the browser address bar; otherwise it can be with and without
    3. redirect_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_requsetIn view before calling the function call, if by then returns None

Session

  1. Use flask comes session needs to be configured app.config['SECRET_KEY'] = 'your key'
  2. from flask import session
  3. session['username'] = 'jack'
  4. 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 runserverfunction
  • Used in manage.py

from flask_script import Manager
manager = Manager(app)
manager.run()

Flask-Migrate

  • Django realization of migratefunctions
  • 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
    1. python manage.py init
    2. python manage.py migrate # django 中 makemigrations
    3. python 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 中迭代取出数据

Guess you like

Origin www.cnblogs.com/megachen/p/11126512.html