How do I do this in my Django urls? (.json, .xml)
I am implementing something like this:
(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 specified two similar url patterns because I want to keep the part extension
optional, and when ignored, the default format is used ( html
in my case).
I can't seem to implement this with an optional template in the regex because doing something like (?P<format>json)?
will result in a value None
and the default will never be used.
Hope this experience helps you.
source to share
I choose default (json) for my api. If the end developer wants to work against another format (yaml, xml, etc.), I allow them to 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
source to share
I think the key point in the question is:
so people can do .json, .xml
This means that the format is optional.
@satoru and @teepark address this as the second entry url()
. However, why not make it just one with a good regex?
Decision
url(r'^test(?:\.(?P<format>json|xml))?$', 'hello.life.views.test', name='test'),
Validation: https://regex101.com/r/iQ8gG4/1
source to share