,'hello.life.views.test'), How can I make it s...">

How do I do this in my Django urls? (.json, .xml)

Suppose this is my url:

(r'^test/?$','hello.life.views.test'),

      

How can I make it so that people can do .json, .xml and it pass the myview.test variable so that I know to do json or xml?

+2


source to share


5 answers


to add to @ ziang's answer, if you really want to emulate file extensions you can just write the regex that way. r'^test\.(?P<extension>(json)|(xml))$'



EDIT: I'll add that it is of course more RESTful for RENDful to get the expected return type as a parameter.

+8


source


Pass xml or json as parameter. You can catch it in a url like this (r '^ test / (? P <doc_type> [^ /] +) $', 'hello.life.views.test'),



0


source


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.

0


source


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

      

0


source


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

0


source







All Articles