1.1 HTTP協(xié)議基礎(chǔ)
HTTP(超文本傳輸協(xié)議)是Web通信的基礎(chǔ)協(xié)議,定義了客戶端和服務(wù)器之間交換信息的方式。
關(guān)鍵概念:
- 請求方法:GET(獲取資源)、POST(提交數(shù)據(jù))、PUT(更新資源)、DELETE(刪除資源)
- 狀態(tài)碼:200(成功)、404(未找到)、500(服務(wù)器錯誤)、302(重定向)
- 頭部信息:包含元數(shù)據(jù)如Content-Type、Cookie等
1.2 請求/響應(yīng)周期
Web交互遵循標(biāo)準(zhǔn)流程:
- 客戶端發(fā)送HTTP請求:瀏覽器或應(yīng)用發(fā)起請求
- 服務(wù)器解析請求:Web服務(wù)器解析請求內(nèi)容
- 應(yīng)用處理業(yè)務(wù)邏輯:框架處理路由、數(shù)據(jù)庫操作等
- 生成HTTP響應(yīng):構(gòu)建響應(yīng)頭和內(nèi)容
- 返回給客戶端:服務(wù)器發(fā)送響應(yīng),客戶端渲染結(jié)果
要點(diǎn):
- 每個請求都是獨(dú)立的(HTTP無狀態(tài))
- 使用Cookie/Session維護(hù)狀態(tài)
2.1 WSGI接口
WSGI(Web Server Gateway Interface)是Python Web應(yīng)用與服務(wù)器之間的標(biāo)準(zhǔn)接口。
基礎(chǔ)實(shí)現(xiàn):
def simple_app(environ, start_response):
"""最簡單的WSGI應(yīng)用"""
status = '200 OK'
headers = [('Content-type', 'text/plain')]
start_response(status, headers)
return [b"Hello World!"]
# 使用wsgiref運(yùn)行
from wsgiref.simple_server import make_server
httpd = make_server('', 8000, simple_app)
httpd.serve_forever()
關(guān)鍵參數(shù):
environ:包含請求信息的字典
start_response:設(shè)置響應(yīng)狀態(tài)和頭部的函數(shù)
2.2 WSGI中間件
中間件是WSGI應(yīng)用的包裝器,用于處理請求/響應(yīng)的預(yù)處理和后處理。
class Middleware:
"""WSGI中間件示例"""
def__init__(self, app):
self.app = app
def__call__(self, environ, start_response):
# 預(yù)處理 - 日志記錄
print(f"請求路徑: {environ['PATH_INFO']}")
# 調(diào)用下層應(yīng)用
defcustom_start_response(status, headers):
# 后處理 - 添加自定義頭部
headers.append(('X-Middleware', 'Processed'))
return start_response(status, headers)
returnself.app(environ, custom_start_response)
# 包裝應(yīng)用
wrapped_app = Middleware(simple_app)
中間件常見用途:
3.1 Flask框架
輕量級微框架,適合中小型項目和API開發(fā)。
基本應(yīng)用:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/')
defhome():
return"<h1>歡迎使用Flask</h1>"
@app.route('/api/data', methods=['GET', 'POST'])
defhandle_data():
if request.method == 'POST':
return jsonify({"status": "成功", "data": request.json})
return jsonify({"values": [1, 2, 3]})
if __name__ == '__main__':
app.run(debug=True)
Flask特點(diǎn):
- 豐富的擴(kuò)展生態(tài)系統(tǒng)
- 內(nèi)置開發(fā)服務(wù)器和調(diào)試器
3.2 Django框架
全功能框架,遵循"不重復(fù)自己"(DRY)原則,適合大型項目。
MTV架構(gòu):
快速開始:
# views.py
from django.http import HttpResponse
from django.shortcuts import render
defindex(request):
return HttpResponse("Hello Django")
defuser_view(request, username):
return render(request, 'user.html', {'name': username})
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('user/<str:username>/', views.user_view)
]
Django特點(diǎn):
3.3 FastAPI框架
現(xiàn)代異步框架,適合高性能API和實(shí)時應(yīng)用。
基本示例:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
classItem(BaseModel):
name: str
price: float
@app.get("/")
asyncdefroot():
return {"message": "Hello FastAPI"}
@app.post("/items/")
asyncdefcreate_item(item: Item):
return {"item": item.dict()}
WebSocket支持:
from fastapi import WebSocket
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"收到: {data}")
FastAPI優(yōu)勢:
- 高性能(基于Starlette和Pydantic)
4.1 Jinja2語法
Jinja2是Python流行的模板引擎,用于動態(tài)生成HTML。
基礎(chǔ)語法:
<!-- base.html -->
<html>
<head><title>{% block title %}{% endblock %}</title></head>
<body>
{% block content %}{% endblock %}
</body>
</html>
<!-- user.html -->
{% extends "base.html" %}
{% block title %}用戶 {{ name }}{% endblock %}
{% block content %}
<h1>歡迎, {{ name }}!</h1>
{% if is_admin %}
<p>您擁有管理員權(quán)限</p>
{% endif %}
<ul>
{% for item in items %}
<li>{{ item.name }}: ${{ item.price }}</li>
{% endfor %}
</ul>
{% endblock %}
4.2 模板繼承與渲染
from jinja2 import Environment, FileSystemLoader
# 創(chuàng)建模板環(huán)境
env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('user.html')
# 渲染模板
context = {
'name': '張三',
'is_admin': True,
'items': [
{'name': '筆記本', 'price': 5999},
{'name': '鼠標(biāo)', 'price': 199}
]
}
output = template.render(context)
print(output)
模板實(shí)踐:
- 對用戶輸入進(jìn)行轉(zhuǎn)義防止XSS攻擊
Web開發(fā)核心要點(diǎn):
- 理解HTTP協(xié)議和請求/響應(yīng)生命周期
- 遵循RESTful設(shè)計原則構(gòu)建API
- 實(shí)施安全最佳實(shí)踐(XSS防護(hù)、CSRF保護(hù)等)
進(jìn)階學(xué)習(xí)方向:
掌握Python Web開發(fā)技能,我們將能夠構(gòu)建從簡單博客到復(fù)雜企業(yè)級應(yīng)用的各類系統(tǒng)。不斷實(shí)踐并參與真實(shí)項目是提升技能的最佳途徑!
閱讀原文:原文鏈接
該文章在 2025/7/18 10:54:28 編輯過