Flask 路由,配置,蓝图

2022-10-12,,,

路由

  1. # -*- coding: utf-8 -*-  

  2. from flask import flask, url_for  

  3.     
     
  4. app = flask(__name__)  

  5.     
     
  6.     
     
  7. @app.route('/index/<int:year>/<string:mon>', endpoint='index'defaults={"name": 'peach', },  

  8.            strict_slashes=falseredirect_to='https://www.baidu.com/')  

  9. def index(name, year, mon):  

  10.     """  

  11.     endpoint:                        相当于url_for,默认函数的名, url_for 反向地址,通过视图函数名,或者endpoint 解析出对应的url  

  12.     defaults                       设置默认参数  name  

  13.     strict_slashes                 严格匹配路径  

  14.     redirect_to                    永久重定向,301 不经过视图函数,302重定向是经过视图函数  

  15.     /index/<int:year>/<string:mon> 动态路由参数,数字可以转字符串字符串不能转数字  

  16.     :return:  

  17.     """  

  18.     return 'index'  

  19.     
     
  20.     
     
  21. app.run(host='0.0.0.0'debug=true)

 
 

实例化配置

  1. # -*- coding: utf-8 -*-  

  2. from flask import flask, render_template  

  3.     
     
  4. app = flask(__name__,  

  5.             template_folder='templates',  # 默认模板路径  

  6.             static_folder='statics',  # 设置静态目录,默认是前面加个/, /statics  

  7.             static_url_path='/static', # 静态目录访问路径,这个意思是,访问它就是访问静态目录,必须带/ == "/" + static_folder  

  8.             )  

  9.     
     
  10. app.config['debug'] = true  

  11.     
     
  12.     
     
  13. @app.route('/')  

  14. def index():  

  15.     return render_template('index2.html')  

  16.     
     
  17.     
     
  18. app.run(host='0.0.0.0')  

 
 

