これが私のPythonコードの一部です:
@app.route("/<int:param>/")
def go_to(param):
return param
上記の関数は、この関数などにURLをルーティングしwww.example.com/12
ます。
www.example.com/and/boy/12
などの整数で終わるURLをこの関数にリダイレクトするパラメータルールを宣言するにはどうすればよいですか?
私はFlaskフレームワークを使用しています。
パラメータに「and/boy」を追加するだけです。
@app.route("/and/boy/<int:param>/")
def go_to(param):
return param
が必要になりますWerkzeug routing
。
完全なコード:
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()
@app.route('/profile/<username>')
def profile(username):
return f"you are in {username} page"
このような整数などの特定のデータ型が必要な場合は、任意のデータ型でパラメータを渡すことができます
@app.route('/profile/<int:id')
def profile(id):
return f"your profile id is {id}"