An asynchronous Web API framework based on Starlette, inspired by Django REST Framework
Project description
Async DRF API
一个基于 Starlette 的异步 Web API 框架,灵感来自 Django REST Framework,提供简洁的 API 开发体验。 仓库链接:https://github.com/sixsfish/async_drf_api
功能特性
- 🚀 异步支持 - 基于 Starlette 和 asyncio,支持高并发
- 📝 自动 API 文档 - 自动生成 Swagger UI 和 ReDoc 文档
- 🗄️ 异步 ORM - 内置异步数据库操作(支持 SQLite)
- 🔄 序列化器 - 类似 DRF 的数据序列化/反序列化
- 🎯 视图集 - 支持 ViewSet 和通用视图
- 🛣️ 路由装饰器 - 简洁的路由定义方式
- 🔌 中间件支持 - 灵活的中间件机制
安装
pip install async-drf-api
快速开始
1. 创建应用
from async_drf_api.web.app import AsyncDrfApiApp
from async_drf_api.web.response import Response
app = AsyncDrfApiApp()
@app.get('/')
async def home(request):
return Response({'message': 'Hello, Async DRF API!'})
@app.post('/api/users')
async def create_user(request):
data = await request.json()
# 处理数据...
return Response({'id': 1, 'name': data.get('name')}, status_code=201)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)
2. 使用 ORM 模型
from async_drf_api.orm.models import Model
from async_drf_api.orm.field import CharField, IntegerField
from async_drf_api.orm.connection import Database
# 定义模型
class User(Model):
name = CharField(max_length=100)
age = IntegerField()
class Meta:
table_name = 'users'
# 配置数据库
from async_drf_api.conf import get_settings
settings = get_settings()
settings.DATABASE_NAME = 'myapp.db'
# 创建表
await User.create_table()
# 使用模型
user = await User.objects.create(name='Alice', age=30)
users = await User.objects.all()
user = await User.objects.get(id=1)
await user.update(name='Bob')
await user.delete()
3. 使用序列化器
from async_drf_api.serializers import Serializer
class UserSerializer(Serializer):
name = CharField()
age = IntegerField()
def validate_age(self, value):
if value < 0:
raise ValueError('Age must be positive')
return value
# 序列化
user = User(name='Alice', age=30)
serializer = UserSerializer(user)
data = serializer.data # {'name': 'Alice', 'age': 30}
# 反序列化
data = {'name': 'Bob', 'age': 25}
serializer = UserSerializer(data=data)
if serializer.is_valid():
validated_data = serializer.validated_data
4. 使用 ViewSet 和 Router
from async_drf_api.views.generic import GenericAPIView
from async_drf_api.views.router import SimpleRouter
class UserViewSet(GenericAPIView):
queryset = User.objects
serializer_class = UserSerializer
# 注册路由
router = SimpleRouter()
router.register('/api/users', UserViewSet)
app.set_router(router)
5. 生命周期事件
@app.on_startup
async def startup():
"""应用启动时执行"""
print('Application starting...')
# 初始化数据库连接等
@app.on_shutdown
async def shutdown():
"""应用关闭时执行"""
print('Application shutting down...')
# 清理资源等
API 文档
启动应用后,访问以下地址查看自动生成的 API 文档:
- Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc - OpenAPI Schema:
http://localhost:8000/openapi.json
完整示例
import asyncio
from async_drf_api.web.app import AsyncDrfApiApp
from async_drf_api.web.response import Response
from async_drf_api.orm.models import Model
from async_drf_api.orm.field import CharField, IntegerField
from async_drf_api.orm.connection import Database
from async_drf_api.serializers import Serializer, CharField as SerializerCharField, IntegerField as SerializerIntegerField
from async_drf_api.views.generic import GenericAPIView
from async_drf_api.views.router import SimpleRouter
from async_drf_api.conf import get_settings
# 配置数据库
settings = get_settings()
settings.DATABASE_NAME = 'example.db'
# 定义模型
class User(Model):
name = CharField(max_length=100)
age = IntegerField()
class Meta:
table_name = 'users'
# 定义序列化器
class UserSerializer(Serializer):
name = SerializerCharField()
age = SerializerIntegerField()
# 定义视图集
class UserViewSet(GenericAPIView):
queryset = User.objects
serializer_class = UserSerializer
# 创建应用
app = AsyncDrfApiApp(title="Example API")
# 注册路由
router = SimpleRouter()
router.register('/api/users', UserViewSet)
app.set_router(router)
# 添加自定义路由
@app.get('/api/health')
async def health_check(request):
return Response({'status': 'ok'})
启动应用:uvicorn main:app --port=8000
依赖
starlette- Web 框架uvicorn- ASGI 服务器
Async DRF API---ENGLISH
An asynchronous Web API framework based on Starlette, inspired by Django REST Framework, providing a clean API development experience. Repository: https://github.com/sixsfish/async_drf_api
Features
- 🚀 Async Support - Based on Starlette and asyncio, supports high concurrency
- 📝 Auto API Documentation - Automatically generates Swagger UI and ReDoc documentation
- 🗄️ Async ORM - Built-in asynchronous database operations (supports SQLite)
- 🔄 Serializers - Data serialization/deserialization similar to DRF
- 🎯 ViewSets - Supports ViewSet and generic views
- 🛣️ Route Decorators - Clean route definition
- 🔌 Middleware Support - Flexible middleware mechanism
Installation
pip install async-drf-api
Quick Start
1. Create Application
from async_drf_api.web.app import AsyncDrfApiApp
from async_drf_api.web.response import Response
app = AsyncDrfApiApp()
@app.get('/')
async def home(request):
return Response({'message': 'Hello, Async DRF API!'})
@app.post('/api/users')
async def create_user(request):
data = await request.json()
# Process data...
return Response({'id': 1, 'name': data.get('name')}, status_code=201)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)
2. Use ORM Models
from async_drf_api.orm.models import Model
from async_drf_api.orm.field import CharField, IntegerField
from async_drf_api.orm.connection import Database
# Define model
class User(Model):
name = CharField(max_length=100)
age = IntegerField()
class Meta:
table_name = 'users'
# Configure database
from async_drf_api.conf import get_settings
settings = get_settings()
settings.DATABASE_NAME = 'myapp.db'
# Create table
await User.create_table()
# Use model
user = await User.objects.create(name='Alice', age=30)
users = await User.objects.all()
user = await User.objects.get(id=1)
await user.update(name='Bob')
await user.delete()
3. Use Serializers
from async_drf_api.serializers import Serializer
class UserSerializer(Serializer):
name = CharField()
age = IntegerField()
def validate_age(self, value):
if value < 0:
raise ValueError('Age must be positive')
return value
# Serialize
user = User(name='Alice', age=30)
serializer = UserSerializer(user)
data = serializer.data # {'name': 'Alice', 'age': 30}
# Deserialize
data = {'name': 'Bob', 'age': 25}
serializer = UserSerializer(data=data)
if serializer.is_valid():
validated_data = serializer.validated_data
4. Use ViewSets and Router
from async_drf_api.views.generic import GenericAPIView
from async_drf_api.views.router import SimpleRouter
class UserViewSet(GenericAPIView):
queryset = User.objects
serializer_class = UserSerializer
# Register routes
router = SimpleRouter()
router.register('/api/users', UserViewSet)
app.set_router(router)
5. Lifecycle Events
@app.on_startup
async def startup():
"""Execute on application startup"""
print('Application starting...')
# Initialize database connections, etc.
@app.on_shutdown
async def shutdown():
"""Execute on application shutdown"""
print('Application shutting down...')
# Clean up resources, etc.
API Documentation
After starting the application, visit the following URLs to view auto-generated API documentation:
- Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc - OpenAPI Schema:
http://localhost:8000/openapi.json
Complete Example
import asyncio
from async_drf_api.web.app import AsyncDrfApiApp
from async_drf_api.web.response import Response
from async_drf_api.orm.models import Model
from async_drf_api.orm.field import CharField, IntegerField
from async_drf_api.orm.connection import Database
from async_drf_api.serializers import Serializer, CharField as SerializerCharField, IntegerField as SerializerIntegerField
from async_drf_api.views.generic import GenericAPIView
from async_drf_api.views.router import SimpleRouter
from async_drf_api.conf import get_settings
# Configure database
settings = get_settings()
settings.DATABASE_NAME = 'example.db'
# Define model
class User(Model):
name = CharField(max_length=100)
age = IntegerField()
class Meta:
table_name = 'users'
# Define serializer
class UserSerializer(Serializer):
name = SerializerCharField()
age = SerializerIntegerField()
# Define viewset
class UserViewSet(GenericAPIView):
queryset = User.objects
serializer_class = UserSerializer
# Create application
app = AsyncDrfApiApp(title="Example API")
# Register routes
router = SimpleRouter()
router.register('/api/users', UserViewSet)
app.set_router(router)
# Add custom routes
@app.get('/api/health')
async def health_check(request):
return Response({'status': 'ok'})
Run application:uvicorn main:app --port=8000
Dependencies
starlette- Web frameworkuvicorn- ASGI server
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file async_drf_api-0.1.0.tar.gz.
File metadata
- Download URL: async_drf_api-0.1.0.tar.gz
- Upload date:
- Size: 15.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3fe1ab03e53b4a1dc5037dcebeb936a0dec3546e0500c034916b6a9bd0a3d16d
|
|
| MD5 |
76ff733e2463866003b0bf850e987759
|
|
| BLAKE2b-256 |
817adba22196102b58641f637a9c713661762cd7b2dd6b7f1578694a996c3013
|
File details
Details for the file async_drf_api-0.1.0-py3-none-any.whl.
File metadata
- Download URL: async_drf_api-0.1.0-py3-none-any.whl
- Upload date:
- Size: 19.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a208e3b3a253f5eab8aeb872f4d247a9b72c378af3af43b41dfab2ac34a6195c
|
|
| MD5 |
c37eb81cf5d9bfa9b43fee1239d0294c
|
|
| BLAKE2b-256 |
6242b28c38a652cef9dae8cc2ed673d01036d75a4e83ea1c75a73e27859406e4
|