5分鐘帶你快速瞭解 Flask

本文帶你快速瞭解 Flask,只需 5 分鐘即可完成一個基礎頁面的開發。廢話不多說,現在開始!

簡潔強大的Flask

安裝

<code>pip install Flask/<code>

你的第一個應用

<code># 此文件存儲為 hello.py from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return '歡迎來到Flask的世界!' @app.route('/hello') def hello(): return '你好,這是經典的Hello World!'/<code>

運行和訪問

<code># Linux 系統: export FLASK_APP=hello.py python -m flask run * Running on http://127.0.0.1:5000/ # Windows 系統: set FLASK_APP=hello.py python -m flask run --host=0.0.0.0 * Running on http://127.0.0.1:5000//<code>

添加 URL 參數

將參數添加到 URL 中,如下代碼所示,經常使用的參數類型如下:

string 接受不帶斜槓的任何文本(默認)int 接受整數float 接受浮點數any 匹配提供的項目之一uuid 接受 uuid 字符串

<code>@app.route('/user/') def show_user(username): return '用戶 %s' % username @app.route('/post/') def show_post(post_id): return '文章 %d' % post_id/<code>

HTTP 方法

Flask 可以處理很多 HTTP 方法,默認為 GET,示例如下:

還支持的方法有:POST、HEAD、PUT、DELETE、OPTION。

<code>from flask import request @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': return '你訪問的是POST方法' else: return '你訪問的是非POST方法'/<code>

渲染模板

Flask 使用 Jinja2 模板引擎來處理 HTML 頁面,使用 render_template 方法來渲染,示例如下:

<code>from flask import render_template @app.route('/hello/') def hello(name): return render_template('hello.html', name=name)/<code>

這是一個示例模板:

<code> Hello from Flask {% if name %}

Hello {{ name }}!

{% else %}

Hello, World!

{% endif %}/<code>

Flask 將在模板文件夾中查找模板。因此,如果您的應用程序是一個模塊,則該文件夾位於該模塊旁邊,如果它是一個包,則它實際上位於您的包中:

<code>模塊示例: /application.py /templates /hello.html 包示例: /application /__init__.py /templates /hello.html/<code>

POST請求參數

可使用 request.form['username'] 來獲取請求參數,示例如下:

<code>from flask import request @app.route('/login', methods=['POST', 'GET']) def login(): error = None if request.method == 'POST': if login(request.form['username'], request.form['password']): return "登錄成功" else: error = '用戶名或密碼錯誤!'/<code>

文件上傳

在 HTML 表單上設置 enctype = "multipart / form-data" 屬性,Flask 代碼如下:

<code>from flask import request @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['file_name'] f.save('你的路徑/file_name.xxx')/<code>

操作 Cookie

<code>from flask import request @app.route('/') def index(): # 讀取 Cookie username = request.cookies.get('username') # 寫入 Cookie resp = make_response(render_template(...)) resp.set_cookie('username', '張三') return resp/<code>

重定向

使用 redirect 函數即可重定向,示例如下:

<code>from flask import abort, redirect, url_for @app.route('/') def index(): return redirect(url_for('login'))/<code>

本文是 Flask 的超簡潔代碼入門文章,如果你還有什麼不清楚的地方,歡迎和我交流!