15

これが私のPythonコードの一部です:

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

上記の関数は、この関数などにURLをルーティングしwww.example.com/12ます。

www.example.com/and/boy/12などの整数で終わるURLをこの関数にリダイレクトするパラメータルールを宣言するにはどうすればよいですか?

私はFlaskフレームワークを使用しています。

4

3 に答える 3

18

パラメータに「and/boy」を追加するだけです。

@app.route("/and/boy/<int:param>/")
def go_to(param):
    return param
于 2013-01-16T04:05:34.887 に答える
9

が必要になります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()
于 2013-01-16T03:50:59.290 に答える
-1
@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}"

于 2021-04-23T03:14:03.637 に答える