我想对我所有的API端点(api/v1/
)使用api版本索引。目前,我是通过像这样构造urlpatterns来实现的:
urlpatterns = [
path('api/v1/units/', include('units.api.urls')),
path('api/v1/accounts/', include('accounts.api.urls')),
]
是否可以更优雅地组织此活动?理想情况下,我希望它看起来像这样:
apipatterns = [
'units/', include('units.api.urls'),
'accounts/', include('accounts.api.urls')
]
urlpatterns = [
path('api/v1/', include(apipatterns)),
]
答案 0 :(得分:1)
Including other URLconfs可以使用from http.server import BaseHTTPRequestHandler, HTTPServer
from os import path
hostName = "localhost"
hostPort = 8080
class RequestHandler(BaseHTTPRequestHandler):
dir = path.abspath(path.dirname(__file__))
content_type = 'text/html'
def _set_headers(self):
self.send_response(200)
self.send_header('Content-Type', self.content_type)
self.send_header('Content-Length', path.getsize(self.getPath()))
self.end_headers()
def do_GET(self):
self._set_headers()
self.wfile.write(self.getContent(self.getPath()))
def getPath(self):
if self.path == '/':
content_path = path.join(dir, 'index.html')
else:
content_path = path.join(dir, str(self.path))
return content_path
def getContent(self, content_path):
with open(content_path, mode='r', encoding='utf-8') as f:
content = f.read()
return bytes(content, 'utf-8')
myServer = HTTPServer((hostName, hostPort), RequestHandler)
myServer.serve_forever()
和path
。
在这种情况下,您可以尝试:
include
因此,路由apipatterns = [
path('units/', include('units.api.urls')),
path('accounts/', include('accounts.api.urls'))
]
urlpatterns = [
path('api/v1/', include(apipatterns)),
]
将由api/v1/units/
处理,而'units.api.urls'
将由api/v1/accounts/
处理
我希望这会有所帮助。
答案 1 :(得分:1)