pip3 install flask
短小精悍、可扩展强 的一个Web框架。
依赖wsgi:werkzurg
werkzurg:
示例一:
from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple
def run(environ,start_response):
return [b"asdfasdf"]
if __name__ == '__main__':
run_simple('localhost', 4000, run)
示例二:
from werkzeug.wrappers import Request, Response
@Request.application
def hello(request):
return Response('Hello World!')
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple('localhost', 4000, hello)
from flask import Flask
app = Flask(__name__)
@app.route('/index')
def index():
return "Hello World"
if __name__='__main__':
app.run()
app.config.from_object("settings.DevelopmentConfig")
class Config(object):
DEBUG = False
TESTING = False
DATABASE_URI = 'sqlite://:memory:'
class ProductionConfig(Config):
DATABASE_URI = 'mysql://user@localhost/foo'
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
TESTING = True
@app.route('/index/',methods=['GET','POST'])
def index(nid):
print(nid)
return "Index"
# 请求相关信息
# 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 “asdf”
return jsonify({'k1':'v1'})
return render_template('xxx.html')
return redirect()
定制响应头:
obj = make_response("asdf")
obj.headers['xxxxxxx'] = '123'
obj.set_cookie('key', 'value')
return obj
render_template('index.html',stu_dic=STUDENT_DICT)
版本二:
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',stu_dic=STUDENT_DICT)
应用场景:比较少的函数中需要额外添加功能。
版本三: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 sb(a1, a2):
# {{sb(1,9)}}
return a1 + a2
@app.template_filter()
def db(a1, a2, a3):
# {{ 1|db(2,3) }}
return a1 + a2 + a3
Title
模板
{% block content %}{% endblock %}
tpl.html
{% extends "layout.html"%}
{% block content %}
{{users.0}}
{% endblock %}
- include
{% include "form.html" %}
form.html
- 宏
{% macro ccccc(name, type='text', value='') %}
宏
{% endmacro %}
{{ ccccc('n1') }}
{{ ccccc('n2') }}
当请求刚到来:flask读取cookie中session对应的值:eyJrMiI6NDU2LCJ1c2VyIjoib2xkYm95,将该值解密并反序列化成字典,放入内存以便视图函数使用。
视图函数:
@app.route('/ses')
def ses():
session['k1'] = 123
session['k2'] = 456
del session['k1']
return "Session"
session['xxx'] = 123
session['xxx']
当请求结束时,flask会读取内存中字典的值,进行序列化+加密,写入到用户cookie中。
from flask import Flask,flash,get_flashed_messages
@app.route('/page1')
def page1():
flash('临时数据存储','error')
flash('sdfsdf234234','error')
flash('adasdfasdf','info')
return "Session"
@app.route('/page2')
def page2():
print(get_flashed_messages(category_filter=['error']))
return "Session"
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()
1. before_request
2. after_request
示例:
from flask import Flask
app = Flask(__name__)
@app.before_request
def x1():
print('before:x1')
return '滚'
@app.before_request
def xx1():
print('before:xx1')
@app.after_request
def x2(response):
print('after:x2')
return response
@app.after_request
def xx2(response):
print('after:xx2')
return response
@app.route('/index')
def index():
print('index')
return "Index"
@app.route('/order')
def order():
print('order')
return "order"
if __name__ == '__main__':
app.run()
3. before_first_request
from flask import Flask
app = Flask(__name__)
@app.before_first_request
def x1():
print('123123')
@app.route('/index')
def index():
print('index')
return "Index"
@app.route('/order')
def order():
print('order')
return "order"
if __name__ == '__main__':
app.run()
4. template_global
5. template_filter
6. errorhandler
@app.errorhandler(404)
def not_found(arg):
print(arg)
return "没找到"