Flask從入門到實戰:基礎、進階、項目架構與接口測試

本文將帶你從零開始掌握Flask框架,涵蓋基礎使用、進階技巧、項目架構設計,并提供完整的接口測試客戶端代碼。

目錄

    • 一、Flask基礎入門
      • 1.1 Flask簡介與安裝
      • 1.2 第一個Flask應用
      • 1.3 路由與請求處理
      • 1.4 請求與響應處理
    • 二、Flask進階使用
      • 2.1 模板引擎Jinja2
      • 2.2 數據庫集成(SQLAlchemy)
      • 2.3 表單處理(Flask-WTF)
    • 三、Flask高階使用
      • 3.1 藍圖(Blueprints)模塊化
      • 3.2 RESTful API開發
      • 3.3 用戶認證與授權
    • 四、Flask項目框架結構
      • 4.1 核心文件說明
    • 五、接口測試客戶端代碼
      • 5.1 Python接口測試客戶端
      • 5.2 使用說明
    • 六、Flask部署實踐
      • 6.1 生產環境部署
      • 6.2 Docker化部署
    • 七、總結
    • 附錄1(實踐代碼示例)
    • 附錄2(其他參考博文)

一、Flask基礎入門

1.1 Flask簡介與安裝

Flask是一個輕量級的Python Web框架,以其簡潔、靈活和易擴展的特性受到開發者喜愛。安裝只需一行命令:

pip install flask

1.2 第一個Flask應用

創建一個最簡單的Flask應用:

from flask import Flaskapp = Flask(__name__)@app.route('/')
def hello_world():return 'Hello, Flask!'if __name__ == '__main__':app.run(host='0.0.0.0', port=5000)

運行后訪問 http://127.0.0.1:5000 即可看到結果

1.3 路由與請求處理

Flask通過裝飾器定義路由:

@app.route('/user/<username>')
def show_user_profile(username):return f'User: {username}'@app.route('/post/<int:post_id>')
def show_post(post_id):return f'Post ID: {post_id}'

1.4 請求與響應處理

處理GET/POST請求并返回JSON響應:

from flask import request, jsonify@app.route('/login', methods=['GET', 'POST'])
def login():if request.method == 'POST':username = request.form['username']password = request.form['password']# 驗證邏輯...return jsonify({'status': 'success', 'user': username})else:return '''<form method="post"><input type="text" name="username"><input type="password" name="password"><input type="submit"></form>'''

二、Flask進階使用

2.1 模板引擎Jinja2

Flask內置強大的模板引擎,實現前后端分離:

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

模板文件 templates/hello.html:

<!doctype html>
<html>
<head><title>Hello Page</title></head>
<body><h1>Hello, {{ name }}!</h1>
</body>
</html>

2.2 數據庫集成(SQLAlchemy)

使用Flask-SQLAlchemy集成數據庫:

pip install flask-sqlalchemy
from flask_sqlalchemy import SQLAlchemyapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)class User(db.Model):id = db.Column(db.Integer, primary_key=True)username = db.Column(db.String(20), unique=True, nullable=False)email = db.Column(db.String(120), unique=True, nullable=False)def __repr__(self):return f"User('{self.username}', '{self.email}')"# 創建數據庫
db.create_all()

2.3 表單處理(Flask-WTF)

使用Flask-WTF處理表單:

pip install flask-wtf
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Lengthclass LoginForm(FlaskForm):username = StringField('Username', validators=[DataRequired(), Length(min=4, max=20)])password = PasswordField('Password', validators=[DataRequired()])submit = SubmitField('Login')

三、Flask高階使用

3.1 藍圖(Blueprints)模塊化

使用藍圖組織大型項目:

# 創建藍圖 auth/__init__.py
from flask import Blueprintauth = Blueprint('auth', __name__)@auth.route('/login')
def login():return 'Login Page'# 在app中注冊藍圖
from auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')

3.2 RESTful API開發

使用Flask-RESTful構建API:

