# 方式一
app.config["NNN"] = 123
# 方式二
app.config.from_pyfile("settings.py")
# 方式三
import os
os.environ["FLASK_SETTINGS"] = "settings.py"
app.config.from_envvar("FLASK_SETTINGS")
# 方式四
app.config.from_object("settings2.DevConfig")
from flask import Flask,url_for
app = Flask(__name__)
# 定义转换的类
from werkzeug.routing import BaseConverter
class RegexConverter(BaseConverter):
"""
自定义URL匹配正则表达式
"""
def __init__(self, map, regex):
super(RegexConverter, self).__init__(map)
self.regex = regex
def to_python(self, value):
"""
路由匹配时,匹配成功后传递给视图函数中参数的值
:param value:
:return:
"""
return int(value)
def to_url(self, value):
"""
使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数
:param value:
:return:
"""
val = super(RegexConverter, self).to_url(value)
return val
# 添加到converts中
app.url_map.converters['xxx'] = RegexConverter
# 进行使用
@app.route('/index/<xxx("\d+"):nid>',endpoint='xx')
def index(nid):
url_for('xx',nid=123)
return "Index"
if __name__ == '__main__':
app.run()
FBV:
@app.route('/index',endpoint='xx')
def index(nid):
url_for('xx',nid=123)
return "Index"
def index(nid):
url_for('xx',nid=123)
return "Index"
app.add_url_rule('/index',index)
CBV:
def auth(func):
def inner(*args, **kwargs):
result = func(*args, **kwargs)
return result
return inner
class IndexView(views.MethodView):
# methods = ['POST']
decorators = [auth,]
def get(self):
v = url_for('index')
print(v)
return "GET"
def post(self):
return "GET"
app.add_url_rule('/index', view_func=IndexView.as_view(name='index'))
删除:session.pop(‘username’, None)
from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
@app.route('/')
def index():
if 'username' in session:
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form action="" method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
@app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index'))
# set the secret key. keep this really secret:
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
基于Session实现的用于保存数据的集合,其特点是:使用一次就删除
@app.template_global()
def sb(a1, a2):
return a1 + a2
@app.template_filter()
def db(a1, a2, a3):
return a1 + a2 + a3
对项目目录结构规则化
manage.py
fcrm
│ __init__.py
├─static
├─templates
│ login.html
└─views
│ account.py
└─ order.py
manage.py
import fcrm # 项目文件包
if __name__ == '__main__':
fcrm.app.run(port=8001)
__init__.py
from flask import Flask
from .views import account
from .views import order
app = Flask(__name__)
print(app.root_path)
app.register_blueprint(account.account)
app.register_blueprint(order.order)
order.py
from flask import Blueprint
order = Blueprint('order',__name__)
@order.route('/order')
def login():
return 'Order'
@app.before_first_request
def before_first_request1():
print('before_first_request1')
@app.before_first_request
def before_first_request2():
print('before_first_request2')
@app.before_request
def before_request1():
Request.nnn = 123
print('before_request1')
@app.before_request
def before_request2():
print('before_request2')
@app.after_request
def after_request1(response):
print('before_request1', response)
return response
@app.after_request
def after_request2(response):
print('before_request2', response)
return response
@app.errorhandler(404)
def page_not_found(error):
return 'This page does not exist', 404
源码
def full_dispatch_request(self):
"""Dispatches the request and on top of that performs request
pre and postprocessing as well as HTTP exception catching and
error handling.
.. versionadded:: 0.7
"""
self.try_trigger_before_first_request_functions()
try:
request_started.send(self)
rv = self.preprocess_request()
if rv is None:
rv = self.dispatch_request()
except Exception as e:
rv = self.handle_user_exception(e)
return self.finalize_request(rv)