Skip to main content
 首页 » 编程设计

python之在 Django 中将 REST API 放在哪里

2024年10月25日38linjiqin

这是来自 Two Scoops of Django: Best Practices For Django 1.6 的引述:

In the past, we placed all API view code into a dedicated Django app called api or apiv1, with custom logic in some of the REST views, serializers, and more. In theory it’s a pretty good approach, but in practice it means we have logic for a particular app in more than just one location.

Our current approach is to lean on URL configuration. When building a project-wide API we write the REST views in the views.py modules, wire them into a URLConf called something like core/api.py or core/apiv1.py and include that from the project root's urls.py module. This means that we might have something like the following code:

# core/api.py 
 
""" Called from the project root's urls.py URLConf thus: 
url(r" ˆ api/", include("core.api"), namespace="api"), 
""" 
 
from django.conf.urls.defaults import patterns, url 
 
from flavors import views as flavor_views 
from users import views as user_views 
 
urlpatterns = patterns("", 
    # {% url "api:flavors" %} 
    url( 
        regex=r" ˆ flavors/ $ ", 
        view=flavor_views.FlavorCreateReadView.as_view(), 
        name="flavors" 
        ), 
 
    # {% url "api:flavors" flavor.slug %} 
    url( 
        regex=r" ˆ flavors/(?P<slug>[-\w]+)/ $ ", 
        view=flavor_views.FlavorReadUpdateDeleteView.as_view(), 
        name="flavors" 
        ), 
 
    # {% url "api:users" %} 
    url( 
        regex=r" ˆ users/ $ ", 
        view=user_views.UserCreateReadView.as_view(), 
        name="users" 
        ), 
 
    # {% url "api:users" user.slug %} 
    url( 
        regex=r" ˆ users/(?P<slug>[-\w]+)/ $ ", 
        view=user_views.UserReadUpdateDeleteView.as_view(), 
        name="users" 
        ), 
) 

但是我不明白把core/api.py放在哪里。这是一个名为 core 的独立 Django 应用程序吗? api.py 应该放在哪里?

请您参考如下方法:

这意味着创建您拥有的文件 core/api.py(以及一个空的 core/__init__.py 文件),然后添加行 url(r"api/", include("core.api"), namespace="api") 到项目的根 urls.py 文件。

您不必将其命名为core/api.py,这只是作者的建议

what does we write the REST views in the views.py modules mean?

这意味着你所做的,对于你项目中的每个 Django 应用程序,例如 flavors,users 他们将有一个 views.py (或 views/*.py)在其中放置 API 和非 API View 的代码。 (这只是一个合理的命名约定,仅此而已……Django 依赖于 urlpatterns 来告诉它如何连接 url 路由以查看代码)

作为学习 Django 的一种方式,从头开始构建这样的东西真是太棒了。如果您正在做一个严肃的 REST API 项目,请查看 Django REST framework .