python框架☞Flask
flask文档: https://flask.palletsprojects.com/en/1.1.x/
flask程序两种启动方式: 1. 通过开发工具启动 2. Windows环境在终端启动 set FLASK_APP = flask_application.py set FLASK_ENV = development #设置为debug模式 set FALSK_DEBUG = 1 # 设置为debug模式(跟上面方法可以任选一种) python -m flask run # 启动flask程序 python -m flask run --host=0.0.0.0 #设置所以机器都可访问flask程序
python routing from markupsafe import escape @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): pass @app.route('/path/<path:subpath>') def show_subpath(subpath): return 'Subpath %s' % escape(subpath)
Converter types:
|
(default) accepts any text without a slash |
|
accepts positive integers |
|
accepts positive floating point values |
|
like |
|
accepts UUID strings |
Unique URLs / Redirection Behavior
@app.route('/projects/') def projects(): return 'The project page' @app.route('/about') def about(): return 'The about page'
1 作用:通过视图函数,给响应请求附加请求头 2 3 函数:make_response(*args) 4 5 函数内部执行操作: 6 - if no arguments are passed, it creates a new response argument 7 - if one argument is passed, :meth:`flask.Flask.make_response` 8 is invoked with it. 9 - if more than one argument is passed, the arguments are passed 10 to the :meth:`flask.Flask.make_response` function as tuple. 11 12 实战: 13 使用方式一: 14 def index(): 15 response = make_response(render_template('index.html', foo=42)) 16 response.headers['X-Parachutes'] = 'parachutes are cool' 17 return response 18 19 使用方式二: 20 response = make_response(render_template('not_found.html'), 404) 21 22 使用方式三: 23 response = make_response(view_function()) 24 response.headers['X-Parachutes'] = 'parachutes are cool'
1 导入:from flask import jsonify 2 3 作用:将response以json格式返回 4 5 定义:jsonify(*args, **kwargs) 6 7 注意事项: 8 the JSON serialization behavior has the following differences 9 from :func:`dumps`: 10 11 1. Single argument: Passed straight through to :func:`dumps`. 12 2. Multiple arguments: Converted to an array before being passed to:func:`dumps`. 13 3. Multiple keyword arguments: Converted to a dict before being passed to:func:`dumps`. 14 4. Both args and kwargs: Behavior undefined and will throw an exception. 15 特别提醒:不支持同时传关键字参数和位置参数 16 17 实战: 18 Example usage:: 19 Example usage:: 20 21 from flask import jsonify 22 23 @app.route('/_get_current_user') 24 def get_current_user(): 25 return jsonify(username=g.user.username, 26 email=g.user.email, 27 id=g.user.id) 28 29 This will send a JSON response like this to the browser:: 30 31 { 32 "username": "admin", 33 "email": "admin@localhost", 34 "id": 42 35 } 36 37 response以json格式输出的前置条件: 38 ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the Flask app is running in debug mode
from flask import Flask, flash, get_flashed_messages 闪现:基于session实现 def flash(message, category='message'): """Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call :func:`get_flashed_messages`. .. versionchanged:: 0.3 `category` parameter added. :param message: the message to be flashed. :param category: the category for the message. The following values are recommended: ``'message'`` for any kind of message, ``'error'`` for errors, ``'info'`` for information messages and ``'warning'`` for warnings. However any kind of string can be used as category. """ # Original implementation: # # session.setdefault('_flashes', []).append((category, message)) # # This assumed that changes made to mutable structures in the session are # are always in sync with the session object, which is not true for session # implementations that use external storage for keeping their keys/values. flashes = session.get('_flashes', []) flashes.append((category, message)) session['_flashes'] = flashes message_flashed.send(current_app._get_current_object(), message=message, category=category) def get_flashed_messages(with_categories=False, category_filter=[]): """Pulls all flashed messages from the session and returns them. Further calls in the same request to the function will return the same messages. By default just the messages are returned, but when `with_categories` is set to ``True``, the return value will be a list of tuples in the form ``(category, message)`` instead. Filter the flashed messages to one or more categories by providing those categories in `category_filter`. This allows rendering categories in separate html blocks. The `with_categories` and `category_filter` arguments are distinct: * `with_categories` controls whether categories are returned with message text (``True`` gives a tuple, where ``False`` gives just the message text). * `category_filter` filters the messages down to only those matching the provided categories. See :ref:`message-flashing-pattern` for examples. .. versionchanged:: 0.3 `with_categories` parameter added. .. versionchanged:: 0.9 `category_filter` parameter added. :param with_categories: set to ``True`` to also receive categories. :param category_filter: whitelist of categories to limit return values """ flashes = _request_ctx_stack.top.flashes if flashes is None: _request_ctx_stack.top.flashes = flashes = session.pop('_flashes') \ if '_flashes' in session else [] if category_filter: flashes = list(filter(lambda f: f[0] in category_filter, flashes)) if not with_categories: return [x[1] for x in flashes] return flashes
1 导入:from flask import url_for 2 3 作用:反向生成url, 配合endpoint一起使用 4 5 定义:url_for(endpoint, **values)
1 Flask定义路由绑定关系有两种方式 2 3 from flask import Flask 4 5 app = Flask(__name__) 6 7 方式1:装饰器 8 @app.route('/user', endpoint='info') 9 def get_current_user(): 10 return jsonify('hello', 12, '男') 11 12 方式2:通过add_url_rule method 13 def get_file_name(): 14 return 'ok' 15 16 app.add_url_rule('/file', 'f', get_file_name) 17 18 说明:装饰器方法内部也是通过add_url_rule 方法来实现的
1 flask的配置文件是一个flask.config.Config对象,默认配置: 2 default_config = ImmutableDict({ 3 'ENV': None, 4 'DEBUG': None, 5 'TESTING': False, 6 'PROPAGATE_EXCEPTIONS': None, 7 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 8 'SECRET_KEY': None, 9 'PERMANENT_SESSION_LIFETIME': timedelta(days=31), 10 'USE_X_SENDFILE': False, 11 'SERVER_NAME': None, 12 'APPLICATION_ROOT': '/', 13 'SESSION_COOKIE_NAME': 'session', 14 'SESSION_COOKIE_DOMAIN': None, 15 'SESSION_COOKIE_PATH': None, 16 'SESSION_COOKIE_HTTPONLY': True, 17 'SESSION_COOKIE_SECURE': False, 18 'SESSION_COOKIE_SAMESITE': None, 19 'SESSION_REFRESH_EACH_REQUEST': True, 20 'MAX_CONTENT_LENGTH': None, 21 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12), 22 'TRAP_BAD_REQUEST_ERRORS': None, 23 'TRAP_HTTP_EXCEPTIONS': False, 24 'EXPLAIN_TEMPLATE_LOADING': False, 25 'PREFERRED_URL_SCHEME': 'http', 26 'JSON_AS_ASCII': True, 27 'JSON_SORT_KEYS': True, 28 'JSONIFY_PRETTYPRINT_REGULAR': False, 29 'JSONIFY_MIMETYPE': 'application/json', 30 'TEMPLATES_AUTO_RELOAD': None, 31 'MAX_COOKIE_SIZE': 4093, 32 }) 33 34 35 实际使用过程中,flask常用导入配置项有三种方式: 36 方式1:app.config.from_pyfile('yourconfig.cfg') 37 注意:yourconfig.cfg 文件一般是放在程序根路径下面 38 如: 39 settings.py 40 DEBUG = True 41 TESTING = True 42 43 app.config.from_pyfile("settings.py") 44 45 方式2:app.config.from_object() 46 官方解释: provide an import path to a module that should be loaded. It is also possible to tell it to use the same module and with that provide the configuration values just before the call 47 使用from_object方式导入配置项,有两种方式 48 1: 49 DEBUG = True 50 SECRET_KEY = 'development key' 51 app.config.from_object(__name__) 52 53 2: 54 app.config.from_object('test_flask.settings.TestConfig') 55 56 settings.py 57 58 class BaseConfig: 59 DEBUG = False 60 TESTING = False 61 DATABASE_URI = 'sqlite://:memory:' 62 63 class ProConfig(BaseConfig): 64 DATABASE_URI = 'mysql://user@localhost/foo' 65 66 class DevConfig(BaseConfig): 67 DEBUG = True 68 69 class TestConfig(BaseConfig): 70 TESTING = True 71 72 73 74 对于上面两种方式导入配置文件,配置文件中的配置项必须大写(In both cases (loading from any Python file or loading from modules), 75 only uppercase keys are added to the config. This makes it possible to use lowercase values in the config file for temporary values that are not added to the config or to define the config keys in the same file that implements the application.) 76 77 方式3:app.config.from_envvar('YOURAPPLICATION_SETTINGS') 78 第三种方式官方解释:In this case before launching the application you have to set this environment variable to the file you want to use. On Linux and OS X 79 use the export statement:: 80 export YOURAPPLICATION_SETTINGS='/path/to/config/file' 81 82 On windows use `set` instead. 83 84 85 86
1 # 请求相关信息 2 # request.method 3 # request.access_route 4 # request.args 5 # request.form 6 # request.data 7 # request.values 8 # request.cookies 9 # request.headers 10 # request.path 11 # request.view_args 12 # request.full_path 13 # request.query_string 14 # request.url 15 # request.base_url 16 # request.url_root 17 # request.host_url 18 # request.host 19 # request.files 20 # obj = request.files['upload_file_name'] 21 # obj.save('/opt/files/' + secure_filename(f.filename)) 22 23 # 响应相关信息 24 # return "字符串" 25 # return render_template('html模板路径',**{}) 26 # return redirect('/index.html') 27 28 # response = make_response(render_template('index.html')) 29 # response.delete_cookie('key') 30 # response.set_cookie('key', 'value') 31 # response.headers['X-Something'] = 'A value' 32 # return response 33 34 #return jsonify(username=g.user.username, 35 email=g.user.email, 36 id=g.user.id)
from flask import Flask, views app = Flask(__name__) def superuser_required(func): def inner(*args, **kwargs): print('before request') result = func(*args, **kwargs) print('after request') return result return inner class CountAPI(views.MethodView): methods = ['GET', 'POST'] decorators = [superuser_required] def get(self): print('request runing') return "Hello GET request" def post(self): pass app.add_url_rule('/count', view_func=CountAPI.as_view('api')) if __name__ == '__main__': app.run()
1 作用:请求分发、自定义静态文件路径 2 3 定义蓝图: 4 from flask import Blueprint 5 sales = Blueprint('c2', __name__, url_prefix='/sales') 6 7 BluePrint构造函数: 8 def __init__(self, name, import_name, static_folder=None, 9 static_url_path=None, template_folder=None, 10 url_prefix=None, subdomain=None, url_defaults=None, 11 root_path=None): 12 _PackageBoundObject.__init__(self, import_name, template_folder, 13 root_path=root_path) 14 self.name = name 15 self.url_prefix = url_prefix 16 self.subdomain = subdomain 17 self.static_folder = static_folder 18 self.static_url_path = static_url_path 19 self.deferred_functions = [] 20 if url_defaults is None: 21 url_defaults = {} 22 self.url_values_defaults = url_defaults 23 24 注册蓝图: 25 app = Flask(__name__) 26 app.register_blueprint(sales)
from flask import Flask app = Flask(__name__) @app.before_first_request # 程序程序后,只有第一次请求进来会执行一次 def before_first(): print('before_first') @app.before_request # def before_request(): print('before_request') @app.after_request def after_request(response): print('after request') return response @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404
1 from flask import Flask 2 3 app = Flask(__name__) 4 5 6 class MiddleWare: 7 def __init__(self, wsgi_app): 8 self.wsgi = wsgi_app 9 10 def __call__(self, environ, start_response): 11 print('request coming') 12 obj = self.wsgi(environ, start_response) 13 print('request end') 14 return obj 15 16 if __name__ == '__main__': 17 app.wsgi_app = MiddleWare(app.wsgi_app) 18 app.run()
1 pipreqs :自动发现项目依赖模块&版本 2 安装: pip install pipreqs 3 生成依赖文件: pipreqs . 会自动生成一个文件(requirements.txt) 4 安装依赖文件:pip3 install -r requirements.txt #会自动安装requirements.txt 中的package
flask插件:http://flask.pocoo.org/extensions/
learn a little every day