使用 Python 進(jìn)行 Web 開發(fā)的 15 個(gè)框架指南
在Python Web開發(fā)領(lǐng)域,有許多不同類型的框架可供選擇,從輕量級(jí)到全功能型,再到專注于異步處理的框架。本文將介紹多個(gè)Python Web框架,幫助開發(fā)者根據(jù)具體需求選擇合適的工具。
1. Flask:輕量級(jí)Web框架
Flask是一個(gè)用Python編寫的輕量級(jí)Web應(yīng)用框架。它簡(jiǎn)單易學(xué),適合快速開發(fā)小到中型項(xiàng)目。
安裝:
pip install flask
示例:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
解釋:
- from flask import Flask:導(dǎo)入Flask類。
- app = Flask(__name__):創(chuàng)建Flask實(shí)例。
- @app.route('/'):定義路由。
- hello_world():視圖函數(shù)。
- app.run(debug=True):?jiǎn)?dòng)開發(fā)服務(wù)器。
2. Django:全能型Web框架
Django是全功能的Web框架,適用于開發(fā)大型項(xiàng)目。它提供了ORM、用戶認(rèn)證等內(nèi)置功能。
安裝:
pip install django
示例:
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
# views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
解釋:
- INSTALLED_APPS:定義安裝的應(yīng)用。
- urlpatterns:定義URL模式。
- index:視圖函數(shù)。
3. FastAPI:現(xiàn)代Web框架
FastAPI是一個(gè)現(xiàn)代、快速(高性能)的Web框架,基于Python 3.6+類型提示。它用于構(gòu)建API,支持異步操作。
安裝:
pip install fastapi
pip install uvicorn
示例:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
解釋:
- from fastapi import FastAPI:導(dǎo)入FastAPI類。
- app = FastAPI():創(chuàng)建FastAPI實(shí)例。
- @app.get("/"):定義GET路由。
- read_root:異步視圖函數(shù)。
4. Tornado:異步Web框架
Tornado是一個(gè)開源的Python Web框架,專為異步處理而設(shè)計(jì),適用于大規(guī)模并發(fā)請(qǐng)求。
安裝:
pip install tornado
示例:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
解釋:
- import tornado.ioloop:導(dǎo)入IOLoop模塊。
- MainHandler:請(qǐng)求處理器。
- make_app:創(chuàng)建應(yīng)用實(shí)例。
5. Pyramid:靈活的Web框架
Pyramid是一個(gè)靈活且可擴(kuò)展的Web框架,適合開發(fā)任何規(guī)模的Web應(yīng)用程序。
安裝:
pip install pyramid
示例:
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
def hello_world(request):
return {'message': 'Hello, world!'}
if __name__ == '__main__':
config = Configurator()
config.add_route('hello', '/')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 6543, app)
server.serve_forever()
解釋:
- from wsgiref.simple_server import make_server:導(dǎo)入WSGI服務(wù)器。
- Configurator:配置器類。
- add_route:添加路由。
- add_view:添加視圖。
6. Sanic:高性能Web框架
Sanic是一個(gè)輕量級(jí)的Python Web框架,專為高性能而設(shè)計(jì),適用于構(gòu)建RESTful API。
安裝:
pip install sanic
示例:
from sanic import Sanic
from sanic.response import json
app = Sanic("My Hello, world app")
@app.route("/")
async def test(request):
return json({"hello": "world"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)
解釋:
- from sanic import Sanic:導(dǎo)入Sanic類。
- app = Sanic("My Hello, world app"):創(chuàng)建Sanic實(shí)例。
- @app.route("/"):定義路由。
- test:異步視圖函數(shù)。
- app.run(host="0.0.0.0", port=8000, debug=True):?jiǎn)?dòng)服務(wù)器。
7. Bottle:輕量級(jí)Web框架
Bottle是一個(gè)輕量級(jí)的Web框架,適用于小型項(xiàng)目或簡(jiǎn)單的Web應(yīng)用程序。
安裝:
pip install bottle
示例:
from bottle import route, run
@route('/')
def hello_world():
return 'Hello, World!'
run(host='localhost', port=8080, debug=True)
解釋:
- from bottle import route, run:導(dǎo)入route和run函數(shù)。
- @route('/'):定義路由。
- hello_world:視圖函數(shù)。
- run(host='localhost', port=8080, debug=True):?jiǎn)?dòng)服務(wù)器。
8. Starlette:高性能Web框架
Starlette是一個(gè)高性能的Web框架,適用于構(gòu)建現(xiàn)代Web應(yīng)用程序,特別是API。
安裝:
pip install starlette
示例:
from starlette.applications import Starlette
from starlette.responses import JSONResponse, PlainTextResponse
from starlette.routing import Route
async def homepage(request):
return JSONResponse({'hello': 'world'})
app = Starlette(routes=[
Route('/', homepage),
])
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
解釋:
- from starlette.applications import Starlette:導(dǎo)入Starlette類。
- from starlette.responses import JSONResponse:導(dǎo)入JSONResponse類。
- homepage:異步視圖函數(shù)。
- app = Starlette(routes=[Route('/', homepage)]):創(chuàng)建Starlette實(shí)例并定義路由。
- uvicorn.run(app, host="127.0.0.1", port=8000):?jiǎn)?dòng)服務(wù)器。
9. aiohttp:異步Web框架
aiohttp是一個(gè)異步Web框架,適用于構(gòu)建高性能Web應(yīng)用程序和API。
安裝:
pip install aiohttp
示例:
from aiohttp import web
async def handle(request):
name = request.match_info.get('name', "Anonymous")
text = "Hello, " + name
return web.Response(text=text)
app = web.Application()
app.add_routes([web.get('/', handle),
web.get('/{name}', handle)])
web.run_app(app)
解釋:
- from aiohttp import web:導(dǎo)入web模塊。
- handle:異步視圖函數(shù)。
- app = web.Application():創(chuàng)建aiohttp實(shí)例。
- app.add_routes([web.get('/', handle), web.get('/{name}', handle)]):定義路由。
- web.run_app(app):?jiǎn)?dòng)服務(wù)器。
10. Cherrypy:成熟Web框架
Cherrypy是一個(gè)成熟的Web框架,適用于構(gòu)建各種規(guī)模的Web應(yīng)用程序。
安裝:
pip install cherrypy
示例:
import cherrypy
class HelloWorld(object):
@cherrypy.expose
def index(self):
return "Hello, world!"
if __name__ == '__main__':
cherrypy.quickstart(HelloWorld())
解釋:
- import cherrypy:導(dǎo)入cherrypy模塊。
- class HelloWorld(object):定義類。
- @cherrypy.expose:暴露方法。
- index:視圖函數(shù)。
- cherrypy.quickstart(HelloWorld()):?jiǎn)?dòng)服務(wù)器。
11. Falcon:輕量級(jí)Web框架
Falcon是一個(gè)輕量級(jí)的Web框架,適用于構(gòu)建高性能API。
安裝:
pip install falcon
示例:
import falcon
class ThingsResource:
def on_get(self, req, resp):
"""Handles GET requests"""
resp.status = falcon.HTTP_200
resp.body = ('This is an example web service')
app = falcon.App()
app.add_route('/things', ThingsResource())
if __name__ == '__main__':
from wsgiref import simple_server
httpd = simple_server.make_server('127.0.0.1', 8000, app)
httpd.serve_forever()
解釋:
- import falcon:導(dǎo)入falcon模塊。
- class ThingsResource:定義類。
- on_get:處理GET請(qǐng)求。
- app = falcon.App():創(chuàng)建falcon實(shí)例。
- app.add_route('/things', ThingsResource()):定義路由。
- httpd.serve_forever():?jiǎn)?dòng)服務(wù)器。
12. Hug:簡(jiǎn)潔的Web框架
Hug是一個(gè)簡(jiǎn)潔的Web框架,適用于構(gòu)建API,特別強(qiáng)調(diào)簡(jiǎn)潔性和性能。
安裝:
pip install hug
示例:
import hug
@hug.get('/')
def hello_world():
return {'hello': 'world'}
if __name__ == '__main__':
hug.API(__name__).http.serve(port=8000)
解釋:
- import hug:導(dǎo)入hug模塊。
- @hug.get('/'):定義GET路由。
- hello_world:視圖函數(shù)。
- hug.API(__name__).http.serve(port=8000):?jiǎn)?dòng)服務(wù)器。
13. Quart:異步Web框架
Quart是一個(gè)異步Web框架,適用于構(gòu)建異步Web應(yīng)用程序和API。
安裝:
pip install quart
示例:
from quart import Quart, jsonify
app = Quart(__name__)
@app.route('/')
async def hello_world():
return jsonify({'hello': 'world'})
if __name__ == '__main__':
app.run(debug=True)
解釋:
- from quart import Quart:導(dǎo)入Quart類。
- app = Quart(__name__):創(chuàng)建Quart實(shí)例。
- @app.route('/'):定義路由。
- hello_world:異步視圖函數(shù)。
- app.run(debug=True):?jiǎn)?dòng)服務(wù)器。
14. Web2py:全功能Web框架
Web2py是一個(gè)全功能的Web框架,適用于開發(fā)各種規(guī)模的Web應(yīng)用程序。
安裝:
pip install web2py
示例:
def index():
return dict(message="Hello, world!")
if __name__ == '__main__':
from gluon.main import run
run()
解釋:
- def index():視圖函數(shù)。
- return dict(message="Hello, world!"):返回字典。
- from gluon.main import run:導(dǎo)入run函數(shù)。
- run():?jiǎn)?dòng)服務(wù)器。
15. Morepath:可擴(kuò)展Web框架
Morepath是一個(gè)可擴(kuò)展的Web框架,適用于開發(fā)可擴(kuò)展性強(qiáng)的Web應(yīng)用程序。
安裝:
pip install morepath
示例:
import morepath
class App(morepath.App):
pass
@App.path(path="")
def get_root():
return Root()
@App.view(model=Root)
def root_default(self, request):
return "Hello, world!"
class Root:
pass
if __name__ == '__main__':
morepath.scan(App)
App().run()
解釋:
- import morepath:導(dǎo)入morepath模塊。
- class App(morepath.App):定義類。
- @App.path(path=""):定義路徑。
- get_root:獲取根對(duì)象。
- @App.view(model=Root):定義視圖。
- root_default:視圖函數(shù)。
- morepath.scan(App):掃描App類。
- App().run():?jiǎn)?dòng)服務(wù)器。
總結(jié)
本文介紹了多個(gè)Python Web框架,包括輕量級(jí)的Flask、全能型的Django、現(xiàn)代的FastAPI、異步的Tornado、靈活的Pyramid以及更多其他框架。這些框架各有特點(diǎn),可以根據(jù)項(xiàng)目的具體需求來(lái)選擇最適合的框架進(jìn)行開發(fā)。