2

I want to write some urls in flask using regular expression. I have them in django like this

r'^v1/$'
r'^v1/(.+/)$'

I want to recreate them in flask

I have tried following

class RegexConverter(BaseConverter):
    def __init__(self, url_map, *items):
        super(RegexConverter, self).__init__(url_map)
        self.regex = items[0]
app.url_map.converters['regex'] = RegexConverter

api.add_resource(Handler1,'/<regex("^v1/$")>')
api.add_resource(Handler2,'/<regex("^v1/(.+/)$")>')

But it's not working. Showing error

ValueError: malformed url rule: '/<regex("^v1/$")>'
hjpotter92
  • 75,209
  • 33
  • 136
  • 171
hard coder
  • 4,959
  • 5
  • 33
  • 56
  • 1
    Take a look at this: [Does Flask support regular expressions in its URL routing?](http://stackoverflow.com/questions/5870188/does-flask-support-regular-expressions-in-its-url-routing) – salmanwahed Jul 12 '16 at 07:24
  • I had taken above code from that example only – hard coder Jul 12 '16 at 09:01

1 Answers1

1

You are not providing the url_map rule value. It should be:

class RegexConverter(BaseConverter):
    def __init__(self, url_map, *items):
        super(RegexConverter, self).__init__(url_map)
        self.regex = items[0]
app.url_map.converters['regex'] = RegexConverter

api.add_resource(Handler1,'/<regex("^v1/$"):just_v1>')
api.add_resource(Handler2,'/<regex("^v1/(.+/)$"):v1_plus>')

And, in your actual handlers (here Handler1 and Handler2); you'll receive those mapped values as parameters:

class Handler1(Resource):
    def get(self, just_v1):
        # you'll receive `v1/` as the value for `just_v1`
hjpotter92
  • 75,209
  • 33
  • 136
  • 171