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.
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.
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 / .
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.
You just need to add "and/boy" to your parameter:
@app.route("/and/boy/<int:param>/")
def go_to(param):
return param
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With