【作者主頁(yè)】:吳秋霖
【作者介紹】:Python領(lǐng)域優(yōu)質(zhì)創(chuàng)作者、阿里云博客專家、華為云享專家。長(zhǎng)期致力于Python與爬蟲(chóng)領(lǐng)域研究與開(kāi)發(fā)工作!
【作者推薦】:對(duì)JS逆向感興趣的朋友可以關(guān)注《爬蟲(chóng)JS逆向?qū)崙?zhàn)》,對(duì)分布式爬蟲(chóng)平臺(tái)感興趣的朋友可以關(guān)注《分布式爬蟲(chóng)平臺(tái)搭建與開(kāi)發(fā)實(shí)戰(zhàn)》
還有未來(lái)會(huì)持續(xù)更新的驗(yàn)證碼突防、APP逆向、Python領(lǐng)域等一系列文章
1. 寫(xiě)在前面
??在Python的Web開(kāi)發(fā)領(lǐng)域內(nèi)這些年框架也是層出不窮,早已不再局限于Django、Flask、Tornado甚至是后面的FastApi
曾經(jīng)的玄冥二老也慢慢退居幕后,新的時(shí)代都是年輕人天下!這個(gè)時(shí)代的年輕王者無(wú)疑是Sanic
在網(wǎng)上有對(duì)Python所有的Web框架做過(guò)測(cè)試,可以看到曾經(jīng)的老牌框架已經(jīng)墊底:
官方地址:Sanic
從Python3+后,各種異步很火,所以說(shuō)相對(duì)于傳統(tǒng)的同步框架在某些特定的場(chǎng)景下更加適應(yīng),因?yàn)橥脚c異步在并發(fā)、實(shí)時(shí)性上還是有很大差異的
2. Sanic框架簡(jiǎn)介
2.1 背景
??Sanic最早由ChannelCat團(tuán)隊(duì)開(kāi)發(fā),旨在提供一個(gè)高性能的異步Web框架。其靈感來(lái)自于Flask,并在異步編程的基礎(chǔ)上進(jìn)行了優(yōu)化。Sanic利用Python3.5引入的async/await語(yǔ)法,使得開(kāi)發(fā)者可以編寫(xiě)快速且高效的異步Web應(yīng)用程序
2.2 特征與優(yōu)勢(shì)
??江湖中的朋友們一直都稱之為Python史上最強(qiáng)且最快的Web框架,并且流行度越來(lái)越廣泛
- 高性能:利用異步編程的優(yōu)勢(shì),允許處理大量并發(fā)請(qǐng)求而不會(huì)阻塞線程,從而實(shí)現(xiàn)高性能和低延遲
- 輕量級(jí):核心設(shè)計(jì)非常簡(jiǎn)潔,不依賴大量的外部庫(kù),使得其體積小巧,易于部署和維護(hù)
- 路由功能:提供了簡(jiǎn)單易用的路由功能,讓開(kāi)發(fā)者能夠輕松地定義URL和處理請(qǐng)求的處理程序
- 中間件支持:支持中間件,開(kāi)發(fā)者可以在請(qǐng)求和響應(yīng)處理過(guò)程中添加額外的邏輯
- WebSocket支持:對(duì)WebSocket 提供了良好的支持,允許構(gòu)建實(shí)時(shí)的雙向通信應(yīng)用程序
3. Sanic框架實(shí)戰(zhàn)
3.1. 安裝Sanic
??首先我們使用pip命令安裝Sonic:
pip3 install sanic
3.2. Demo案例編寫(xiě)
如下是一個(gè)簡(jiǎn)單的Sanic應(yīng)用程序,實(shí)現(xiàn)了基本的路由與請(qǐng)求:
# -*- coding: utf-8 -*-
from sanic import Sanic
from sanic import response
app = Sanic("sanic_demo")
@app.route("/")
def run(request):
return response.text("Hello World !")
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8001, debug=True)
在終端中運(yùn)行上面應(yīng)用程序:
程序運(yùn)行后我們?cè)跒g覽器地址中訪問(wèn)http://127.0.0.1:8001就可以看到返回的信息了
接下來(lái)我們編寫(xiě)一個(gè)稍微復(fù)雜的案例代碼,這是一個(gè)簡(jiǎn)化的在線商店系統(tǒng),包括用戶注冊(cè)、商品管理、購(gòu)物車等功能。實(shí)際真實(shí)的商城會(huì)更加復(fù)雜
# -*- coding: utf-8 -*-
from sanic import Sanic, response
from sanic.exceptions import NotFound, ServerError
from sanic_jwt import Initialize, protected
from sanic_session import Session, InMemorySessionInterface
app = Sanic("OnlineStore")
app.config.SECRET_KEY = "supersecretkey"
Initialize(app, authenticate=None)
Session(app, interface=InMemorySessionInterface())
users_db = {}
products_db = {}
carts_db = {}
# Routes
@app.route("/")
async def home(request):
return response.text("歡迎來(lái)到爬蟲(chóng)商店!")
@app.route("/register", methods=["POST"])
async def register(request):
data = request.json
username = data.get("username")
password = data.get("password")
if username in users_db:
return response.json({"message": "Username already exists"}, status=400)
users_db[username] = password
return response.json({"message": "Registration successful"})
@app.route("/login", methods=["POST"])
async def login(request):
data = request.json
username = data.get("username")
password = data.get("password")
if username not in users_db or users_db[username] != password:
return response.json({"message": "Invalid credentials"}, status=401)
token = app.auth.jwt_encode(request, {"username": username})
return response.json({"token": token})
@app.route("/products", methods=["GET"])
@protected()
async def get_products(request):
return response.json({"products": products_db})
@app.route("/add_to_cart", methods=["POST"])
@protected()
async def add_to_cart(request):
data = request.json
username = request.ctx.get("user").get("username")
product_id = data.get("product_id")
quantity = data.get("quantity", 1)
if product_id not in products_db:
return response.json({"message": "Product not found"}, status=404)
if username not in carts_db:
carts_db[username] = {}
if product_id not in carts_db[username]:
carts_db[username][product_id] = quantity
else:
carts_db[username][product_id] += quantity
return response.json({"message": "Product added to cart"})
@app.route("/view_cart", methods=["GET"])
@protected()
async def view_cart(request):
username = request.ctx.get("user").get("username")
if username not in carts_db:
return response.json({"cart": {}}, status=200)
return response.json({"cart": carts_db[username]})
# Error Handlers
@app.exception(NotFound)
async def not_found(request, exception):
return response.json({"message": "Not Found"}, status=404)
@app.exception(ServerError)
async def server_error(request, exception):
return response.json({"message": "Internal Server Error"}, status=500)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)
在上面的代碼中使用了Sanic框架處理用戶注冊(cè)、登錄、商品管理、購(gòu)物車等功能。同時(shí),使用了Sanic JWT進(jìn)行用戶身份驗(yàn)證和會(huì)話管理
最后總結(jié)一下:
Sanic適用于需要高性能、實(shí)時(shí)性的應(yīng)用,以及小型到中型項(xiàng)目
Django適用于大型、全功能的Web應(yīng)用程序,尤其是需要使用內(nèi)置功能快速構(gòu)建應(yīng)用的場(chǎng)景
Flask適用于對(duì)框架提供的功能有更大靈活性和控制需求,以及對(duì)輕量級(jí)框架的偏好文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-751979.html
??好了,到這里又到了跟大家說(shuō)再見(jiàn)的時(shí)候了。創(chuàng)作不易,幫忙點(diǎn)個(gè)贊再走吧。你的支持是我創(chuàng)作的動(dòng)力,希望能帶給大家更多優(yōu)質(zhì)的文章文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-751979.html
到了這里,關(guān)于一文帶你快速了解Python史上最快Web框架的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!