Python 框架之Flask初步了解
Python 框架之Flask初步了解
前言
? 在了解python web 框架之前,我們需要先了解框架實現的基本原理。首先,需要了解WSGI(Web Server Gateway Interface),借助WSGI我們就能實現用Python專注于生成HTML文檔,不用接觸到TCP連接、HTTP原始請求和響應格式,所以,需要一個統一的接口,讓我們專心用Python編寫Web業務。
? WSGI將Web服務分成兩個部分:服務器和應用程序。WGSI服務器只負責與網絡相關的兩件事:接收瀏覽器的HTTP請求、向瀏覽器發送HTTP應答;而對HTTP請求的具體處理邏輯,則通過調用WSGI應用程序進行。
Flask
Flask與別的框架(尤其是采用其他編程語言的框架)的不同之處在于:它沒有綁定諸如數據庫查詢或者表單處理等功能庫,以及它們所組成的整個生態系統。它傾向于對這些功能的實現方式不做任何限定。
實驗環境:win10、pycharm、anaconda2.4
安裝:
由于安裝了anaconda全家桶,所以已經自動包含了flask的框架。需要安裝的話可以通過pip命令進行安裝。
試運行hello world
在pycharm新建一個項目,配置相關python解釋器,然后創建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()點擊run的按鈕,即可在瀏覽器輸入127.0.0.1:5000,顯示如下:
關于路由分發
通過@app.route(‘xxx’)形式分配路由,如上代碼,“/”表示訪問站點根目錄,即hello_world()函數,“/test”表示訪問test()函數,通過這種新式我們可以很方便的給路由進行分組。
關于變量規則
如果希望獲取/hello/1這樣的路徑參數,就需要使用變量規則。語法是/path/<converter:varname>。在變量前還可以使用可選的轉換器,有以下幾種轉換器:
| string | 默認選項,接受除了斜杠之外的字符串 |
| int | 接受整數 |
| float | 接受浮點數 |
| path | 和string類似,不過可以接受帶斜杠的字符串 |
| any | 匹配任何一種轉換器 |
| uuid | 接受UUID字符串 |
?
構建url
使用函數 url_for() 來針對一個特定的函數構建一個 URL。它能夠接受函數名作為第一參數,以及一些關鍵字參數, 每一個關鍵字參數對應于 URL 規則的變量部分。未知變量部分被插入到 URL 中作為查詢參數。
如:
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裝飾器中會有相應的methods參數
from flask import request@app.route('/login', methods=['GET', 'POST']) def login():if request.method == 'POST':do_the_login()else:show_the_login_form()靜態文件的引入
靜態文件如css、js資源的引入需要在項目中創建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)模板繼承
設置可重寫區域:
# 以 {% block xx %} 開頭# 以 {% endblock %} 結束繼承:
# 以 {% extends "base.html" %} 可繼承base.html# 以 {{ super() }} 可獲取父類內容
request 對象
request 是一個全局對象。可通過request對象獲取頁面的傳輸數據。當前請求的方法可以用method屬性來訪問。你可以用 form 屬性來訪問表單數據,如:
@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 的發送@app.route('/set') def index1():resp = make_response(render_template(...))resp.set_cookie('username', 'the username')return resp重定向和錯誤
重定向采用redirect()函數,錯誤中斷采用abort()函數并指定一個錯誤代碼(如404),通過 errorhandler()裝飾器制定自定義錯誤頁面。如:
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()錯誤界面:
from flask import render_template@app.errorhandler(404) def page_not_found(error):return render_template('page_not_found.html'), 404session 會話
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'- 生成隨機密鑰:
附上一些有用的說明,便于理解: urandom
import os os.urandom(24)日志
flask提供Logger,Logger是一個標準的Python Logger,所以我們可以向標準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')
總結
以上是生活随笔為你收集整理的Python 框架之Flask初步了解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux ubantu扩展空间,ubu
- 下一篇: python实现多人聊天udp_pyth