pip install pycubeware-api

安裝完成后,我們先來看一個(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ù)啦!

1.路由系統(tǒng)詳解

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

2.請(qǐng)求參數(shù)處理

獲取查詢參數(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ù)。

3.中間件功能

中間件可以幫我們?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

4. 錯(cuò)誤處理

優(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

5.實(shí)戰(zhàn)小練習(xí)

讓我們來完成一個(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)的接口

6.總結(jié)要點(diǎn)

  1. Pycubeware-api 的基本使用方法
  2. 路由系統(tǒng)和 HTTP 方法
  3. 請(qǐng)求參數(shù)的獲取和處理
  4. 中間件的使用
  5. 錯(cuò)誤處理機(jī)制

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ò)誤信息!

7. 響應(yīng)序列化

處理復(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)序列化

8.數(shù)據(jù)庫集成

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

]}

9.文件上傳處理

支持文件上傳功能:

@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

}

10.API 版本控制

管理不同版本的 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)

11.跨域資源共享(CORS)

啟用 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']

))

12.實(shí)戰(zhàn)練習(xí):小型博客 API

來做一個(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)證!

13.總結(jié)要點(diǎn)

  1. 請(qǐng)求數(shù)據(jù)驗(yàn)證的重要性和實(shí)現(xiàn)方式
  2. 響應(yīng)數(shù)據(jù)序列化處理
  3. 數(shù)據(jù)庫操作的最佳實(shí)踐
  4. 文件上傳處理技巧
  5. API 版本控制的實(shí)現(xiàn)方法
  6. CORS 配置和安全考慮

小伙伴們,今天的 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

上一篇:

使用 Dify、Meilisearch、零一萬物模型實(shí)現(xiàn)最簡(jiǎn)單的 RAG 應(yīng)用(三):AI 電影推薦

下一篇:

API市場(chǎng)與API門戶:有何區(qū)別?
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)