Flask是一個基於Python開發而且依賴jinja2模板和Werkzeug WSGI服務的一個微型框架,對於Werkzeug本質是Socket服務端,其用於接收http請求並對請求進行預處理,而後觸發Flask框架,開發人員基於Flask框架提供的功能對請求進行相應的處理,並返回給用戶,若是要返回給用戶複雜的內容時,須要藉助jinja2模板來實現對模板的處理,即:將模板和數據進行渲染,將渲染後的字符串返回給用戶瀏覽器。html
「微」(micro) 並不表示你須要把整個 Web 應用塞進單個 Python 文件(雖然確實能夠 ),也不意味着 Flask 在功能上有所欠缺。微框架中的「微」意味着 Flask 旨在保持核心簡單而易於擴展。Flask 不會替你作出太多決策——好比使用何種數據庫。而那些 Flask 所選擇的——好比使用何種模板引擎——則很容易替換。除此以外的一切都由可由你掌握。如此,Flask 能夠與您珠聯璧合。python
默認狀況下,Flask 不包含數據庫抽象層、表單驗證,或是其它任何已有多種庫能夠勝任的功能。然而,Flask 支持用擴展來給應用添加這些功能,如同是 Flask 自己實現的同樣。衆多的擴展提供了數據庫集成、表單驗證、上傳處理、各類各樣的開放認證技術等功能。Flask 也許是「微小」的,但它已準備好在需求繁雜的生產環境中投入使用。正則表達式
安裝數據庫
pip install Flask
werkzeug:flask
#!/usr/bin/env python # -*- coding:utf-8 -*- 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)
1、第一次segmentfault
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run()
2、路由系統瀏覽器
@app.route('/user/<username>')cookie
@app.route('/post/<int:post_id>')session
@app.route('/post/<float:post_id>')app
@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://segmentfault.com/q/1010000000125259
3、模板
一、模板的使用
Flask使用的是Jinja2模板,因此其語法和Django無差異
二、自定義模板方法
Flask中自定義模板方法的方式和Bottle類似,建立一個函數並經過參數的形式傳入render_template,如:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <h1>自定義函數</h1> {{ww()|safe}} </body> </html>
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask,render_template app = Flask(__name__) def wupeiqi(): return '<h1>Wupeiqi</h1>' @app.route('/login', methods=['GET', 'POST']) def login(): return render_template('login.html', ww=wupeiqi) app.run()
4、公共組件
一、請求
對於Http請求,Flask會講請求信息封裝在request中(werkzeug.wrappers.BaseRequest),提供的以下經常使用方法和字段以供使用:
request.method request.args request.form request.values request.files 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
表單處理Demo
@app.route('/login', methods=['POST', 'GET']) def login(): error = None if request.method == 'POST': if valid_login(request.form['username'], request.form['password']): return log_the_user_in(request.form['username']) else: error = 'Invalid username/password' # the code below is executed if the request method # was GET or the credentials were invalid return render_template('login.html', error=error)
上傳文件Demo
from flask import request from werkzeug import secure_filename @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('/var/www/uploads/' + secure_filename(f.filename)) ...
Cookie操做
from flask import request @app.route('/setcookie/') def index(): username = request.cookies.get('username') # use cookies.get(key) instead of cookies[key] to not get a # KeyError if the cookie is missing. from flask import make_response @app.route('/getcookie') def index(): resp = make_response(render_template(...)) resp.set_cookie('username', 'the username') return resp
二、響應
當用戶請求被開發人員的邏輯處理完成以後,會將結果發送給用戶瀏覽器,那麼就須要對請求作出相應的響應。
a.字符串
@app.route('/index/', methods=['GET', 'POST']) def index(): return "index"
b.模板引擎
from flask import Flask,render_template,request app = Flask(__name__) @app.route('/index/', methods=['GET', 'POST']) def index(): return render_template("index.html") app.run()
c.重定向
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask, redirect, url_for app = Flask(__name__) @app.route('/index/', methods=['GET', 'POST']) def index(): # return redirect('/login/') return redirect(url_for('login')) @app.route('/login/', methods=['GET', 'POST']) def login(): return "LOGIN" app.run()
d.錯誤頁面
指定URL,簡單錯誤
from flask import Flask, abort, render_template app = Flask(__name__) @app.route('/e1/', methods=['GET', 'POST']) def index(): abort(404, 'Nothing') app.run()
from flask import Flask, abort, render_template app = Flask(__name__) @app.route('/index/', methods=['GET', 'POST']) def index(): return "OK" @app.errorhandler(404) def page_not_found(error): return render_template('page_not_found.html'), 404 app.run()
e.設置相應信息
使用make_response能夠對相應的內容進行操做
from flask import Flask, abort, render_template,make_response app = Flask(__name__) @app.route('/index/', methods=['GET', 'POST']) def index(): response = make_response(render_template('index.html')) # response是flask.wrappers.Response類型 # response.delete_cookie # response.set_cookie # response.headers['X-Something'] = 'A value' return response app.run()
三、Session
除請求對象以外,還有一個 session 對象。它容許你在不一樣請求間存儲特定用戶的信息。它是在 Cookies 的基礎上實現的,而且對 Cookies 進行密鑰簽名要使用會話,你須要設置一個密鑰。
設置:session['username'] = 'xxx'
刪除:session.pop('username', None)
from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) @app.route('/') def index(): if 'username' in session: return 'Logged in as %s' % escape(session['username']) return 'You are not logged in' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return ''' <form action="" method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ''' @app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index')) # set the secret key. keep this really secret: app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
4.message
message是一個基於Session實現的用於保存數據的集合,其特色是:使用一次就刪除
index.html
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> {% with messages = get_flashed_messages() %} {% if messages %} <ul class=flashes> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} </body> </html>
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' if __name__ == "__main__": app.run()
5.中間件
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)