Search code examples
pythonregexgoogle-app-engineurlwebapp2

I'm trying to write a Regex for Google AppEngine URL's to return none, one or more variables


In order to make sure my app runs smoothly I am trying to match a number of URL's like so:

I have the following get function:

class Competition(Handler):
     def get(self, *a):
        if a:
            print a
        else:
            print 'None'

app = webapp2.WSGIApplication([('/', Index),
                               ('/competitions[/]?([^/]+)[/]?([^/]+)[/]?([^/]*)$', Competition),
                              ],debug=True)

The Regex I am using currently is a modified version of this one: Jed Smith helps someone else

And get the following output:

/competitions/one/two/three = ('one', 'two', 'three') - expected result
/competitions/one/two = ('one', 'two', '') - expected result

/competitions/one/ = ('on', 'e', '') - unexpected result
/competitions/one = ('on', 'e', '') - unexpected result

/competitions/ = 404 - Doesn't match pattern
/competitions = 404 - Doesn't match pattern

Ideally I would like the Regex to start by matching the base url:

localhost:8080/competitions (with or without the trailing "/") to the Competitions handler

Then add 0 or more arguments which I can test for... 0 will match the start of my if statement and following statements will be handled as needed.

I could limit it to 3 max variables in *a (ie: /competitions/one/two/three is max) however for the purpose of better learning how to handle this stuff I'd like to learn how to make it match as many as entered.

Any help would be appreciated. Regex is confusing to me.

Cheers

  • edited to fix formatting

Solution

  • So this seems to work. Thanks to @FrankieTheKneeMan for pointing me in the right direction:

    class Test(Handler):
        ''' Test Handler '''
        def get(self, variables):
            variables = filter(None, (variables.split('/')))
            if variables:
                print variables
            else:
                print 'None'
    

    and the regex:

    ('/test[/]?(.*)', Test),
    

    This results in either 'None' if no trailing slash or variables are added... and returns a list of exactly the variables entered with or without trailing slash.

    The filter statement removes empty strings from variables quite nicely and also returns None if there are no variables.

    Hope this helps someone else learning AppEngine... it's been bugging me for a while.