{"id":27949545,"url":"https://github.com/drchai/django-async-pydantic-example","last_synced_at":"2026-05-15T01:36:12.962Z","repository":{"id":172785443,"uuid":"648883638","full_name":"DrChai/django-async-pydantic-example","owner":"DrChai","description":"Django Example of integrate with Pydantic and Async framework","archived":false,"fork":false,"pushed_at":"2023-08-04T01:23:28.000Z","size":108,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-09T17:07:15.040Z","etag":null,"topics":["asyncio","chatgpt","django","django-rest-framework","pydantic","tutorial"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DrChai.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-06-03T04:58:59.000Z","updated_at":"2023-06-05T16:06:31.000Z","dependencies_parsed_at":null,"dependency_job_id":"cd3a9a3c-29d9-4ccb-8874-53948269e551","html_url":"https://github.com/DrChai/django-async-pydantic-example","commit_stats":null,"previous_names":["drchai/django-async-pydantic-example"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/DrChai/django-async-pydantic-example","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DrChai%2Fdjango-async-pydantic-example","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DrChai%2Fdjango-async-pydantic-example/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DrChai%2Fdjango-async-pydantic-example/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DrChai%2Fdjango-async-pydantic-example/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DrChai","download_url":"https://codeload.github.com/DrChai/django-async-pydantic-example/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DrChai%2Fdjango-async-pydantic-example/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33050343,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-13T13:14:54.681Z","status":"online","status_checked_at":"2026-05-14T02:00:06.663Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["asyncio","chatgpt","django","django-rest-framework","pydantic","tutorial"],"created_at":"2025-05-07T15:28:41.724Z","updated_at":"2026-05-15T01:36:12.949Z","avatar_url":"https://github.com/DrChai.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# django-async-pydantic-example\nDjango Example of integration with Pydantic and Async framework\n\n## Background\nWhen building a RESTful API on Django, [Django REST framework](https://www.django-rest-framework.org/) is probably the first framework that comes to mind. It provides all the necessary functions for production. After using DRF for years, it became evident that the performance of core functionality - data validation had limitations. Considering to get benefits of [Pydantic V2](https://docs.pydantic.dev/latest/)(validation logic implemented in Rust) and asyncio, a few scripts in [django_router]() and related [example]() may help.\n\n### 😌 Mitigation Approach\nRewrite DRF's `APIView` to make it [asynchronous](https://github.com/DrChai/django-async-pydantic-example/blob/main/django_router/views.py#L13), and use Pydantic as your data serialization and validation:\n```python\n#schemas.py\nclass QuestionPost(BaseModel):\n    # Pydantic V2:\n    model_config = ConfigDict(from_attributes=True)\n    pub_date: datetime | None = Field(default_factory=timezone.now)\n    question_text: constr(max_length=200)\n    choice_set: list[ChoicePost]\n    # Pydantic V1:\n    # class Config:\n        # orm_mode = True\n        # getter_dict = ModelGetterDict\n\n\nclass QuestionOut(QuestionPost):\n    id: int\n\n#views.py\nclass AsyncPollsDetail(AsyncAPIView):\n    authentication_classes = (authentication.BasicAuthentication,)\n    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n\n    async def get(self, request, *args, **kwargs) -\u003e JsonResponse:\n        instance = await aget_object_or_404(Question.objects.prefetch_related('choice_set',), pk=kwargs['pk'])\n        data = schemas.QuestionOut.from_orm(instance)\n        return JsonResponse(data.dict())\n    #...\n```\nMore examples in [polls](https://github.com/DrChai/django-async-pydantic-example/blob/main/example/polls/views.py)(same application in Django official tutorial) \n### 🌶️ Spicy Approach\nTo take the step further and make the whole interface in `FastAPI` manner. A decorator [`Router`](https://github.com/DrChai/django-async-pydantic-example/blob/main/django_router/routing.py#L286) is provided and a real-world example can be found in the [gpt](https://github.com/DrChai/django-async-pydantic-example/blob/main/example/gpt/views.py) application. `def completion()` returns the response to the client immediately once the awaitable `openai.Completion.acreate()` which interacts with the ChatGPT endpoint yields a result. It then arranges with `asyncio.Task` in a separate thread to handle IO jobs, such as saving the record to the database. \n```python\n#views.py\ngpt_router = Router(authentication_classes=[authentication.BasicAuthentication, ])\n\nasync def save_to_db(view_rts, **view_kwargs):\n    await asyncio.sleep(3)\n    print(f'save_to_db with params: ret: {view_rts}, kwargs: {view_kwargs}')\n\n\nasync def update_stat(view_rts, **view_kwargs):\n    connection = redis.Redis(password=os.environ.get('REDIS_PWD'))\n    user = view_kwargs.get('request').user\n    total_tokens = view_rts.get('usage', {}).get('total_tokens', None)\n    async with connection.pipeline(transaction=True) as pipe:\n        await (pipe.hincrby(f'{user.username}:stats', \"tokens\", total_tokens).\n               hincrby(f'{user.username}:stats', \"req\", 1).execute())\n\n\n@gpt_router.post(\n    r'completion$',\n    permissions=[permissions.IsAuthenticated, ],\n    async_tasks=[update_stat, save_to_db])\nasync def completion(body: CompletionRequest, request: HttpRequest):\n    patch_data = body.dict()\n    patch_data |= {'user': request.user.username}\n    completion_resp = await openai.Completion.acreate(**patch_data)\n    return completion_resp\n# urls.py\nurlpatterns = [\n    path('admin/', admin.site.urls),\n    path(\"polls/\", include(\"polls.urls\")),\n]\nurlpatterns += gpt_router.get_urls()\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdrchai%2Fdjango-async-pydantic-example","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdrchai%2Fdjango-async-pydantic-example","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdrchai%2Fdjango-async-pydantic-example/lists"}