基本使用
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
配置文件
在app 中引入
app.config.from_object("settings.DevelopmentConfig")
settings
class BaseConfig(object):
DEBUG = True
SECRET_KEY = "随机字符串"
class ProductionConfig(BaseConfig):
DEBUG = False
class DevelopmentConfig(BaseConfig):
pass
class TestingConfig(BaseConfig):
pass
路由
a. 添加路由的两种方式:
from flask import Flask,render_template,redirect
app = Flask(__name__)
"""
1. 执行decorator=app.route('/index',methods=['GET','POST'])
2. @decorator
- decorator(index)
"""
# 路由方式一(*):
@app.route('/index',methods=['GET','POST'])
def index():
return "Index"
# 路由方式二:
def order():
return 'Order'
app.add_url_rule('/order',view_func=order)
if __name__ == '__main__':
app.run()
b. endpoint(默认函数名)
c. 传参数
@app.route('/index/<int:nid>',methods=['GET','POST'])
def index(nid):
print(nid,type(nid))
url_for('index',nid=888)
return "Index"
d. 自定义正则参数
from flask import Flask,render_template,redirect,url_for
from werkzeug.routing import BaseConverter
app = Flask(__name__)
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
app.url_map.converters['xxx'] = RegexConverter
@app.route('/index/<xxx("\d+"):nid>',methods=['GET','POST'])
def index(nid):
print(nid,type(nid))
v = url_for('index',nid=999) # /index/999
print(v)
return "Index"
if __name__ == '__main__':
app.run()
e. 其他参数
- 重定向
from flask import Flask,render_template,redirect
app = Flask(__name__)
@app.route('/index',methods=['GET','POST'],redirect_to='/new')
def index():
return "老功能"
@app.route('/new',methods=['GET','POST'])
def new():
return '新功能'
if __name__ == '__main__':
app.run()
PS: 前端重定向
- meta/js
重点:
- url
- methods
- endpoint
- @app.route('/index/<int:nid1>/<int:nid2>/')
- url_for
视图函数
fbv(常用)
import functools
def wapper(func):
@functools.wraps(func)
def inner(*args,**kwargs):
print('before')
return func(*args,**kwargs)
return inner
@app.route('/xxxx',methods=['GET','POST'])
@wapper
def index():
return "Index"
cbv
class IndexView(views.MethodView):
methods = ['GET']
decorators = [wapper, ]
def get(self):
return 'Index.GET'
def post(self):
return 'Index.POST'
app.add_url_rule('/index', view_func=IndexView.as_view(name='index2')) # name=endpoint
请求和响应
请求相关
request.method
request.args
request.form
request.cookies
request.headers
request.path
request.files
obj = request.files['the_file_name']
obj.save('/var/www/uploads/' + secure_filename(obj.filename))
request.values
request.full_path
request.script_root
request.url
request.base_url
request.url_root
request.host_url
request.host
响应相关
return ""
return json.dumps({}) # return jsonify({})
return render_template('index.html',n1=123)
return redirect('/index')
response = make_response(render_template('index.html'))
response = make_response("xxxx")
response.set_cookie('key', 'value')
response.headers['X-Something'] = 'A value'
response.delete_cookie('key')
return response
模板
调用方法基本和Django相同
session
- 设置:session['username'] = 'xxx'
- 删除:session.pop('username', None)
蓝图(Blueprint)
目录结构
manage.py
from s8pro import app
if __name__ == '__main__':
app.run()
init.py
from flask import Flask
from .views import account
from .views import admin
from .views import user
app = Flask(__name__)
app.register_blueprint(account.ac)
app.register_blueprint(admin.ad)
app.register_blueprint(user.us)
views 文件夹内
1.account.py
from flask import Blueprint,render_template
import redis
ac = Blueprint('ac',__name__)
@ac.route('/login')
def login():
conn = redis.Redis()
return render_template('login.html')
@ac.route('/logout')
def logout():
return '退出'
2.admin.py
from flask import Blueprint
ad = Blueprint('ad',__name__,url_prefix='/admin')
@ad.before_request
def bf():
print('before_request')
@ad.route('/home')
def home():
return 'home'
@ad.route('/xxxx')
def xxxx():
return 'xxxx'
3.user.py
from flask import Blueprint
us = Blueprint('us',__name__)
@us.route('/info')
def info():
return 'info'
前缀和子域名
蓝图URL前缀:xxx = Blueprint('account', __name__,url_prefix='/xxx')
蓝图子域名:xxx = Blueprint('account', __name__,subdomain='admin')
# 前提需要给配置SERVER_NAME: app.config['SERVER_NAME'] = 'xxx.com:5000'
# 访问时:admin.xxx.com:5000/login.html
闪现(message)
message是一个基于Session实现的用于保存数据的集合
其特点是:使用一次就删除。
@app.route('/x1',methods=['GET','POST'])
def login():
flash('我要上学校1',category='x1')
flash('我要上学校2',category='x2')
return "视图函数x1"
@app.route('/x2',methods=['GET','POST'])
def index():
data = get_flashed_messages(category_filter=['x1'])
print(data)
return "视图函数x2"
中间件
class Middleware(object):
def __init__(self,old_wsgi_app):
"""
服务端启动时,自动执行
:param old_wsgi_app:
"""
self.old_wsgi_app =old_wsgi_app
def __call__(self, environ, start_response):
"""
每次有用户请求道来时
:param args:
:param kwargs:
:return:
"""
print('before')
from flask import session,request
obj = self.old_wsgi_app(environ, start_response)
print('after')
return obj
if __name__ == '__main__':
app.wsgi_app = Middleware(app.wsgi_app)
app.run()
"""
1.执行app.__call__
2.再调用app.wsgi_app方法
"""
常见装饰器
@app.before_request 每次请求进来之前执行
@app.after_request 每次请求进来之后执行
@app.errorhandler(404) 引发404错误时候执行
@app.before_first_request 第一次请求进来之前执行(如创建数据库连接池这样的业务)
@app.template_global() 调用方法{{函数名(参数1,参数2)}}
@app.template_filter() 调用方法{{参数1|函数名(参数2,参数3))}}