pip install flask-restful
from flask_restful import Resource, Apiapi = Api(app)class UserAPI(Resource):def get(self, user_id):# 獲取用戶信息return {'user': user_id}def put(self, user_id):# 更新用戶信息return {'status': 'updated'}def delete(self, user_id):# 刪除用戶return {'status': 'deleted'}api.add_resource(UserAPI, '/user/<int:user_id>')

3.3 用戶認證與授權

實現JWT認證:

pip install flask-jwt-extended
from flask_jwt_extended import JWTManager, create_access_token, jwt_requiredapp.config['JWT_SECRET_KEY'] = 'super-secret'  # 實際項目中應使用強密鑰
jwt = JWTManager(app)@app.route('/login', methods=['POST'])
def login():username = request.json.get('username', None)password = request.json.get('password', None)# 驗證邏輯...access_token = create_access_token(identity=username)return jsonify(access_token=access_token)@app.route('/protected', methods=['GET'])
@jwt_required()
def protected():return jsonify(logged_in_as=current_user)

四、Flask項目框架結構

一個典型的Flask項目結構如下:

myflaskapp/
├── app/
│   ├── __init__.py
│   ├── auth/
│   │   ├── __init__.py
│   │   ├── routes.py
│   │   └── forms.py
│   ├── main/
│   │   ├── __init__.py
│   │   └── routes.py
│   ├── models.py
│   ├── templates/
│   │   ├── base.html
│   │   ├── index.html
│   │   └── auth/
│   │       ├── login.html
│   │       └── register.html
│   └── static/
│       ├── css/
│       ├── js/
│       └── img/
├── config.py
├── requirements.txt
├── run.py
└── tests/├── __init__.py├── test_auth.py└── test_main.py

4.1 核心文件說明

  • run.py: 應用入口
  • config.py: 配置文件
  • app/__init__.py: 應用工廠函數
  • app/models.py: 數據庫模型
  • app/templates/: HTML模板
  • app/static/: 靜態資源

五、接口測試客戶端代碼

5.1 Python接口測試客戶端

使用requests庫編寫的通用測試工具:

import requests
import jsonclass FlaskAPITester:def __init__(self, base_url='http://localhost:5000'):self.base_url = base_urlself.session = requests.Session()self.headers = {'Content-Type': 'application/json'}def test_get(self, endpoint, params=None):url = f"{self.base_url}{endpoint}"try:response = self.session.get(url, params=params, headers=self.headers)return self._format_response(response)except Exception as e:return {'error': str(e)}def test_post(self, endpoint, data=None):url = f"{self.base_url}{endpoint}"try:response = self.session.post(url, json=data, headers=self.headers)return self._format_response(response)except Exception as e:return {'error': str(e)}def _format_response(self, response):return {'status_code': response.status_code,'headers': dict(response.headers),'response': self._try_parse_json(response.text)}def _try_parse_json(self, text):try:return json.loads(text)except:return textdef set_token(self, token):self.headers['Authorization'] = f'Bearer {token}'def clear_token(self):if 'Authorization' in self.headers:del self.headers['Authorization']# 使用示例
if __name__ == '__main__':tester = FlaskAPITester()# 測試GET請求print("Testing GET /api/data:")print(tester.test_get('/api/data'))# 測試POST請求print("\nTesting POST /api/login:")login_data = {'username': 'testuser', 'password': 'testpass'}login_response = tester.test_post('/api/login', data=login_data)print(login_response)# 使用返回的token測試受保護端點if 'response' in login_response and 'access_token' in login_response['response']:token = login_response['response']['access_token']tester.set_token(token)print("\nTesting protected endpoint with token:")print(tester.test_get('/api/protected'))

5.2 使用說明

  1. 創建測試器實例:

    tester = FlaskAPITester(base_url='http://your-flask-server:5000')
    
  2. 測試GET接口:

    result = tester.test_get('/api/users', params={'page': 1, 'per_page': 10})
    
  3. 測試POST接口:

    result = tester.test_post('/api/users', data={'name': 'John', 'email': 'john@example.com'})
    
  4. 測試需要認證的接口:

    # 先獲取token
    login_res = tester.test_post('/auth/login', data={'username': 'admin', 'password': 'secret'})
    token = login_res['response']['access_token']# 設置token
    tester.set_token(token)# 測試受保護接口
    protected_res = tester.test_get('/api/protected')
    

