flask的配置文件的和路由的探索

Do better / 2023-08-15 / 原文

1.配置文件

1. 配置文件方式一:只能配置debug,secret_key

from flask import Flask

app = Flask(__name__)

# 配置文件方式一.只能配置debug,secret_key
app.DEBUG = True # 页面刷新会自动重启
app.secret_key = 'abc'

@app.route('/',methods=['GET']) 
def index():
    print(app.secret_key)
    return 'hi'

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

 2. 配置文件的方式二,使用app.config 类似于django中的 settings : from djamgo.conf import settings

from flask import Flask

app = Flask(__name__)

# 配置文件的方式二,使用app.config 类似于django中的 settings : from djamgo.conf import settings
app.config['DEBUG']=True
app.config['secret_key']='abc'
# config是字典,可以使用config.updtae[{}]

@app.route('/',methods=['GET']) # 发送get请求就会执行
def index():
    print(app.config)
    return 'hi'

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

3. 配置文件的方式三,app.config.from_pyfile("py文件名称")

from flask import Flask

app = Flask(__name__)

# 配置文件的方式三,app.config.from_pyfile("py文件名称")
app.config.from_pyfile("settings.py")
# app.config.from_pyfile("dev.py") # 类似django的开发环境
# app.config.from_pyfile("pro.py") # 类似django的上线环境

@app.route('/',methods=['GET']) # 发送get请求就会执行
def index():
    print(app.config)
    return 'hi'

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

settings.py文件

DEBUG = True
SECRET_KEY = 'abc'

4. 配置文件的方式四,在settings.py中定义一个类

from flask import Flask

app = Flask(__name__)

# 配置文件的方式四,在settings.py中定义一个类
app.config.from_object('settings.DevelopmentConfig')
app.config.from_object('settings.Test')

@app.route('/',methods=['GET']) # 发送get请求就会执行
def index():
    print(app.config)
    return 'hi'

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

settings.py文件

class Test():
    DEBUG = False

class DevelopmentConfig(Test):
    DEBUG = True

 

2.路由系统

1. flask的路由是基于装饰器的

# 1 flask的路由是基于装饰器的:
# 它的参数有:rule(路径),methods:请求方式,列表

2. 转换器 (多个)

'''  string  int  path
'default':          UnicodeConverter,
'string':           UnicodeConverter,
'any':              AnyConverter,
'path':             PathConverter,
'int':              IntegerConverter,
'float':            FloatConverter,
'uuid':             UUIDConverter,
'''

 3 路由系统的本质,读源码

# @app.route('/',methods=['GET'])本质就是下面的代码注册
# 和django配置路由的方式很像
app.add_url_rule('/','index',index,defaults={'name':'jack'}) # 给出默认值
# redirect='/' 重定向
app.add_url_rule('/home','home',home,redirect='/')

 4 endpoint 不传

不传不传会以视图函数的名字作为值,但是如果加了装饰器,
所有视图函数名字都是inner,就会出错,使用wrapper装饰器再装饰装饰器