Flask框架:配置文件与路由

Posted bad-robot

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask框架:配置文件与路由相关的知识,希望对你有一定的参考价值。

1、Flask配置文件

技术分享图片
  1 import os
  2 import logging
  3 import datetime
  4 
  5 basedir = os.path.abspath(os.path.dirname(__file__))
  6 
  7 class InfoFilter(logging.Filter):
  8     def filter(self, record):
  9         """
 10         only use INFO
 11         筛选,只需要INFO级别的log
 12         :param record:
 13         :return:
 14         """
 15         if logging.INFO <= record.levelno <logging.ERROR:
 16             # 已经是INFO级别了
 17             # 然后利用父类,返回1
 18             return super().filter(record)
 19         else:
 20             return 0
 21 
 22 
 23 class BaseConfig(object):
 24     DEBUG = False
 25     TESTING = False
 26     PROPAGATE_EXCEPTIONS = None
 27     PRESERVE_CONTEXT_ON_EXCEPTION = None
 28     SECRET_KEY = None
 29     PERMANENT_SESSION_LIFETIME = datetime.timedelta(31)
 30     USE_X_SENDFILE = False
 31     LOGGER_NAME = "app"
 32     LOGGER_HANDLER_POLICY = "always"
 33     SERVER_NAME = None
 34     APPLICATION_ROOT = None
 35     SESSION_COOKIE_NAME = "session"
 36     SESSION_COOKIE_DOMAIN = None
 37     SESSION_COOKIE_PATH = None
 38     SESSION_COOKIE_HTTPONLY = True
 39     SESSION_COOKIE_SECURE = False
 40     SESSION_REFRESH_EACH_REQUEST = True
 41     MAX_CONTENT_LENGTH = None
 42     SEND_FILE_MAX_AGE_DEFAULT =  datetime.timedelta(0, 43200)
 43     TRAP_BAD_REQUEST_ERRORS = False
 44     TRAP_HTTP_EXCEPTIONS = False
 45     EXPLAIN_TEMPLATE_LOADING = False
 46     PREFERRED_URL_SCHEME = http
 47     JSON_AS_ASCII = True
 48     JSON_SORT_KEYS = True
 49     JSONIFY_PRETTYPRINT_REGULAR = True
 50     JSONIFY_MIMETYPE = application / json
 51     TEMPLATES_AUTO_RELOAD = None
 52 
 53     LOG_PATH = os.path.join(basedir, logs)
 54     LOG_PATH_ERROR = os.path.join(LOG_PATH, error.log)
 55     LOG_PATH_INFO = os.path.join(LOG_PATH, info.log)
 56     LOG_FILE_MAX_BYTES =100*1024*1024
 57     # 轮转数量是10个
 58     LOG_FILE_BACKUP_COUNT = 10
 59 
 60     @classmethod
 61     def init_app(cls, app):
 62         pass
 63 
 64 class ProductionConfig(BaseConfig):
 65     DEBUG = False
 66 
 67 class DevelopmentConfig(BaseConfig):
 68 
 69     DEBUG = True
 70     SECRET_KEY = "avafaewffewfaew"
 71 
 72     @classmethod
 73     def init_app(cls, app):
 74         # BaseConfig.init_app(app)
 75         super().init_app(app)
 76 
 77         import logging
 78         from logging.handlers import RotatingFileHandler
 79         # Formatter
 80         formatter = logging.Formatter(
 81             %(asctime)s %(levelname)s %(process)d %(thread)d 
 82             %(pathname)s %(lineno)s %(message)s)
 83 
 84         # FileHandler Info
 85         file_hander_info = RotatingFileHandler(filename=cls.LOG_PATH_INFO)
 86         file_hander_info.setFormatter(formatter)
 87         file_hander_info.setLevel(logging.INFO)
 88         info_filter = InfoFilter()
 89         file_hander_info.addFilter(info_filter)
 90         app.logger.addHandler(file_hander_info)
 91 
 92         # FileHandler Error
 93         file_hander_error = RotatingFileHandler(filename=cls.LOG_PATH_ERROR)
 94         file_hander_error.setFormatter(formatter)
 95         file_hander_error.setLevel(logging.ERROR)
 96         app.logger.addHandler(file_hander_error)
 97 
 98 
 99 
100 class TestConfig(BaseConfig):
101 
102     DEBUG = True
103 
104 config = {
105     development: DevelopmentConfig,
106     xxx: ProductionConfig,
107     testing: TestConfig,
108     default: DevelopmentConfig,
109 }
settings.py
技术分享图片
 1 from flask import Flask,Response
 2 
 3 app = Flask(__name__)
 4 app.config.from_object("settings.DevelopmentConfig")
 5 
 6 @app.route("/index/")
 7 def index():
 8     return Response("hello")
 9 
10 if __name__ == "__main__":
11     app.run()
app.py

2、Flask的路由系统

  endpoint:反向生成URL,默认是函数名

  url_for(‘endpoint‘) 或 url_for("index", nid=10)

  动态路由:

@app.route(/index/<int:nid>,methods=[GET,POST])
def index(nid):
    print(nid)
    return "Index"

 

以上是关于Flask框架:配置文件与路由的主要内容,如果未能解决你的问题,请参考以下文章

Flask框架—— 反向解析配置信息路由系统模板请求响应闪现请求扩展session

doraemon的python Flask框架 路由和配置

flask配置参数路由转换器

Flask之测试与部署

python高级之Flask框架

Flask的配置与路由