Search code examples
google-app-enginerouteswebapp2

Webapp2 extract named parameters from route URL (without the Request, just the URL)


I am using a route like the following in my app:

Route(r'/thing/<some_id>/foo', handler=ThingFoo, name="thing-foo")

This is used to generate a url using uri_for('thing-foo', some_id="something"), which is returned to the user which they store. Then, in another request, the user posts the url returned to them previously, where it needs to be parsed.

I would like to extract the <some_id> pattern's value from the url provided in a similar way to how the router does it to pass the value to the RequestHandler's get/post methods, but the documentation on this seems to be lacking.

Is there something like the following?

route, some_id = webapp2.extract_uri(the_url)

(Of course I could extract the value directly using a regex, but that doesn't seem very DRY).

Here is an example of what I want to do.

def image_url(request, image_blob_key):
    if image_blob_key:
        return request.url_for('image', resource=image_blob_key, _full=True)
    else:
        return None

def blob_key_from_image_url(image_url):
    # Do something here to calculate the blob_key from the URL.
    return blob_key

In one part of my app, image_url is calculated from a blob_key and passed to the user. Later on if they (for example) want to delete the image, they pass the url back in a POST request, and I want to extract the blob_key from it so I can delete it.


Solution

  • Maybe something like this will work for you:

    import webapp2
    
    # somewhere in a request handler:
    route = self.app.router.build_routes.get('my-route-name')
    match = route.regex.match(the_url)
    args, kwargs = webapp2._get_route_variables(match, route.defaults.copy())
    
    # do something with args and kwargs, e.g. 
    # thing = kwargs['thing-foo']
    

    Source code: http://webapp-improved.appspot.com/_modules/webapp2.html#Route

    To be honest, I would simply pass blob_key to the template where users can delete an image, so that I could just build a URL beforehand, e.g.

    uri_for('delete-image', image_key=some_blob_key)