flask
Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后触发Flask框架,开发人员基于Flask框架提供的功能对请求进行相应的处理,并返回给用户,如果要返回给用户复杂的内容时,需要借助jinja2模板来实现对模板的处理,即:将模板和数据进行渲染,将渲染后的字符串返回给用户浏览器。
“微”(micro) 并不表示你需要把整个 Web 应用塞进单个 Python 文件(虽然确实可以 ),也不意味着 Flask 在功能上有所欠缺。微框架中的“微”意味着 Flask 旨在保持核心简单而易于扩展。Flask 不会替你做出太多决策——比如使用何种数据库。而那些 Flask 所选择的——比如使用何种模板引擎——则很容易替换。除此之外的一切都由可由你掌握。如此,Flask 可以与您珠联璧合。
默认情况下,Flask 不包含数据库抽象层、表单验证,或是其它任何已有多种库可以胜任的功能。然而,Flask 支持用扩展来给应用添加这些功能,如同是 Flask 本身实现的一样。众多的扩展提供了数据库集成、表单验证、上传处理、各种各样的开放认证技术等功能。Flask 也许是“微小”的,但它已准备好在需求繁杂的生产环境中投入使用。
一般情况下使用pycharm可直接创建flask项目
也可使用命令 pip install Flask
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 from werkzeug.wrappers import Request, Response 4 5 @Request.application 6 def hello(request): 7 return Response('Hello World!') 8 9 if __name__ == '__main__': 10 from werkzeug.serving import run_simple 11 run_simple('localhost', 4000, hello)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from flask import Flask 2 app = Flask(__name__) 3 4 @app.route("/") 5 def hello(): 6 return "Hello World!" 7 8 if __name__ == "__main__": 9 app.run()
一、路由系统
- @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, } # 对于Flask默认不支持直接写正则表达式的路由,不过可以通过自定义来实现
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
通过运行如下代码: from flask import Flask from pprint import pprint if __name__ == '__main__': app = Flask(__name__) pprint(app.url_map.converters) 可以获取Flask默认支持的转换器: {'any': <class 'werkzeug.routing.AnyConverter'>, 'default': <class 'werkzeug.routing.UnicodeConverter'>, 'float': <class 'werkzeug.routing.FloatConverter'>, 'int': <class 'werkzeug.routing.IntegerConverter'>, 'path': <class 'werkzeug.routing.PathConverter'>, 'string': <class 'werkzeug.routing.UnicodeConverter'>} 那如何创建一个新的路由解析转化器呢? 在Flask的app.py里有个简单的例子,这个例子是创建了一个list类型的路由转换器: from werkzeug.routing import BaseConverter class ListConverter(BaseConverter): def to_python(self, value): return value.split(',') def to_url(self, values): return ','.join(BaseConverter.to_url(value) for value in values) app = Flask(__name__) app.url_map.converters['list'] = ListConverter 那么我们可以容易创建一个正则解析器,因为之前的转换器最终也是转换成正则的,只需要将获取的值设置为regex属性就可以使用了: from flask import Flask from werkzeug.routing import BaseConverter class RegexConverter(BaseConverter): def __init__(self, map, *args): self.map = map self.regex = args[0] app = Flask(__name__) app.url_map.converters['regex'] = RegexConverter @app.route('/view/<regex("[a-zA-Z0-9]+"):uuid>/') def view(uuid): """ url: /view/1010000000125259/ result: view uuid:1010000000125259 """ return "view uuid: %s" % (uuid) @app.route('/<regex(".*"):url>') def not_found(url): """ url: /hello result: not found: 'hello' """ return "not found: '%s'" % (url) if __name__ == '__main__': app.run()
二、模板
1、模板的使用
Flask使用的是Jinja2模板,所以其语法和Django无差别
2、自定义模板方法
Flask中自定义模板方法的方式和Bottle相似,创建一个函数并通过参数的形式传入render_template
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <h1>自定义函数</h1> {{ww()|safe}} </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
三、公共组件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # 对于Http请求,Flask会讲请求信息封装在request中(werkzeug.wrappers.BaseRequest),提供的如下常用方法和字段以供使用 2 request.method 3 request.args 4 request.form 5 request.values 6 request.files 7 request.cookies 8 request.headers 9 request.path 10 request.full_path 11 request.script_root 12 request.url 13 request.base_url 14 request.url_root 15 request.host_url 16 request.host
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 @app.route('/login', methods=['POST', 'GET']) 2 def login(): 3 error = None 4 if request.method == 'POST': 5 if valid_login(request.form['username'], 6 request.form['password']): 7 return log_the_user_in(request.form['username']) 8 else: 9 error = 'Invalid username/password' 10 # the code below is executed if the request method 11 # was GET or the credentials were invalid 12 return render_template('login.html', error=error)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from flask import request 2 from werkzeug import secure_filename 3 4 @app.route('/upload', methods=['GET', 'POST']) 5 def upload_file(): 6 if request.method == 'POST': 7 f = request.files['the_file'] 8 f.save('/var/www/uploads/' + secure_filename(f.filename)) 9 ...
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from flask import request 2 3 @app.route('/setcookie/') 4 def index(): 5 username = request.cookies.get('username') 6 # use cookies.get(key) instead of cookies[key] to not get a 7 # KeyError if the cookie is missing. 8 9 10 11 12 from flask import make_response 13 14 @app.route('/getcookie') 15 def index(): 16 resp = make_response(render_template(...)) 17 resp.set_cookie('username', 'the username') 18 return resp
-----------------------------------------------------------------------------------------------------
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # 当用户请求被开发人员的逻辑处理完成之后,会将结果发送给用户浏览器,那么就需要对请求做出相应的响应。 2 a.字符串 3 4 @app.route('/index/', methods=['GET', 'POST']) 5 def index(): 6 return "index" 7 b.模板引擎 8 9 from flask import Flask,render_template,request 10 app = Flask(__name__) 11 12 @app.route('/index/', methods=['GET', 'POST']) 13 def index(): 14 return render_template("index.html") 15 16 app.run() 17 c.重定向 18 19 #!/usr/bin/env python 20 # -*- coding:utf-8 -*- 21 from flask import Flask, redirect, url_for 22 app = Flask(__name__) 23 24 @app.route('/index/', methods=['GET', 'POST']) 25 def index(): 26 # return redirect('/login/') 27 return redirect(url_for('login')) 28 29 @app.route('/login/', methods=['GET', 'POST']) 30 def login(): 31 return "LOGIN" 32 33 app.run() 34 d.错误页面 35 36 from flask import Flask, abort, render_template 37 app = Flask(__name__) 38 39 @app.route('/e1/', methods=['GET', 'POST']) 40 def index(): 41 abort(404, 'Nothing') 42 app.run() 43 44 45 from flask import Flask, abort, render_template 46 app = Flask(__name__) 47 48 @app.route('/index/', methods=['GET', 'POST']) 49 def index(): 50 return "OK" 51 52 @app.errorhandler(404) 53 def page_not_found(error): 54 return render_template('page_not_found.html'), 404 55 56 app.run() 57 e.设置相应信息 58 59 使用make_response可以对相应的内容进行操作 60 61 from flask import Flask, abort, render_template,make_response 62 app = Flask(__name__) 63 64 @app.route('/index/', methods=['GET', 'POST']) 65 def index(): 66 response = make_response(render_template('index.html')) 67 # response是flask.wrappers.Response类型 68 # response.delete_cookie 69 # response.set_cookie 70 # response.headers['X-Something'] = 'A value' 71 return response 72 73 app.run()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # 除请求对象之外,还有一个 session 对象。它允许你在不同请求间存储特定用户的信息。它是在 Cookies 的基础上实现的,并且对 Cookies 进行密钥签名要使用会话,你需要设置一个密钥。 2 3 # 设置:session['username'] = 'xxx' 4 5 # 删除:session.pop('username', None) 6 7 8 9 from flask import Flask, session, redirect, url_for, escape, request 10 11 app = Flask(__name__) 12 13 @app.route('/') 14 def index(): 15 if 'username' in session: 16 return 'Logged in as %s' % escape(session['username']) 17 return 'You are not logged in' 18 19 @app.route('/login', methods=['GET', 'POST']) 20 def login(): 21 if request.method == 'POST': 22 session['username'] = request.form['username'] 23 return redirect(url_for('index')) 24 return ''' 25 <form action="" method="post"> 26 <p><input type=text name=username> 27 <p><input type=submit value=Login> 28 </form> 29 ''' 30 31 @app.route('/logout') 32 def logout(): 33 # remove the username from the session if it's there 34 session.pop('username', None) 35 return redirect(url_for('index')) 36 37 # set the secret key. keep this really secret: 38 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # message是一个基于Session实现的用于保存数据的集合,其特点是:使用一次就删除 2 3 # index.html 4 5 <!DOCTYPE html> 6 <html> 7 <head lang="en"> 8 <meta charset="UTF-8"> 9 <title></title> 10 </head> 11 <body> 12 {% with messages = get_flashed_messages() %} 13 {% if messages %} 14 <ul class=flashes> 15 {% for message in messages %} 16 <li>{{ message }}</li> 17 {% endfor %} 18 </ul> 19 {% endif %} 20 {% endwith %} 21 </body> 22 </html> 23 24 25 26 #view.py 27 from flask import Flask, flash, redirect, render_template, request 28 29 app = Flask(__name__) 30 app.secret_key = 'some_secret' 31 32 @app.route('/') 33 def index1(): 34 return render_template('index.html') 35 36 @app.route('/set') 37 def index2(): 38 v = request.args.get('p') 39 flash(v) 40 return 'ok' 41 42 if __name__ == "__main__": 43 app.run()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from flask import Flask, flash, redirect, render_template, request 2 3 app = Flask(__name__) 4 app.secret_key = 'some_secret' 5 6 @app.route('/') 7 def index1(): 8 return render_template('index.html') 9 10 @app.route('/set') 11 def index2(): 12 v = request.args.get('p') 13 flash(v) 14 return 'ok' 15 16 class MiddleWare: 17 def __init__(self,wsgi_app): 18 self.wsgi_app = wsgi_app 19 20 def __call__(self, *args, **kwargs): 21 22 return self.wsgi_app(*args, **kwargs) 23 24 if __name__ == "__main__": 25 app.wsgi_app = MiddleWare(app.wsgi_app) 26 app.run(port=9999)
其他
http://docs.jinkan.org/docs/flask/
http://flask.pocoo.org/