Flask是一个使用 Python 编写的轻量级 Web 应用框架。其 WSIG工具箱采用 Werkzeug ,模板引擎则使用 Jinja2 。Flask使用 BSD 授权。
Flask也被称为 “microframework” ,因为它使用简单的核心,用 extension 增加其他功能。Flask没有默认使用的数据库、窗体验证工具。
一、安装及其使用
pip install flask
1 from flask import Flask 2 app = Flask(__name__) 3 4 @app.route('/index') 5 def index(): 6 return 'Hello Flask' 7 8 if __name__ == '__mian__': 9 app.run()
二、配置文件
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 app = Flask(__name__) app.config.from_object('settings.BaseConfig')
class BaseConfig(object): DEBUG = True SECRET_KEY = 'dfaf3432iojjklfvndj=' class ProductionConfig(BaseConfig): DEBUG = False
三、路由系统
在上面一个简单的例子中我们使用了无传参的url和Django类似在url中也可以进行传参
app.route('/index/<username>') #默认传参类型为str app.route('/index/<int:post_id>') #类型为整型传参 app.route('/index/<float:post_id>') #类型为浮点型传参 app.route('/index/<path:path>') #类型是一个路径 app.route('/login', methods=['GET', 'POST']) #默认只get请求,这样就添加了POST请求
上面的路由都是根据下面的配置来进行解析的
DEFAULT_CONVERTERS = { 'default': UnicodeConverter, 'string': UnicodeConverter, 'any': AnyConverter, 'path': PathConverter, 'int': IntegerConverter, 'float': FloatConverter, 'uuid': UUIDConverter, }
路由的反向解析:url_for
from flask import Flask, url_for app = Flask(__name__) @app.route('/index') def index(): v1 = url_for('login') v2 = url_for('user') print(v1, v2) return 'ok' @app.route('/login', methods=['GET', 'POST'], endpoint='login') def login(): return '登录页面' @app.route('/user', methods=['GET', 'POST'], endpoint='user') def user(): return '用户界面' if __name__ == '__main__': app.run()
自定义URL匹配正则表达式:
from flask import Flask, render_template, redirect, url_for from werkzeug.routing import BaseConverter app = Flask(__name__) class RegexConverter(BaseConverter): def __init__(self, map, regex): super(RegexConverter, self).__init__(map) self.regex = regex def to_python(self, value): return value def to_url(self, value): val = super(RegexConverter, self).to_url(value) return val app.url_map.converters['xxx'] = RegexConverter @app.route('/index/<xxx("w+"):nid>', methods=['GET', 'POST'], endpoint='index') def index(nid): print(nid, type(nid)) v = url_for('index', nid=999) return 'Index' if __name__ == '__main__': app.run()
重定向功能:
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()
子域名
from flask import Flask,render_template,redirect app = Flask(__name__) app.config['SERVER_NAME'] = 'oldboy.com:5000' @app.route("/dynamic", subdomain="<username>") def xxxxxxx(username): print(username) return 'xxxxx' if __name__ == '__main__': app.run()
在flask中注册路由大致有两种方式FBV,CBV
1 #FBV有两种方式 2 #第一种装饰器来注册 3 @app.route('/index', methods=['GET']) 4 def index(): 5 return 'Hello Flask!' 6 7 #第二种注册方式 8 def index(): 9 return 'Hello Flask!' 10 11 app.add_url_rule('/index', view_func=index)
from Flask import views def auth(func): def inner(*args, **kwargs): print('之前做的') ret = func(*args, **kwargs) print('之后做的') return ret return inner class IndexView(views.MethodView): methods = ['GET'] decorators = [auth,] def get(self): return '这是GET方法!' def post(self): return '这是POST方法!' app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) #name为endpoint
注册url方法中的参数
@app.route和app.add_url_rule参数: rule, URL规则 view_func, 视图函数名称 defaults=None, 默认值,当URL中无参数,函数需要参数时,使用defaults={'k':'v'}为函数提供参数 endpoint=None, 名称,用于反向生成URL,即: url_for('名称') methods=None, 允许的请求方式,如:["GET","POST"] strict_slashes=None, 对URL最后的 / 符号是否严格要求, 如: @app.route('/index',strict_slashes=False), 访问 http://www.xx.com/index/ 或 http://www.xx.com/index均可 @app.route('/index',strict_slashes=True) 仅访问 http://www.xx.com/index redirect_to=None, 重定向到指定地址 如: @app.route('/index/<int:nid>', redirect_to='/home/<nid>') 或 def func(adapter, nid): return "/home/888" @app.route('/index/<int:nid>', redirect_to=func) subdomain=None, 子域名访问 from flask import Flask, views, url_for app = Flask(import_name=__name__) app.config['SERVER_NAME'] = 'wupeiqi.com:5000' @app.route("/", subdomain="admin") def static_index(): """Flask supports static subdomains This is available at static.your-domain.tld""" return "static.your-domain.tld" @app.route("/dynamic", subdomain="<username>") def username_index(username): """Dynamic subdomains are also supported Try going to user1.your-domain.tld/dynamic""" return username + ".your-domain.tld" if __name__ == '__main__': app.run() 注册url参数
四、请求和相应
from flask import Flask from flask import request from flask import render_template from flask import redirect from flask import make_response app = Flask(__name__) @app.route('/login.html', methods=['GET', "POST"]) def login(): # 请求相关信息 # request.method # 当前请求的方法(POST,GET) # request.args # GET方法传来的数据一个Multidict类型 # request.form # POST方法传来的数据一个Multidict类型 # request.values # GET, POST数据都在其中 # request.cookies # 可以去到cookie中的数据 # 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 return "内容" if __name__ == '__main__': app.run()
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
五、闪现
from flask import Flask,session,flash,get_flashed_messages app = Flask(__name__) app.secret_key = 'asdfasdfasdf' @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" if __name__ == '__main__': app.run()
存储的时候flash贴上标签,然后可以根据标签来取值