简体   繁体   English

将实时 Django 项目转换为 REST API 项目

[英]Convert live Django project to REST API project

What is the best way to convert the project from django to django rest framework?将项目从 django 转换为 django rest 框架的最佳方法是什么?

I have live django project, which is completely working, but now it want to convert the project into REST API.我有现场 django 项目,它完全可以工作,但现在它想将该项目转换为 REST API。

I made the rest api for project which has new classes and function for the rest api with (form verification and same logic) copy from the django class which has been implemented. I made the rest api for project which has new classes and function for the rest api with (form verification and same logic) copy from the django class which has been implemented.

So there is duplication of logic, so is there any way to do not replicate the logic and make running both of the classes django and django rest framework?所以有重复的逻辑,那么有什么方法可以不复制逻辑并同时运行 django 和 django rest 框架类?

Problem is when any update needed for any page then i have to code both side django and django rest framework, so there can be some mistake arise in copy.问题是当任何页面需要任何更新时,我必须对 django 和 django rest 框架进行编码,因此在复制时可能会出现一些错误。

One can create an API with Django using custom views but I advise one to use Django REST Framework (DRF) instead as it simplifies the process. One can create an API with Django using custom views but I advise one to use Django REST Framework (DRF) instead as it simplifies the process.

In short,简而言之,

  1. Install DRF with pip install djangorestframework (add it as well to the INSTALLED_APPS in your settings.py file).使用pip install djangorestframework (也将其添加到 settings.py 文件中的INSTALLED_APPS中)。
  2. Create a serializer per your needs (DRF has built-in serializers, like ModelSerializer).根据您的需要创建一个序列化程序(DRF 具有内置的序列化程序,如 ModelSerializer)。 Note that OP can definitely use the models that OP already had in Django.请注意,OP 绝对可以使用 OP 在 Django 中已有的模型。
  3. Create the views ( DRF has generic views ) and specify the URLs to access the views.创建视图( DRF 有通用视图)并指定访问视图的 URL。

Let's say one has an app named books .假设一个人有一个名为books的应用程序。 In order to ensure the code isn't mixed between Django and the API, create an api folder inside of the books app and you should have something like this为了确保代码不会在 Django 和 API 之间混合,请在图书应用程序内创建一个 api 文件夹,您应该有这样的内容

books
-...
-api
--__init__.py
--serializers.py
--views.py
--urls.py 

If OP wills, add reference to that urls.py in OPs main urls.py file,如果 OP 愿意,请在 OPs 主 urls.py 文件中添加对该 urls.py 的引用,

urlpatterns = [
    # ...
    path('api/', include('books.api.urls', namespace='api')),
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM