
掌握API建模:基本概念和實(shí)踐
安裝完成后,我們先來看一個(gè)最簡(jiǎn)單的 Hello World 示例:
from pycubeware_api import API
app = API()
@app.route('/hello')
def hello():
return {'message':'Hello, Pycubeware!'}
if __name__ == '__main__':
app.run()
小貼士:運(yùn)行這段代碼后,在瀏覽器訪問?就能看到返回的 JSON 數(shù)據(jù)啦!
Pycubeware-api 的路由系統(tǒng)非常靈活,支持多種 HTTP 方法:
@app.route('/users', methods=['GET'])
def get_users():
return {'users':['張三', '李四', '王五']}
@app.route('/users', methods=['POST'])
def create_user():
return {'status':'created'}, 201 # 返回狀態(tài)碼 201
獲取查詢參數(shù)和請(qǐng)求體數(shù)據(jù)超級(jí)簡(jiǎn)單:
@app.route('/search')
def search(request):
# 獲取查詢參數(shù)
keyword = request.args.get('q', '')
# 獲取請(qǐng)求體數(shù)據(jù)
data = request.json
return {
'keyword':keyword,
'data':data
}
注意事項(xiàng):request.args 獲取的是 URL 中的查詢參數(shù),而 request.json 獲取的是 POST 請(qǐng)求體中的 JSON 數(shù)據(jù)。
中間件可以幫我們?cè)谡?qǐng)求處理前后做一些額外的工作:
@app.middleware
def log_request(request, next_handler):
print(f'收到請(qǐng)求:{request.path}')
response = next_handler(request)
print(f'響應(yīng)狀態(tài):{response.status}')
return response
優(yōu)雅地處理各種異常情況:
@app.error_handler(404)
def not_found(request, exc):
return {'error':'頁面不存在'}, 404
@app.route('/divide/<int:a>/<int:b>')
def divide(request, a, b):
try:
result = a / b
return {'result':result}
except ZeroDivisionError:
return {'error':'除數(shù)不能為零'}, 400
讓我們來完成一個(gè)簡(jiǎn)單的待辦事項(xiàng) API:
todos = []
@app.route('/todos', methods=['GET'])
def get_todos():
return {'todos':todos}
@app.route('/todos', methods=['POST'])
def add_todo(request):
todo = request.json
todos.append(todo)
return {'status':'success'}, 201
# 練習(xí):試試自己實(shí)現(xiàn)刪除和更新待辦事項(xiàng)的接口
P.S. 想要獲取更多示例代碼,可以訪問 Pycubeware-api 的官方文檔:# Pycubeware-api 進(jìn)階指南:讓你的 API 更加強(qiáng)大!
大家好,我又來啦!上次我們學(xué)習(xí)了 Pycubeware-api 的基礎(chǔ)用法,今天我們來深入探索一些進(jìn)階特性,讓你的 API 更加專業(yè)和強(qiáng)大!
## 1. 請(qǐng)求驗(yàn)證和數(shù)據(jù)校驗(yàn)
在實(shí)際開發(fā)中,對(duì)輸入數(shù)據(jù)的驗(yàn)證非常重要。Pycubeware-api 提供了便捷的驗(yàn)證裝飾器:
```python
from pycubeware_api import API, validator
app = API()
# 定義驗(yàn)證規(guī)則
user_schema = {
'username':{'type':'string', 'required':True, 'minlength':3},
'age':{'type':'integer', 'min':0, 'max':120},
'email':{'type':'string', 'regex':r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'}
}
@app.route('/users', methods=['POST'])
@validator(user_schema)
def create_user(request):
user_data = request.json
# 數(shù)據(jù)已經(jīng)通過驗(yàn)證,可以直接使用
return {'status':'user created', 'data':user_data}
小貼士:驗(yàn)證失敗時(shí),API 會(huì)自動(dòng)返回 400 狀態(tài)碼和詳細(xì)的錯(cuò)誤信息!
處理復(fù)雜的響應(yīng)數(shù)據(jù)結(jié)構(gòu):
from datetime import datetime
from pycubeware_api import serializer
class User:
def __init__(self, name, create_time):
self.name = name
self.create_time = create_time
@serializer.register(User)
def serialize_user(user):
return {
'name':user.name,
'create_time':user.create_time.isoformat()
}
@app.route('/user/info')
def get_user():
user = User('張三', datetime.now())
return {'user':user} # 自動(dòng)序列化
Pycubeware-api 可以輕松集成各種數(shù)據(jù)庫,這里以 SQLite 為例:
import sqlite3
from contextlib import contextmanager
@contextmanager
def get_db():
conn = sqlite3.connect('app.db')
try:
yield conn
finally:
conn.close()
@app.route('/posts', methods=['GET'])
def get_posts():
with get_db() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM posts')
posts = cursor.fetchall()
return {'posts':[
{'id':post[0], 'title':post[1], 'content':post[2]}
for post in posts
]}
支持文件上傳功能:
@app.route('/upload', methods=['POST'])
def upload_file(request):
if 'file' not in request.files:
return {'error':'沒有文件上傳'}, 400
file = request.files['file']
# 保存文件
file.save(f'uploads/{file.filename}')
return {
'message':'上傳成功',
'filename':file.filename
}
管理不同版本的 API:
v1 = API(prefix='/api/v1')
v2 = API(prefix='/api/v2')
@v1.route('/features')
def features_v1():
return {'features':['基礎(chǔ)功能']}
@v2.route('/features')
def features_v2():
return {'features':['基礎(chǔ)功能', '高級(jí)功能']}
# 注冊(cè)到主應(yīng)用
app.mount(v1)
app.mount(v2)
啟用 CORS 支持:
from pycubeware_api import CORS
# 全局配置 CORS
app.use(CORS(
allow_origins=['http://localhost:3000'],
allow_methods=['GET', 'POST', 'PUT', 'DELETE'],
allow_headers=['Content-Type', 'Authorization']
))
來做一個(gè)簡(jiǎn)單的博客 API 系統(tǒng)吧:
# 存儲(chǔ)博客文章的列表
posts = []
@app.route('/posts', methods=['POST'])
@validator({
'title':{'type':'string', 'required':True},
'content':{'type':'string', 'required':True}
})
def create_post(request):
post = {
'id':len(posts) + 1,
'title':request.json['title'],
'content':request.json['content'],
'created_at':datetime.now().isoformat()
}
posts.append(post)
return {'status':'success', 'post':post}, 201
# 練習(xí):實(shí)現(xiàn)獲取文章列表、獲取單篇文章、更新文章、刪除文章的接口
注意事項(xiàng):實(shí)際項(xiàng)目中記得加入適當(dāng)?shù)腻e(cuò)誤處理和數(shù)據(jù)驗(yàn)證!
小伙伴們,今天的 Python 學(xué)習(xí)之旅就到這里啦!記得動(dòng)手完成博客 API 的練習(xí),實(shí)現(xiàn)完整的 CRUD 功能。有問題隨時(shí)在評(píng)論區(qū)問貓哥哦。祝大家學(xué)習(xí)愉快,Python學(xué)習(xí)節(jié)節(jié)高!
文章轉(zhuǎn)自微信公眾號(hào)@建國(guó)聊編程ai
掌握API建模:基本概念和實(shí)踐
程序員常用的API接口管理工具有哪些?
簡(jiǎn)化API縮寫:應(yīng)用程序編程接口終極指南
如何為你的項(xiàng)目挑選最佳API?完整選擇流程解讀
應(yīng)用程序開發(fā)蓬勃發(fā)展的必備開放API
.NET Core Web APi類庫如何內(nèi)嵌運(yùn)行和.NET Core Web API 中的異常處理
.NET Core Web API + Vue By Linux and Windows 部署方案知識(shí)點(diǎn)總結(jié)
優(yōu)化利潤(rùn):計(jì)算并報(bào)告OpenAI支持的API的COGS
用于集成大型語言模型的LLM API
對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力
一鍵對(duì)比試用API 限時(shí)免費(fèi)