Python 框架之Flask初步了解
Python 框架之Flask初步了解
前言
? 在了解python web 框架之前,我們需要先了解框架實(shí)現(xiàn)的基本原理。首先,需要了解WSGI(Web Server Gateway Interface),借助WSGI我們就能實(shí)現(xiàn)用Python專注于生成HTML文檔,不用接觸到TCP連接、HTTP原始請(qǐng)求和響應(yīng)格式,所以,需要一個(gè)統(tǒng)一的接口,讓我們專心用Python編寫Web業(yè)務(wù)。
? WSGI將Web服務(wù)分成兩個(gè)部分:服務(wù)器和應(yīng)用程序。WGSI服務(wù)器只負(fù)責(zé)與網(wǎng)絡(luò)相關(guān)的兩件事:接收瀏覽器的HTTP請(qǐng)求、向?yàn)g覽器發(fā)送HTTP應(yīng)答;而對(duì)HTTP請(qǐng)求的具體處理邏輯,則通過調(diào)用WSGI應(yīng)用程序進(jìn)行。
Flask
Flask與別的框架(尤其是采用其他編程語言的框架)的不同之處在于:它沒有綁定諸如數(shù)據(jù)庫查詢或者表單處理等功能庫,以及它們所組成的整個(gè)生態(tài)系統(tǒng)。它傾向于對(duì)這些功能的實(shí)現(xiàn)方式不做任何限定。
實(shí)驗(yàn)環(huán)境:win10、pycharm、anaconda2.4
安裝:
由于安裝了anaconda全家桶,所以已經(jīng)自動(dòng)包含了flask的框架。需要安裝的話可以通過pip命令進(jìn)行安裝。
試運(yùn)行hello world
在pycharm新建一個(gè)項(xiàng)目,配置相關(guān)python解釋器,然后創(chuàng)建hello.py文件,寫入如下代碼:
from flask import Flaskapp = Flask(__name__)@app.route('/') def hello_world():return 'Hello world!' @app.route('/test') def test():return 'This is a test'if __name__ == '__main__':app.run()點(diǎn)擊run的按鈕,即可在瀏覽器輸入127.0.0.1:5000,顯示如下:
關(guān)于路由分發(fā)
通過@app.route(‘xxx’)形式分配路由,如上代碼,“/”表示訪問站點(diǎn)根目錄,即hello_world()函數(shù),“/test”表示訪問test()函數(shù),通過這種新式我們可以很方便的給路由進(jìn)行分組。
關(guān)于變量規(guī)則
如果希望獲取/hello/1這樣的路徑參數(shù),就需要使用變量規(guī)則。語法是/path/<converter:varname>。在變量前還可以使用可選的轉(zhuǎn)換器,有以下幾種轉(zhuǎn)換器:
| string | 默認(rèn)選項(xiàng),接受除了斜杠之外的字符串 |
| int | 接受整數(shù) |
| float | 接受浮點(diǎn)數(shù) |
| path | 和string類似,不過可以接受帶斜杠的字符串 |
| any | 匹配任何一種轉(zhuǎn)換器 |
| uuid | 接受UUID字符串 |
?
構(gòu)建url
使用函數(shù) url_for() 來針對(duì)一個(gè)特定的函數(shù)構(gòu)建一個(gè) URL。它能夠接受函數(shù)名作為第一參數(shù),以及一些關(guān)鍵字參數(shù), 每一個(gè)關(guān)鍵字參數(shù)對(duì)應(yīng)于 URL 規(guī)則的變量部分。未知變量部分被插入到 URL 中作為查詢參數(shù)。
如:
from flask import Flask, url_for app = Flask(__name__) @app.route('/') def index():return 'Home page'@app.route('/login') def login():return 'Get login'@app.route('/user/<username>') def profile(username):return 'show user %s' % usernamewith app.test_request_context():print url_for('index')print url_for('login')print url_for('profile', username='John Doe')if __name__ == '__main__':app.run()HTTP方法
首先需要引入request的包,route裝飾器中會(huì)有相應(yīng)的methods參數(shù)
from flask import request@app.route('/login', methods=['GET', 'POST']) def login():if request.method == 'POST':do_the_login()else:show_the_login_form()靜態(tài)文件的引入
靜態(tài)文件如css、js資源的引入需要在項(xiàng)目中創(chuàng)建static文件夾,用/static來引用訪問。也可以給資源定義url
url_for('static', filename='common.css')模板渲染
引入render_template,模板文件需要放在templates 文件夾中,通過render_template()渲染模板。
from flask import render_template@app.route('/hello/') @app.route('/hello/<name>') def hello(name=“”):return render_template('hello.html', name=name)模板繼承
設(shè)置可重寫區(qū)域:
# 以 {% block xx %} 開頭# 以 {% endblock %} 結(jié)束繼承:
# 以 {% extends "base.html" %} 可繼承base.html# 以 {{ super() }} 可獲取父類內(nèi)容
request 對(duì)象
request 是一個(gè)全局對(duì)象??赏ㄟ^request對(duì)象獲取頁面的傳輸數(shù)據(jù)。當(dāng)前請(qǐng)求的方法可以用method屬性來訪問。你可以用 form 屬性來訪問表單數(shù)據(jù),如:
@app.route('/login', methods=['POST', 'GET']) def login():error = Noneif 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'return render_template('login.html', error=error)cookies
from flask import request# cookies 的讀取# 使用 cookies.get(key) 代替 cookies[key] 避免# 得到 KeyError 如果cookie不存在@app.route('/get') def index():username = request.cookies.get('username')# cookies 的發(fā)送@app.route('/set') def index1():resp = make_response(render_template(...))resp.set_cookie('username', 'the username')return resp重定向和錯(cuò)誤
重定向采用redirect()函數(shù),錯(cuò)誤中斷采用abort()函數(shù)并指定一個(gè)錯(cuò)誤代碼(如404),通過 errorhandler()裝飾器制定自定義錯(cuò)誤頁面。如:
from flask import abort, redirect, url_for@app.route('/') def index():return redirect(url_for('login'))@app.route('/login') def login():abort(404)this_is_never_executed()錯(cuò)誤界面:
from flask import render_template@app.errorhandler(404) def page_not_found(error):return render_template('page_not_found.html'), 404session 會(huì)話
from flask import Flask, session, redirect, url_for, escape, requestapp = 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 theresession.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'- 生成隨機(jī)密鑰:
附上一些有用的說明,便于理解: urandom
import os os.urandom(24)日志
flask提供Logger,Logger是一個(gè)標(biāo)準(zhǔn)的Python Logger,所以我們可以向標(biāo)準(zhǔn)Logger那樣配置它,詳情查閱官方文檔 logging documentation。
app.logger.debug('A value for debugging') app.logger.warning('A warning occurred (%d apples)', 42) app.logger.error('An error occurred')
總結(jié)
以上是生活随笔為你收集整理的Python 框架之Flask初步了解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux ubantu扩展空间,ubu
- 下一篇: python实现多人聊天udp_pyth