user111677
user111677

Reputation: 951

How to write a RESTful URL path regex in GAE/Python for n parameters?

Currently I have three URL paths that map to ServiceHandler. How do I combine the three into one neat regex that can pass n number of arguments to ServiceHandler?

(r'/s/([^/]*)', ServiceHandler),
(r'/s/([^/]*)/([^/]*)', ServiceHandler),
(r'/s/([^/]*)/([^/]*)/([^/]*)', ServiceHandler)

Upvotes: 2

Views: 2049

Answers (3)

John La Rooy
John La Rooy

Reputation: 304335

This should work for any number

(r'(?<!^)/([^/]+)', ServiceHandler)

Since I've looked in urlresolvers.py, I see this won't work although you could patch the correct behaviour into urlresolvers.py using regex.findall instead of re.search.

Upvotes: 0

Mez
Mez

Reputation: 24953

(r'^/s/(([^/]*)((/[^/]+)*))$', ServiceHandler)

Should do the trick to match any amount of

/s/foo/bar/baz/to/infinity/and/beyond/

You can also limit it to a range by doing something like

^/s/(([^/]*)((/[^/]+){0,2}))$

Which would only match things like

/s/foo/bar/baz
/s/foo/bar
/s/foo

but not

/s/foo/bar/baz/pirate
/s

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304335

You can try something like

(r'/s/([^/]*)/?([^/]*)/?([^/]*)', ServiceHandler)

I think you will always get 3 parameters to ServiceHandler but the ones that aren't used will be empty strings

Upvotes: 0

Related Questions