其他配置

  1. static_folder = 'static',     # 静态文件目录的路径 默认当前项目中的static目录  

  2. static_host = none,           # 远程静态文件所用的host地址,默认为空  

  3. static_url_path = none,       # 静态文件目录的url路径 默认不写是与static_folder同名,远程静态文件时复用  

  4.     
     
  5. # host_matching是否开启host主机位匹配,是要与static_host一起使用,如果配置了static_host, 则必须赋值为true  

  6. 这里要说明一下,@app.route("/",host="localhost:5000"就必须要这样写  

  7. host="localhost:5000" 如果主机头不是 localhost:5000 则无法通过当前的路由  

  8.     
     
  9. host_matching = false,            # 如果不是特别需要的话,慎用,否则所有的route 都需要host=""的参数  

  10. subdomain_matching = false,       # 理论上来说是用来限制server_name子域名的,但是目前还没有感觉出来区别在哪里  

  11. template_folder = 'templates'     # template模板目录默认当前项目中的 templates 目录  

  12. instance_path = none,             # 指向另一个flask实例的路径  

  13. instance_relative_config = false  # 是否加载另一个实例的配置  

  14. root_path = none                  # 主模块所在的目录的绝对路径,默认项目目录 

 
 

对象配置

  1. # -*- coding: utf-8 -*-  

  2. from flask import flask  

  3. app = flask(__name__)  

  4.     
     
  5. 对象配置  

  6. app.secret_key = 'ytyttyt'  

  7. app.config['secret_key'] = 'frfrvr'  

  8. app.config['debug'] = true  

  9.     
     
  10. @app.route('/')  

  11. def index():  

  12.     return 'index'  

  13.     
     
  14. app.run(host='0.0.0.0'

 
 

配置参数

  1. {  

  2.     'debug': false,                      # 是否开启debug模式  

  3.     'testing': false,                    # 是否开启测试模式  

  4.     'propagate_exceptions': none,        # 异常传播(是否在控制台打印log) debug或者testing开启后,自动为true  

  5.     'preserve_context_on_exception': none,  # 一两句话说不清楚,一般不用它  

  6.     'secret_key': none,                  # 之前遇到过,在启用内置session的时候/flash闪现的时候,一定要有它  

  7.     'permanent_session_lifetime': 31,    # days , session的生命周期()默认31  

  8.     'use_x_sendfile': false,             # 是否弃用 x_sendfile  

  9.     'logger_name': none,                 # 日志记录器的名称  

  10.     'logger_handler_policy': 'always',  

  11.     'server_name': none,                 # 服务访问域名  

  12.     'application_root': none,            # 项目的完整路径  

  13.     'session_cookie_name': 'session',    # cookies中存放session加密字符串的名字  

  14.     'session_cookie_domain': none,       # 在哪个域名下会产生session记录在cookies  

  15.     'session_cookie_path': none,         # cookies的路径  

  16.     'session_cookie_httponly': true,     # 控制 cookie 是否应被设置 httponly 的标志,  

  17.     'session_cookie_secure': false,      # 控制 cookie 是否应被设置安全标志  

  18.     'session_refresh_each_request': true,  # 这个标志控制永久会话如何刷新  

  19.     'max_content_length': none,          # 如果设置为字节数, flask 会拒绝内容长度大于此值的请求进入,并返回一个 413 状态码  

  20.     'send_file_max_age_default': 12,     # hours 默认缓存控制的最大期限  

  21.     'trap_bad_request_errors': false,  

  22.     # 如果这个值被设置为 true flask不会执行 http 异常的错误处理,而是像对待其它异常一样,  

  23.     # 通过异常栈让它冒泡地抛出。这对于需要找出 http 异常源头的可怕调试情形是有用的。  

  24.     
     
  25.     'trap_http_exceptions': false,  

  26.     # werkzeug 处理请求中的特定数据的内部数据结构会抛出同样也是"错误的请求"异常的特殊的 key errors   

  27.     # 同样地,为了保持一致,许多操作可以显式地抛出 badrequest 异常。  

  28.     # 因为在调试中,你希望准确地找出异常的原因,这个设置用于在这些情形下调试。  

  29.     # 如果这个值被设置为 true ,你只会得到常规的回溯。  

  30.     
     
  31.     'explain_template_loading': false,  

  32.     'preferred_url_scheme': 'http',       # 生成url的时候如果没有可用的 url 模式话将使用这个值  

  33.     'json_as_ascii': true,  

  34.     # 默认情况下 flask 使用 ascii 编码来序列化对象。如果这个值被设置为 false   

  35.     # flask不会将其编码为 ascii,并且按原样输出,返回它的 unicode 字符串。  

  36.     # 比如 jsonfiy 会自动地采用 utf-8 来编码它然后才进行传输。  

  37.     
     
  38.     'json_sort_keys': true,  

  39.     #默认情况下 flask 按照 json 对象的键的顺序来序来序列化它。  

  40.     # 这样做是为了确保键的顺序不会受到字典的哈希种子的影响,从而返回的值每次都是一致的,不会造成无用的额外 http 缓存。  

  41.     # 你可以通过修改这个配置的值来覆盖默认的操作。但这是不被推荐的做法因为这个默认的行为可能会给你在性能的代价上带来改善。  

  42.     
     
  43.     'jsonify_prettyprint_regular': true,  

  44.     'jsonify_mimetype': 'application/json',  

  45.     'templates_auto_reload': none,  

  46. }  

通过对象进行配置

  1. # -*- coding: utf-8 -*-  

  2. class flaskdebug(object):  

  3.     debug = true  

  4.     secret_key = 'debug_key_gtgrgtrg'  

  5.     session_cookie_name = 'debug_session'  

  6.     
     
  7.     
     
  8. class flasktseting(object):  

  9.     testing = true  

  10.     secret_key = 'testing_key_gtgrgtrg'  

  11.     permanent_session_lifetime = 15  

  12.     session_cookie_name = 'testing_session'

 
 

  1. # -*- coding: utf-8 -*-  

  2. from flask import flask  

  3. from flasksetting import flaskdebug, flasktseting  

  4. app = flask(__name__)  

  5.     
     
  6. 类的方式对象配置  

  7. app.config.from_object(flaskdebug)  

  8.     
     
  9. @app.route('/')  

  10. def index():  

  11.     return 'index'  

  12.     
     
  13. app.run(host='0.0.0.0')

 
 

flash闪现

  1. @app.route('/')  

  2. def index():  

  3.     flash('闪现', 'tag')   # tag 闪现命名  

  4.     flash('闪现2', 'tag2')  # tag 闪现命名  

  5.     return 'index'  

  6.     
     
  7.     
     
  8. @app.route('/index2')  

  9. def index2():  

  10.     # print(get_flashed_messages(category_filter='tag2'))  # flash  

  11.     print(get_flashed_messages(category_filter=['tag','tag2']))  # flash  

  12.     return 'index2' 

 
 

蓝图

注册蓝图

  1. # -*- coding: utf-8 -*-  

  2. from flask import flask  

  3. from blue_11 import views  # 导入定义的蓝图视图  

  4. app = flask(__name__, template_folder="apptmp")  # 指定tmp路径  

  5.     
     
  6. app.register_blueprint(views.app, url_prefix='/blue')  # 注册蓝图, url前缀在视图里面和这里写一个即可  

  7.                                                        # 两边都写以注册的为准  

  8.     
     
  9. app.run(host='0.0.0.0'debug=true

蓝图views

  1. # -*- coding: utf-8 -*-  

  2. from flask import blueprint, render_template  

  3.     
     
  4. app = blueprint('app', __name__,  

  5.                 url_prefix='/blue',)  # url前缀  

  6.     
     
  7. @app.route('/')  

  8. def index():  

  9.     return render_template('apptmp.html')  

《Flask 路由,配置,蓝图.doc》

下载本文的Word格式文档,以方便收藏与打印。