如何将Django Rest Framework的默认URL更改为自定义 [英] How to change the Django Rest Framework's default url to a custom

查看:334
本文介绍了如何将Django Rest Framework的默认URL更改为自定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题几乎说明了一切。



例如将默认网址(



对于自定义对象,我们说:



https://api.example.org/v1/

解决方案

您正在将两个问题混合在一起:


  1. 如何运行 django-rest-framework 在其他域上的项目

  2. 如何更改API的URL路径

要回答第一个,我会说:就做吧。 Django的反向使用请求的域来构建绝对URL。



更新:不要忘记从nginx / apache传递 Host 标头。下面是一个示例Nginx配置:

 服务器{

位置/ {
proxy_set_header主机$ host;
proxy_set_header X-Real-IP $ remote_addr;
proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $ scheme;
proxy_pass http://127.0.0.1:8000;
}

}

第二个(路径,挂载点)设置在django.conf中的 urls.py

  .urls导入url,包括django中的
.contrib导入管理员

来自rest_framework导入路由器

来自quickstart导入视图

router = routers.DefaultRouter()
router.register(r'users',views.UserViewSet)
router.register(r'groups',views.GroupViewSet)


urlpatterns = [
url(r'^ admin /',admin.site.urls),
url(r'^ api-auth /',include('rest_framework.urls',namespace =' rest_framework')),
url(r'^ v1 /',include(router.urls)),#< --------------这里
]


Question says it almost all.

E.g. changing default url (http://127.0.0.1:8000) to a custom (https://api.example.com/v1)

I'm using HyperlinkedModels and everything seems to work properly in development. Moving the app to another server with custom url is giving me problems.

How do I change the default url:

To a custom one, let's say:

https://api.example.org/v1/

解决方案

You are mixing two questions in one:

  1. How to run django-rest-framework project on a different domain
  2. How to change URL path of API

To answer the first one I'd say, "Just do it". Django's reverse uses request's domain to build absolute URL.

UPDATE: don't forget to pass Host header from nginx/apache. Below is a sample nginx config:

server {

    location / {
        proxy_set_header        Host $host;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto $scheme;
        proxy_pass              http://127.0.0.1:8000;
    }

}

The second (path, mount point) is set in the urls.py:

from django.conf.urls import url, include
from django.contrib import admin

from rest_framework import routers

from quickstart import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^v1/', include(router.urls)), # <-------------- HERE
]

这篇关于如何将Django Rest Framework的默认URL更改为自定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