六、Flask部署實踐

6.1 生產環境部署

使用Gunicorn+NGINX部署Flask應用:

# 安裝Gunicorn
pip install gunicorn# 啟動應用
gunicorn -w 4 -b 0.0.0.0:8000 run:app

6.2 Docker化部署

創建Dockerfile:

FROM python:3.9-slimWORKDIR /appCOPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txtCOPY . .CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "run:app"]

構建并運行:

docker build -t flask-app .
docker run -d -p 5000:5000 flask-app

七、總結

Flask作為一個輕量級但功能強大的Web框架,適合從簡單應用到復雜系統的開發。本文涵蓋了:

  1. Flask基礎:路由、請求處理、模板渲染
  2. 進階技術:數據庫集成、表單處理
  3. 高級功能:藍圖模塊化、RESTful API、認證授權
  4. 項目架構設計
  5. 接口測試客戶端實現
  6. 生產環境部署方案

掌握這些知識后,你已具備使用Flask開發專業Web應用的能力。Flask的靈活性允許你根據項目需求選擇合適的擴展,構建從簡單API到復雜企業級應用的各種解決方案。

最佳實踐建議

  1. 始終使用藍圖組織大型項目
  2. 將配置信息分離到環境變量或配置文件中
  3. 使用工廠模式創建應用實例
  4. 為生產環境配置合適的WSGI服務器
  5. 編寫單元測試覆蓋核心功能
  6. 使用Docker容器化部署應用

附錄1(實踐代碼示例)

from flask import Flask, jsonify, render_template, request"""
實現一個簡單的Flask應用程序訪問地址:
http://127.0.0.1:8084/
http://192.168.5.8:8084/運行命令:
source venv/bin/activate
python app.py
ps -ef | grep "app.py"
lsof -i :5000
ps -ef | grep "python.*app.py" | grep -v grep | awk '{print $2}' | xargs kill -9
pgrep -f "app.py"  | xargs kill -9 && echo "進程已終止"
"""
# 創建Flask應用實例
app = Flask(__name__)# http://192.168.5.8:8084
@app.route('/')  # 定義路由
def hello_world():  # 定義視圖函數"""定義視圖函數 hello_world。Args: 無Returns:str: 返回字符串 'Hello, Flask!'"""return 'Hello, Flask!'# http://192.168.5.8:8084/login
@app.route('/login', methods=['GET', 'POST'])
def login():"""處理用戶登錄請求的函數。Args:無Returns:如果請求方法為POST,則返回包含用戶登錄信息的JSON格式字符串;如果請求方法不是POST,則返回HTML格式的登錄表單。"""if request.method == 'POST':# 處理表單提交username = request.form['username']password = request.form['password']# 驗證邏輯...return jsonify({'status': 'success', 'user': username, 'password': password})else:# 顯示登錄表單return '''<form method="post"><input type="text" name="username"><input type="password" name="password"><input type="submit"></form>'''# http://192.168.5.8:8084/hello/Flask
@app.route('/hello/<name>')
def hello(name):"""向用戶顯示問候頁面。Args:name (str): 用戶的名字。Returns:str: 渲染后的 HTML 頁面。"""return render_template('hello.html', name=name)# 啟動應用
if __name__ == '__main__':app.run(host='0.0.0.0', port=8084, debug=True)

附錄2(其他參考博文)

【Python Web】一文搞懂Flask框架:從入門到實戰的完整指南

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/92347.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/92347.shtml
英文地址,請注明出處:http://en.pswp.cn/web/92347.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

華為云產品圖解

框架圖核心說明: 1. 分層邏輯清晰 基礎設施層(IaaS):提供最基礎的計算(ECS/BMS)、存儲(OBS/EVS)、網絡(VPC/CDN)資源,是所有上層服務的 “物理底座”。 平臺服務層(PaaS):基于 IaaS 構建,提供容器編排(CCE)、數據庫(GaussDB)、大數據與 AI(ModelArts)、中…

Git 中如何回退到以前的提交記錄?

回答重點要在 Git 中回退到以前的提交記錄&#xff0c;你可以使用 git reset 命令。這個命令有三個常用選項來控制你想要回退的程度&#xff1a;1&#xff09; git reset --soft <commit> &#xff1a;僅修改 HEAD 指針&#xff0c;不修改索引和工作區內容。2&#xff09…

JavaWeb03——基礎標簽及樣式(表單)(黑馬視頻筆記)

1.表單標簽 及 表單屬性表單標簽是 &#xff1a;<form> 表單屬性有&#xff1a;action 和 method&#xff1b;action屬性&#xff1a;規定向何處發送表單數據。method屬性&#xff1a;規定用什么方法發送數據。&#xff08;get和post&#xff09;get:在發送的url后面拼接…

STM32的SPI通信(軟件讀寫W25Q64)

在了解完I2C通信后&#xff0c;不免會接觸到到SPI通信。而一開始&#xff0c;可能會覺得兩者好似沒什么區別。為什么要學SPI呢&#xff0c;I2C和SPI有什么區別呢。為此我詳細展開說說。1.什么是 SPI&#xff1f;SPI&#xff0c;全稱 Serial Peripheral Interface&#xff0c;中…

子詞分詞器(Byte Pair Encoding + WordPiece)

參考文章&#xff1a;子詞分詞器BPE和WordPiece理解_wordpeice-CSDN博客 子詞分詞器BPE和WordPiece理解_wordpeice-CSDN博客 WordPiece 和 BPE 的區別-CSDN博客 點互信息&#xff08;PMI&#xff09;和正點互信息&#xff08;PPMI&#xff09;-CSDN博客 https://zhuanlan.z…

阿里招AI產品運營

AI產品運營&#xff08;崗位信息已經過jobleap.cn授權&#xff0c;可在csdn發布&#xff09;靈犀互娛 廣州收錄時間&#xff1a; 2025年08月05日職位描述負責AI技術在游戲行業的應用與落地&#xff0c;專注于海外市場的運營中臺建設&#xff1b; 將結合AI技術與游戲行業特點&a…

Git 分支遷移完整指南(結合分支圖分析)

基于分支圖的當前狀態分析 分支圖關鍵信息解讀?分支結構?&#xff1a; #mermaid-svg-gc9SPnwlbrM2FzHf {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-gc9SPnwlbrM2FzHf .error-icon{fill:#552222;}#mermaid-svg-…

小程序省市級聯組件使用

背景。uni-data-picker組件用起來不方便。調整后級聯效果欠佳&#xff0c;會關閉彈窗需要重新選擇。解決方案。讓cursor使用uniapp 原生組件生成懶加載省市級聯 <template><view class"picker-cascader"><view class"cascader-label">&l…

Java技術棧/面試題合集(8)-Redis篇

場景 Java入門、進階、強化、擴展、知識體系完善等知識點學習、性能優化、源碼分析專欄分享: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/140870227 通過對面試題進行系統的復習可以對Java體系的知識點進行查漏補缺。 注: 博客: 霸道流氓氣質-CSDN博…

川翔云電腦:引領開啟算力無邊界時代

一、何為云電腦&#xff1f;重新定義“主機”概念 云電腦將傳統本地計算機的核心硬件資源&#xff08;CPU、GPU、內存、硬盤等&#xff09;集中部署于遠程高性能數據中心&#xff0c;通過網絡技術將虛擬桌面實時傳輸到您的任意訪問設備上。 ??如同將高配主機裝入云端&#…

tc 介紹

目錄 1.背景 2. tc介紹 3. tc 丟包 1.背景 需要使用tc 構造丟包場景&#xff0c;注意tc 丟包不能確定丟棄的是否是payload 數據包&#xff0c;有可能丟棄 ack 包。 2. tc介紹 1. 無法正常使用 [rootpool-100-1-1-18 /]# [rootpool-100-1-1-18 /]# tc qdisc add dev swif…

LabVIEW注冊表操作

?本文圍繞LabVIEW中操作Windows 注冊表的 4 個 VI 展開&#xff0c;介紹其功能、使用場景等并對比&#xff0c;助力工程師高效運用注冊表交互功能。各 VI 功能說明&#xff08;一&#xff09;Write the Key功能&#xff1a;創建新注冊表鍵&#xff0c;設置其值&#xff0c;隨后…

阿里云部署若依后,瀏覽器能正常訪問,但是apifox和小程序訪問后報錯鏈接被重置

項目場景&#xff1a;阿里云部署若依后瀏覽器能正常通過https訪問,但是在apifox和小程序調用接口的時候生報錯E問題描述apifox報錯&#xff1a;curl報錯&#xff1a;通過curl可以清楚的看到通過域名是能準確的訪問到IP地址的&#xff0c;說明這個DNS是沒有問題的&#xff0c;但…

升級 Elasticsearch 到新的 AWS Java SDK

作者&#xff1a;來自 Elastic David Turner, Dianna Hohensee Elasticsearch 使用官方的 AWS Java SDK 集成了某些 Amazon Web Services (AWS) 功能。這些集成最早在近 10 年前發布的 Elasticsearch 2.0 版本中引入。 最近&#xff0c;AWS 宣布 Elasticsearch 過去十年使用的…

從0到1學習微服務項目黑馬頭條day01-《APP端登錄功能實現》

個人主頁&#xff1a;VON文章所屬專欄&#xff1a;黑馬頭條個人唯一微信&#xff1a;微信 有一起學習微服務的小伙伴可以加作者微信&#xff1a;單擊即可添加 目錄 一、前言 二、項目概述 1、技術棧 2、項目引入 三、改造項目 1、創建heima-leadnews-user 2、創建實體…

Renesas Electronics RZ/V2N 評估套件

簡介Renesas Electronics RZ/V2N評估套件采用RZ/V2N中檔嵌入式AI微處理器 (MPU) 為嵌入式人工智能 (AI) 應用提供全面的開發平臺。該評估套件包括兩塊板&#xff1a;主板 (RTK0EF0186C02000BJ)&#xff0c;緊湊的153mm x 100mm外形尺寸和RTK0EF0168B00000BJ擴展板。其核心是RZ/…

使用PHP與Apache實現服務器端文件管理

引言 作為前端開發者&#xff0c;你可能經常需要與服務器文件系統交互。本文將詳細介紹如何通過PHP配合Apache實現服務器端文件管理功能。即使你沒有任何PHP經驗&#xff0c;也能按照本教程實現完整解決方案&#xff01; 系統準備 PHP下載與安裝 訪問PHP官網下載頁面 選擇與…

在Word和WPS文字中如何輸入漢字的偏旁部首

如何在Word和WPS文字中輸入偏旁部首&#xff1f;許多輸入法會把常見的偏旁部首直接放到詞庫&#xff0c;對于詞庫中沒有的可以試試這個方法&#xff1a;先輸入一個有這個偏旁部首的字&#xff0c;盡量簡單一點的&#xff0c;然后選中這個字插入-符號-其他符號。滾動到這個偏旁部…

day44 力扣1143.最長公共子序列 力扣1035.不相交的線 力扣53. 最大子序和 力扣392.判斷子序列

最長公共子序列 給定兩個字符串 text1 和 text2&#xff0c;返回這兩個字符串的最長 公共子序列 的長度。如果不存在 公共子序列 &#xff0c;返回 0 。 一個字符串的 子序列 是指這樣一個新的字符串&#xff1a;它是由原字符串在不改變字符的相對順序的情況下刪除某些字符&…

應用7:用小白量化智能體金融模塊做一個股票選股工具

應用7&#xff1a;用小白量化智能體金融模塊做一個股票選股工具 【小白量化智能體】包含有豐富的金融模塊。可以讓智能體寫各種金融量化工具。 我用讓小白量化智能體寫一個股票選股工具。 我們給【小白量化智能體】一個程序生成話術。 幫我寫一個 選股 的應用程序&#xff0c;要…