用于API端点的Django子域configuration

我已经build立了一个Django项目,它使用django-rest-framework提供一些ReSTfunction。 网站和其他function都工作正常。

然而,有一个小问题:我需要我的API端点指向一个不同的子域

例如,当用户访问网站时,他/她可以根据我的urls.py正常导航:

 http://example.com/control_panel 

到现在为止还挺好。 但是,当使用API​​时,我想将其更改为更合适的内容。 所以,而不是http://example.com/api/tasks我需要这成为:

 http://api.example.com/tasks 

我该怎么做?

提前致谢。

PS该网站将运行在Gunicorn上,nginx作为反向代理。

我有一个类似的问题与基于Django的API。 我发现编写一个自定义的中间件类并用它来控制哪个URL在哪个子域上被提供是有用的。

在提供URL时,Django并不关心子域名,所以假设您的DNS设置为api.example.com指向您的Django项目,那么api.example.com/tasks/将调用预期的API视图。

问题是www.example.com/tasks/也会调用API视图,而api.example.com将在浏览器中提供主页。

所以有些中间件可以检查子域是否与URL匹配,并在适当的情况下引发404个响应:

 ## settings.py MIDDLEWARE_CLASSES += ( 'project.middleware.SubdomainMiddleware', ) ## middleware.py api_urls = ['tasks'] # the URLs you want to serve on your api subdomain class SubdomainMiddleware: def process_request(self, request): """ Checks subdomain against requested URL. Raises 404 or returns None """ path = request.get_full_path() # ie /tasks/ root_url = path.split('/')[1] # ie tasks domain_parts = request.get_host().split('.') if (len(domain_parts) > 2): subdomain = domain_parts[0] if (subdomain.lower() == 'www'): subdomain = None domain = '.'.join(domain_parts[1:]) else: subdomain = None domain = request.get_host() request.subdomain = subdomain # ie 'api' request.domain = domain # ie 'example.com' # Loosen restrictions when developing locally or running test suite if not request.domain in ['localhost:8000', 'testserver']: return # allow request if request.subdomain == "api" and root_url not in api_urls: raise Http404() # API subdomain, don't want to serve regular URLs elif not subdomain and root_url in api_urls: raise Http404() # No subdomain or www, don't want to serve API URLs else: raise Http404() # Unexpected subdomain return # allow request 

怎么样Django-dynamicsites-lite 。 而且你的代码会更干净,因为API和站点在不同的文件夹中。