flask之配置文件的加载和动态url的使用

七行代码实现一个flask app

from flask import Flask

app = Flask(__name__)

@app.route('/')
def helloworld():
    return 'helloworld'


if __name__ == '__main__':
    app.run()

app.run()只适合调试,不适合生产环境使用,生产环境应该使用Gunicorn和uWSGI启动


配置管理

  • app.config是flask.config.Config类的实例,该类继承自Python内置数据结构dict,可以使用dict的方式添加配置

    1. app.config['DEBUG']=True
    2. 使用update方法
        app.config.update(
        DEBUG=True,
        SECREY_KEY='HELLOWORLD',
        )
    
  • 一般项目的配置都统一放在一个settings.py文件中,可以集中管理配置项

   # settings.py
   class Develop():
       DEBUG = True

   class Product():

       DEBUG = False

   develop = Develop()

   product = Product()
   # app.py
   from flask import Flask
   from settings import develop,product

   app = Flask(__name__)

   app.config.from_object(product)
  • 通过文件名加载,了解即可
    • app.config.from_pyfile('settings.py',slient=True)
  • 通过环境变量加载,了解即可
    • app.config.from_envvar('settings_path')

动态url的配置

  • flask中定义了url转换器converter,在使用时需要实际特殊字段标记
  • <name>不指定参数类型or<converter_name:name>指定参数类型
@app.route('/item/<id>/')
def detali(id):
    return id

自定义url转换器

  • 继承自BaseConverter
   from werkzeug.routing import BaseConverter

   class CustomConverter(BaseConverter):
       def __init__(self,url_map,regex):
           super(CustomConverter, self).__init__(url_map)
           self.regex = regex
  • 使用
   from utils.custom_converter import CustomConverter

   app = Flask(__name__)

   app.config.from_object(develop)
   app.url_map.converters['re'] = CustomConverter # 添加到converter列表中

   @app.route('/hello/<re("[1-9]{2}"):cus>/') # re("regex") 定义匹配规则
   def custom(cus):
       return cus

posted @ 2018-06-10 12:27  Gary556  阅读(815)  评论(0)    收藏  举报