如何将Django Rest Framework的默认URL更改为自定义 [英] How to change the Django Rest Framework's default url to a custom
问题描述
问题几乎说明了一切。
例如将默认网址(
对于自定义对象,我们说:
https://api.example.org/v1/
您正在将两个问题混合在一起:
- 如何运行
django-rest-framework
在其他域上的项目 - 如何更改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:
- How to run
django-rest-framework
project on a different domain - 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屋!