Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a route for url ending with integer in python

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.

like image 407
iJade Avatar asked Jan 16 '13 03:01

iJade


People also ask

How do you create a route in Python?

Routing in FlaskThe route() decorator in Flask is used to bind an URL to a function. As a result when the URL is mentioned in the browser, the function is executed to give the result. Here, URL '/hello' rule is bound to the hello_world() function.

How do you put a variable in a URL in flask?

You want a variable URL, which you create by adding <name> placeholders in the URL and accepting corresponding name arguments in the view function. @app. route('/landingpage<id>') # /landingpageA def landing_page(id): ... More typically the parts of a URL are separated with / .

What is app route ()?

App Routing means mapping the URLs to a specific function that will handle the logic for that URL. Modern web frameworks use more meaningful URLs to help users remember the URLs and make navigation simpler. Example: In our application, the URL (“/”) is associated with the root URL.


2 Answers

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

@app.route("/and/boy/<int:param>/")
def go_to(param):
    return param
like image 144
John Brodie Avatar answered Oct 26 '22 22:10

John Brodie


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()
like image 22
ATOzTOA Avatar answered Oct 26 '22 23:10

ATOzTOA