跳到主要内容Python 与前端集成:构建全栈应用 | 极客日志Python大前端
Python 与前端集成:构建全栈应用
Python 后端与前端框架(React/Vue)的集成方法。内容包括使用 FastAPI 或 Flask 构建 RESTful API,实现前后端数据交互(JSON)、跨域处理(CORS)、用户认证(JWT)。同时涵盖了 Docker 容器化部署方案,对比了 Python 与 Rust 在开发效率与性能上的差异,并提供了全栈项目实践建议及学习方法。
乱七八糟2 浏览 Python 与前端集成:构建全栈应用
一、后端 API 设计
1.1 使用 FastAPI 创建 RESTful API
FastAPI 是一个现代化的 Python Web 框架,非常适合构建 RESTful API:
from fastapi import FastAPI
from pydantic import BaseModel
typing
app = FastAPI()
():
:
name:
price:
is_offer: =
items = []
():
{: }
():
item items:
item. == item_id:
item
{: }
():
items.append(item)
item
():
i, existing_item (items):
existing_item. == item_id:
items[i] = item
item
{: }
():
i, item (items):
item. == item_id:
items.pop(i)
{: }
{: }
from
import
List
class
Item
BaseModel
id
int
str
float
bool
None
@app.get("/")
def
read_root
return
"message"
"Hello, World!"
@app.get("/items/{item_id}")
def
read_item
item_id: int
for
in
if
id
return
return
"error"
"Item not found"
@app.post("/items/")
def
create_item
item: Item
return
@app.put("/items/{item_id}")
def
update_item
item_id: int, item: Item
for
in
enumerate
if
id
return
return
"error"
"Item not found"
@app.delete("/items/{item_id}")
def
delete_item
item_id: int
for
in
enumerate
if
id
return
"message"
"Item deleted"
return
"error"
"Item not found"
1.2 使用 Flask 创建 RESTful API
Flask 是另一个流行的 Python Web 框架,也可以用于构建 RESTful API:
from flask import Flask, request, jsonify
app = Flask(__name__)
items = []
@app.route('/', methods=['GET'])
def read_root():
return jsonify({"message": "Hello, World!"})
@app.route('/items/<int:item_id>', methods=['GET'])
def read_item(item_id):
for item in items:
if item['id'] == item_id:
return jsonify(item)
return jsonify({"error": "Item not found"})
@app.route('/items/', methods=['POST'])
def create_item():
item = request.get_json()
items.append(item)
return jsonify(item)
@app.route('/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
item = request.get_json()
for i, existing_item in enumerate(items):
if existing_item['id'] == item_id:
items[i] = item
return jsonify(item)
return jsonify({"error": "Item not found"})
@app.route('/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
for i, item in enumerate(items):
if item['id'] == item_id:
items.pop(i)
return jsonify({"message": "Item deleted"})
return jsonify({"error": "Item not found"})
if __name__ == '__main__':
app.run(debug=True)
二、前端框架集成
2.1 与 React 集成
React 是一个流行的前端框架,可以与 Python 后端 API 集成:
import React, { useState, useEffect } from 'react';
function App() {
const [items, setItems] = useState([]);
const [newItem, setNewItem] = useState({ id: '', name: '', price: '', is_offer: false });
useEffect(() => {
fetch('http://localhost:8000/items/')
.then(response => response.json())
.then(data => setItems(data));
}, []);
const handleSubmit = (e) => {
e.preventDefault();
fetch('http://localhost:8000/items/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newItem),
})
.then(response => response.json())
.then(data => {
setItems([...items, data]);
setNewItem({ id: '', name: '', price: '', is_offer: false });
});
};
return (
<div>
<h1>Items</h1>
<ul>
{items.map(item => (
<li key={item.id}>
{item.name} - ${item.price}
</li>
))}
</ul>
<form onSubmit={handleSubmit}>
<input type="text" placeholder="ID" value={newItem.id} onChange={(e) => setNewItem({...newItem, id: parseInt(e.target.value)})} />
<input type="text" placeholder="Name" value={newItem.name} onChange={(e) => setNewItem({...newItem, name: e.target.value})} />
<input type="number" placeholder="Price" value={newItem.price} onChange={(e) => setNewItem({...newItem, price: parseFloat(e.target.value)})} />
<button type="submit">Add Item</button>
);
}
export default App;
2.2 与 Vue 集成
Vue 是另一个流行的前端框架,也可以与 Python 后端 API 集成:
<!-- App.vue -->
<template>
<div>
<h1>Items</h1>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }} - ${{ item.price }}
</li>
</ul>
<form @submit.prevent="handleSubmit">
<input type="text" placeholder="ID" v-model.number="newItem.id" />
<input type="text" placeholder="Name" v-model="newItem.name" />
<input type="number" placeholder="Price" v-model.number="newItem.price" />
<button type="submit">Add Item</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
newItem: { id: '', name: '', price: '', is_offer: false }
};
},
mounted() {
this.fetchItems();
},
methods: {
fetchItems() {
fetch('http://localhost:8000/items/')
.then(response => response.json())
.then(data => {
this.items = data;
});
},
handleSubmit() {
fetch('http://localhost:8000/items/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(this.newItem),
})
.then(response => response.json())
.then(data => {
this.items.push(data);
this.newItem = { id: '', name: '', price: '', is_offer: false };
});
}
}
};
</script>
三、数据传输
3.1 JSON 数据格式
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
id: int
name: str
price: float
@app.get("/item", response_model=Item)
def get_item():
return {"id": 1, "name": "Item 1", "price": 10.99}
3.2 处理 CORS
跨域资源共享(CORS)是前后端集成中常见的问题:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def read_root():
return {"message": "Hello, World!"}
from flask import Flask, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/')
def read_root():
return jsonify({"message": "Hello, World!"})
四、认证与授权
4.1 JWT 认证
JSON Web Token(JWT)是一种常用的认证方式:
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from datetime import datetime, timedelta
from pydantic import BaseModel
app = FastAPI()
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
fake_users_db = {
"alice": {
"username": "alice",
"full_name": "Alice Smith",
"email": "[email protected]",
"hashed_password": "fakehashedsecret",
"disabled": False,
}
}
def fake_hash_password(password: str):
return "fakehashed" + password
def verify_password(plain_password, hashed_password):
return hashed_password == fake_hash_password(plain_password)
def get_user(db, username: str):
if username in db:
user_dict = db[username]
return user_dict
def create_access_token(data: dict, expires_delta: timedelta = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
except JWTError:
raise credentials_exception
user = get_user(fake_users_db, username=username)
if user is None:
raise credentials_exception
return user
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
user = get_user(fake_users_db, form_data.username)
if not user:
raise HTTPException(status_code=400, detail="Incorrect username or password")
if not verify_password(form_data.password, user["hashed_password"]):
raise HTTPException(status_code=400, detail="Incorrect username or password")
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": user["username"]},
expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
@app.get("/users/me")
async def read_users_me(current_user: dict = Depends(get_current_user)):
return current_user
五、部署
5.1 部署后端
# Dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
5.2 部署前端
使用 Vercel、Netlify 等平台部署前端:
- Vercel:适合部署 React、Next.js 应用
- Netlify:适合部署 Vue、React 应用
- GitHub Pages:适合部署静态网站
5.3 完整部署
version: '3'
services:
backend:
build: ./backend
ports:
- "8000:8000"
frontend:
build: ./frontend
ports:
- "3000:3000"
depends_on:
- backend
六、Python 与 Rust 的对比
6.1 前端集成对比
- Python:生态丰富,有 FastAPI、Flask 等框架
- Rust:有 Actix-web、Rocket 等框架
- 开发效率:Python 开发效率高,Rust 开发效率相对较低
- 性能:Rust 性能优异,Python 性能相对较低
6.2 学习心得
- Python 的优势:开发效率高,生态丰富
- Rust 的优势:性能优异,内存安全
- 相互借鉴:从 Python 学习快速开发,从 Rust 学习性能优化
七、实践项目推荐
7.1 全栈项目
- 博客系统:使用 Python 作为后端,React/Vue 作为前端
- 电商系统:使用 Python 作为后端,React/Vue 作为前端
- 社交应用:使用 Python 作为后端,React/Vue 作为前端
- 数据分析平台:使用 Python 作为后端,React/Vue 作为前端
八、学习方法和技巧
8.1 学习方法
- 循序渐进:先学习后端 API 开发,再学习前端框架
- 项目实践:通过实际项目来巩固知识
- 文档阅读:仔细阅读框架的官方文档
- 社区交流:加入社区,向他人学习
8.2 常见问题和解决方法
- CORS 问题:配置 CORS 中间件
- 认证问题:使用 JWT 等认证方式
- 部署问题:使用 Docker 等容器化技术
- 性能问题:优化 API 设计,使用缓存
九、总结
Python 与前端技术的集成可以构建出功能强大的全栈应用。本文介绍了后端 API 设计、前端框架集成、数据传输、认证授权及部署方案。通过不断实践和学习,可以掌握 Python 与前端集成的各种技巧。
微信扫一扫,关注极客日志
微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
相关免费在线工具
- curl 转代码
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
- Base64 字符串编码/解码
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
- Base64 文件转换器
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
- Markdown 转 HTML
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML 转 Markdown 互为补充。 在线工具,Markdown 转 HTML在线工具,online
- HTML 转 Markdown
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML 转 Markdown在线工具,online
- JSON 压缩
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online
</form>
</div>