Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的微型框架。
对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后触发Flask框架。
开发人员基于Flask框架提供的功能对请求进行相应的处理,并返回给用户,如果要返回给用户复杂的内容时,需要借助jinja2模板来实现对模板的处理
即:将模板和数据进行渲染,将渲染后的字符串返回给用户浏览器。
“微”(micro) 并不表示你需要把整个 Web 应用塞进单个 Python 文件(虽然确实可以 ),也不意味着 Flask 在功能上有所欠缺。
微框架中的“微”意味着 Flask 旨在保持核心简单而易于扩展
pip3 install -i https://pypi.doubanio.com/simple/ --trusted-host pypi.doubanio.com flask
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('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run()
""" 一 Flask参数 import_name, # 起一个名字,__name__,不会重名 static_path=None, # 即将废弃 static_url_path=None, # 静态文件前缀,/staticss static_folder='static', # 静态文件路径 template_folder='templates', # 模板路径 instance_path=None, # instance_relative_config=True时,寻找的目录 instance_relative_config=False, # True时,影响配置文件目录 root_path=None # None时,根目录找配置文件 """
二 配置文件
1. 配置基础
config 实际上继承于字典,并且可以像修改字典一样修改它
app = Flask(__name__) app.config['DEBUG'] = True
给定的配置值会被推送到 Flask 对象中,所以你可以在那里读写它们:
app.debug = True
你可以使用 dict.update() 方法来一次性更新多个键:
app.config.update( DEBUG=True, SECRET_KEY='...' )
{ '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, }
2. 从文件中读配置
app.config.from_pyfile('settings.py') app.config.from_envvar("环境变量名称") app.config.from_json("json文件名称") app.config.from_mapping({'DEBUG':True}) app.config.from_object("python类或类的路径")
配置文件 settings.py
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.config.from_object("settings.TestingConfig") @app.route('/') def hello_world(): print(app.testing) return 'Hello World!'
三 路由系统
-
@app.route('/user/<username>')
-
@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, }
from flask import Flask, render_template app = Flask(__name__) # 1. 简单示例 @app.route('/') def hello_world(): return 'Hello World!!!' # 2. 模板示例 @app.route('/template') def template(): return render_template('hello.html') # 3. 路由的另外写法 def hello(): from flask import url_for url = url_for('reverse_hello') print(url) # /hello return 'Hello World!' app.add_url_rule('/hello', view_func=hello, endpoint='reverse_hello', methods=['GET', 'POST']) # /hello,url地址 # view_func,视图函数 # endpoint用来反向解析url,默认函数名 # methods = ['GET', 'POST'] # 4. 路由传递参数,<类型:变量名>,那对应的函数也要定义变量等待传值 @app.route('/edit/<int:nid>') def edit(nid): return 'edit:<%s>' % nid if __name__ == '__main__': app.run()
from flask import Flask, views app = Flask(__name__) # 定义装饰器,注意装饰器的顺序 def auth(func): def inner(*args, **kwargs): print('before') res = func(*args, **kwargs) print('after') return res return inner @app.route('/') @auth # hello=auth(hello),加了装饰器之后,其实调用的是闭合函数inner def hello(): return 'Hello World!!!' # Class Base View class IndexView(views.MethodView): methods = ['GET', 'POST'] decorators = [auth, ] def get(self): return 'IndexView.Get' def post(self): return 'IndexView.POST' app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name就是endpoint if __name__ == '__main__': app.run()
from flask import Flask, views app = Flask(__name__) def index(): return 'Hello Index!' app.add_url_rule('/index', view_func=index) @app.route('/hello', defaults={'k1': 'v1'}, strict_slashes=False) def hello(k1): return 'Hello {}'.format(k1) @app.route('/index_old', redirect_to='/index') def index_old(): return 'Hello old friends!' @app.route('/backend',subdomain='admin') # 待测试 def backend(): return '欢迎登陆管理后台' ''' rule, URL规则 view_func, 视图函数名称 defaults=None, 默认值,当URL中无参数,函数需要参数时,使用defaults={'k':'v'}为函数提供参数 endpoint=None, 名称,用于反向生成URL,即: url_for('名称') methods=None, 允许的请求方式,如:["GET","POST"] strict_slashes=True, 对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, 重定向到指定地址 subdomain=None, 子域名访问,需配置 app.config['SERVER_NAME'] = 'localhost:5000' 访问地址就可为,http://admin.localhost:5000/backend 注意localhost指向相应ip 实际场景用DNS来区分子域名 ''' if __name__ == '__main__': app.run()
from flask import Flask, views, url_for from werkzeug.routing import BaseConverter app = Flask(import_name=__name__) class RegexConverter(BaseConverter): # 自定义URL匹配正则表达式 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): # 使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数 val = super(RegexConverter, self).to_url(value) return val # 添加到Flask中 app.url_map.converters['regex'] = RegexConverter @app.route('/index/<regex("d+"):nid>') def index(nid): print(url_for('index', nid='888')) # /index/888 return 'Index' if __name__ == '__main__': app.run()
四 模板
1、模板的使用
Flask使用的是Jinja2模板,所以其语法和Django无差别
2、自定义模板方法
Flask中自定义模板方法的方式和Bottle相似,创建一个函数并通过参数的形式传入render_template,如:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <h1>自定义函数</h1> {{func()|safe}} </body> </html>
from flask import Flask,render_template app = Flask(__name__) def func(): return '<h1>Hello World</h1>' @app.route('/login', methods=['GET', 'POST']) def login(): return render_template('login.html', func=func) app.run()
五 请求和响应
直接导入request对象,数据已封装在内
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 # 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 return "内容" if __name__ == '__main__': app.run()
from flask import (Flask, request, render_template, redirect, url_for, make_response) app = Flask(__name__) @app.route('/') def index(): # 请求信息 print(request.method) # 请求方法 print(request.args) # GET传递参数 print(request.form) # POST传递参数 print(request.cookies) # Cookie,字典形式 print(' ') print(request.headers) # 定义好含义的报头 print(' ') print(request.files) # obj = request.files['the_file_name'],obj.save('/xx/xx/xx/filename') # 响应信息 return 'Hello World!' # return render_template('html模板路径', **{}) # return redirect('/detail') 或 return redirect(url_for('endpoint')) # 响应信息修改cookie,headers # response是flask.wrappers.Response类型 # response = make_response(render_template('html模板路径', **{})) # response.delete_cookie('key') # response.set_cookie('key', 'value') # response.headers['X-Something'] = 'Value' # return response if __name__ == '__main__': app.run()
六 Session
除请求对象之外,还有一个 session 对象。它允许你在不同请求间存储特定用户的信息。它是在 Cookies 的基础上实现的,并且对 Cookies 进行密钥签名要使用会话,你需要设置一个密钥。
-
设置:session['username'] = 'xxx'
- 删除:session.pop('username', None)
@app.route('/login',methods=['GET', 'POST']) def login(): if request.method == "GET": return render_template('login.html') else: user = request.form.get('username') pwd = request.form.get('password') if user == 'alex' and pwd == '123': # return redirect('http://www.baidu.com') session['user_info'] = 'alex' return redirect(url_for('index')) else: return render_template('login.html',msg="用户密码错误") @app.route('/logout', methods=['GET']) def logout(): session.pop('user_info',None) return redirect(url_for('login'))
pip3 install Flask-Session run.py from flask import Flask from flask import session from pro_flask.utils.session import MySessionInterface app = Flask(__name__) app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' app.session_interface = MySessionInterface() @app.route('/login.html', methods=['GET', "POST"]) def login(): print(session) session['user1'] = 'alex' session['user2'] = 'alex' del session['user2'] return "内容" if __name__ == '__main__': app.run() session.py #!/usr/bin/env python # -*- coding:utf-8 -*- import uuid import json from flask.sessions import SessionInterface from flask.sessions import SessionMixin from itsdangerous import Signer, BadSignature, want_bytes class MySession(dict, SessionMixin): def __init__(self, initial=None, sid=None): self.sid = sid self.initial = initial super(MySession, self).__init__(initial or ()) def __setitem__(self, key, value): super(MySession, self).__setitem__(key, value) def __getitem__(self, item): return super(MySession, self).__getitem__(item) def __delitem__(self, key): super(MySession, self).__delitem__(key) class MySessionInterface(SessionInterface): session_class = MySession container = {} def __init__(self): import redis self.redis = redis.Redis() def _generate_sid(self): return str(uuid.uuid4()) def _get_signer(self, app): if not app.secret_key: return None return Signer(app.secret_key, salt='flask-session', key_derivation='hmac') def open_session(self, app, request): """ 程序刚启动时执行,需要返回一个session对象 """ sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self._generate_sid() return self.session_class(sid=sid) signer = self._get_signer(app) try: sid_as_bytes = signer.unsign(sid) sid = sid_as_bytes.decode() except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid) # session保存在redis中 # val = self.redis.get(sid) # session保存在内存中 val = self.container.get(sid) if val is not None: try: data = json.loads(val) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid) return self.session_class(sid=sid) def save_session(self, app, session, response): """ 程序结束前执行,可以保存session中所有的值 如: 保存到resit 写入到用户cookie """ domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = json.dumps(dict(session)) # session保存在redis中 # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime) # session保存在内存中 self.container.setdefault(session.sid, val) session_id = self._get_signer(app).sign(want_bytes(session.sid)) response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure) 自定义Session
七 蓝图
蓝图用于为应用提供目录划分:
小型应用程序:示例
大型应用程序:示例
其他:
-
蓝图URL前缀:xxx = Blueprint('account', __name__,url_prefix='/xxx')
-
蓝图子域名:xxx = Blueprint('account', __name__,subdomain='admin')
# 前提需要给配置SERVER_NAME: app.config['SERVER_NAME'] = 'localhost.com:5000'
# 访问时:admin.localhost.com:5000/login.html
八 message
message是一个基于Session实现的用于保存数据的集合,其特点是:使用一次就删除。
from flask import Flask, flash, redirect, render_template, request, get_flashed_messages app = Flask(__name__) app.secret_key = 'some_secret' @app.route('/') def index1(): messages = get_flashed_messages() print(messages) return "Index1" @app.route('/set') def index2(): v = request.args.get('p') flash(v) return 'ok' if __name__ == "__main__": app.run()
九 中间件
from flask import Flask, flash, redirect, render_template, request app = Flask(__name__) app.secret_key = 'some_secret' @app.route('/') def index1(): return render_template('index.html') @app.route('/set') def index2(): v = request.args.get('p') flash(v) return 'ok' class MiddleWare: def __init__(self,wsgi_app): self.wsgi_app = wsgi_app def __call__(self, *args, **kwargs): return self.wsgi_app(*args, **kwargs) if __name__ == "__main__": app.wsgi_app = MiddleWare(app.wsgi_app) app.run(port=9999)
十 Flask插件
- Session: Flask-Session
- 表单验证:WTForms
- ORM: SQLAchemy
- 更多信息参考 http://flask.pocoo.org/extensions/
更多信息参考:http://www.cnblogs.com/wupeiqi/articles/7552008.html
Flask代码示例:https://github.com/Jonathan1314/LearnFlask