How do I do this in my Django URLs? (.json, .xml)
Suppose this 开发者_运维知识库is my URL route:
(r'^test/?$','hello.life.views.test'),
How do I make it so that people can do .json, .xml, and it would pass a variable to my views.test, so that I know to make json or xml?
to add to @ziang's answer, if you really want to emulate file extensions you could just write the regular expression that way. r'^test\.(?P<extension>(json)|(xml))$'
EDIT: I will add that it's certainly more RESTful to provide the expected return content type as a parameter.
Pass xml or json as a parameter. You can catch it in the URL like this (r'^test/(?P < doc_type > [^/]+)$','hello.life.views.test'),
I have implement something similar:
(r'^test$', 'test'),
(r'^test/(?P<format>json)$', 'test'),
And in views.py, I have something like:
def list(request, format="html"):
if format == 'json':
...
elif format == 'html':
...
...
I have specify two similar url patterns because I want to keep the extension
part optional, and when ignored the default format (html
in my case) is used.
It seems like I can't implement this with an optional pattern in regex, because doing something like (?P<format>json)?
would result in a None
value and the default value will never be used.
Hope this experience can be helpful for you.
I choose a default (json) for my api. If the end-developer wants to work against a different format (yaml, xml, etc) I let them send it as a get parameter:
http://api.mysite.com/getinfo/?format=xml
def get_info_view(request):
format = request.GET.get(format, None)
if format:
# handle alternate (non-json) format
return json_object
I think the key point to the question is can:
so that people can do .json, .xml
Which means the format is optional.
@satoru & @teepark address this as a second url()
entry. However, why not make it just one with good regex?
Solution
url(r'^test(?:\.(?P<format>json|xml))?$', 'hello.life.views.test', name='test'),
Validation: https://regex101.com/r/iQ8gG4/1
Django 3.0
re_path('api/test/values\.json', Api.as_view())
Work perfectly in my case, url looks like : http://127.0.0.1:8000/api/test/values.json
精彩评论