Define a route for url ending with integer in python


Question

Here is a portion of my python code:

@app.route("/<int:param>/")
def go_to(param):
    return param

The above function routes a url such as www.example.com/12 to this function.

How can I declare a parameter rule to redirect urls ending with integers, such as www.example.com/and/boy/12, to this function?

I'm using the Flask framework.

1
11
1/10/2016 9:57:38 PM

Accepted Answer

You will need Werkzeug routing.

Complete code:

from flask import Flask
from werkzeug.routing import BaseConverter

app = Flask(__name__)

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

# To get all URLs ending with "/number"
@app.route("/<regex('.*\/([0-9]+)'):param>/")
def go_to_one(param):
    return param.split("/")[-1]

# To get all URLs ending with a number
@app.route("/<regex('.*([0-9]+)'):param>/")
def go_to_one(param):
    return param.split("/")[-1]

# To get all URLs without a number
@app.route("/<regex('[^0-9]+'):param>/")
def go_to_two(param):
    return param

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()
7
1/17/2013 4:02:07 AM

You just need to add "and/boy" to your parameter:

@app.route("/and/boy/<int:param>/")
def go_to(param):
    return param

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon