Question

I want to use following urls in my api, using a single regex

The urls I needed are

testapi/type1/   

testapi/type2/  

testapi/type2/subtype1/   

testapi/type2/subtype2/  

The regex now I use:

(r'^testapi/(?P<type>type1|type2|type3)/(?P<subtype>.*)/$', my_handler),

Now the issue is not page not fond for urls like myapi/type1/ [urls doesn't have subtype]

What is the best solution

Was it helpful?

Solution

Try:

(r'^testapi/(?P<type>type1|type2|type3)/(?P<subtype>subtype\d+|)/?$', my_handler)

>>  testapi/type2/
>>  [('type2', '')]
>>  testapi/type2/subtype1/
>>  [('type2', 'subtype1')]
>>  testapi/type2/subtype1
>>  [('type2', 'subtype1')]

(?P<subtype>subtype\d+|) will either capture subtype<number> or <empty string> .

If you want to make your regex more flexible, you can substitute following:

  • (?P<subtype>subtype\d+|) --> (?P<subtype>\w+|)
  • (?P<type>type1|type2|type3) --> (?P<type>\w+)

These replacement will not require your url to include subtype and type and accept any string.

OTHER TIPS

Just create two patterns:

r('^testapi/type(?P<type\d+)/subtype(?P<subtype>\d+)/$', my_handler),
r('^testapi/type(?P<type>\d+)/$', my_handler),

The trailing / on your reg is not optional:

(r'^testapi/(?P<type>type1|type2|type3)/(?P<subtype>.*)/$', my_handler),
                                                       ^ here

Try adding a ? to make this optional too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top