Flask组件
1.配置文件
flask中的配置文件是一个flask.config.Config对象(继承字典),默认配置为:
{
'DEBUG': get_debug_flag(default=False), 是否开启Debug模式
'TESTING': False, 是否开启测试模式
'PROPAGATE_EXCEPTIONS': None,
'PRESERVE_CONTEXT_ON_EXCEPTION': None,
'SECRET_KEY': None,
'PERMANENT_SESSION_LIFETIME': timedelta(days=31),
'USE_X_SENDFILE': False,
'LOGGER_NAME': None,
'LOGGER_HANDLER_POLICY': 'always',
'SERVER_NAME': None,
'APPLICATION_ROOT': None,
'SESSION_COOKIE_NAME': 'session',
'SESSION_COOKIE_DOMAIN': None,
'SESSION_COOKIE_PATH': None,
'SESSION_COOKIE_HTTPONLY': True,
'SESSION_COOKIE_SECURE': False,
'SESSION_REFRESH_EACH_REQUEST': True,
'MAX_CONTENT_LENGTH': None,
'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),
'TRAP_BAD_REQUEST_ERRORS': False,
'TRAP_HTTP_EXCEPTIONS': False,
'EXPLAIN_TEMPLATE_LOADING': False,
'PREFERRED_URL_SCHEME': 'http',
'JSON_AS_ASCII': True,
'JSON_SORT_KEYS': True,
'JSONIFY_PRETTYPRINT_REGULAR': True,
'JSONIFY_MIMETYPE': 'application/json',
'TEMPLATES_AUTO_RELOAD': None,
}
使用方式
from flask import Flask,render_template,request,redirect,session
app = Flask(__name__,template_folder="templates",static_folder="static")
app.config.from_object('setting.Pro')
setting.py
class Base(object)
SECRET_KEY = 'myweb' class Pro(Base): DEBUG = False class Dev(Base): DEBUG = True
2.路由系统
- @app.route(‘/user/
‘) - @app.route(‘/post/int:post_id‘)
- @app.route(‘/post/float:post_id‘)
- @app.route(‘/post/path:path‘)
- @app.route(‘/login’, methods=[‘GET’, ‘POST’])使用方法
DEFAULT_CONVERTERS ={ 'default': UnicodeConverter, 'string': UnicodeConverter, 'any': AnyConverter, 'path': PathConverter, 'int': IntegerConverter, 'float': FloatConverter, 'uuid': UUIDConverter, }
app.router(endpoint=’’) 相当于django的url中得name=,,默认不写是函数名@app.route('/index.html',methods=['GET','POST'],endpoint='index') def index(): return 'Index'
url_for 相当于django的revers3.请求和响应@app.route('/index/<int:nid>',endpoint='index') 传递参数 def index(nid): return rediect (url_for('index',nid=) )反向解析带参数
- 请求相关信息
- request.method
- request.args
- request.form
- request.values
- request.cookies
- request.headers
- request.path
- request.full_path
- request.script_root
- request.url
- request.base_url
- request.url_root
- request.host_url
- request.host
- request.files
obj = request.files['the_file_name'] obj.save('/var/www/uploads/' + secure_filename(f.filename))
响应相关信息:
return “字符串”
return render_template(‘html模板路径’,**{})
return redirect(‘/index.html’)
响应头加参数:
response = make_response(render_template('index.html')
response是flask.wrappers.Response类型
response.delete_cookie('key')
response.set_cookie('key', 'value')
response.headers['X-Something'] = 'A value'
return response
4.Session
- 设置:session[‘username’] = ‘xxx’
- 删除:session.pop(‘username’, None)
- 获取 session.get(‘username’)
5.模板
Flask使用的是Jinja2模板,所以其语法和Django无差别
自定义组件,多用于多次调用
{% macro input(name, type='text', value='') %}
<input type="{{ type }}" name="{{ name }}" value="{{ value }}">
{% endmacro %}
{{ input('n1') }}
Markup等价django的mark_safe
其他extend include等与django无差异
6.请求扩展
用于少量页面添加认证后才可能访问
import functools
def auth(func):
@functools.wraps(func)
def inner(*args,**kwargs):
if not session.get('user'):
return redirect(url_for('login'))
ret = func(*args,**kwargs)
return ret
return inner
@app.route('/index')
@auth
def index():
return render_template('index.html')
before_request,用于大量页面认证后才可以访问
@app.before_request
def xxxxxx():
if request.path == '/login':
return None
if session.get('user'):
return None
return redirect('/login')
过滤
@app.template_global()
def test1(a1, a2):
return a1 + a2
@app.template_filter()
def test2(a1, a2, a3):
return a1 + a2 + a3
调用方式:
{{test1(1,2)}} {{ 1|test2(2,3)}}
7 message
message是一个基于Session实现的用于保存数据的集合,其特点是:使用一次就删除。
使用方法
flash添加
from flask import Flask, flash, get_flashed_messages
flash('临时数据存储','error')
flash('sdfsdf234234','error')
flash('adasdfasdf','info')
get_flashed_messages()获取
get_flashed_messages(category_filter=['error']) 根据分类获取
8 中间件
- call方法什么时候出发?
- 用户发起请求时,才执行。
- 任务:在执行call方法之前,做一个操作,call方法执行之后做一个操作。
class Middleware(object):
def __init__(self,old):
self.old = old
def __call__(self, *args, **kwargs):
'''''''执行前
ret = self.old(*args, **kwargs)
'''''''执行后
return ret
if __name__ == '__main__':
app.wsgi_app = Middleware(app.wsgi_app)
app.run()
9 额外装饰器
before_request 无需参数
after_request 必须要传递一个参数 要return
before_first_request 第一次请求调用
template_global
template_filter
errorhandler(404) 定制错误页面 需要传递一个参数
@app.errorhandler(404)
def not_found(arg):
print(arg)
return "not found"
Flask组件
http://www.jcwit.com/article/235/