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?
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?
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'),
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.
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