Flask有可选的URL参数吗?

时间:2022-08-24 14:48:44

Is it possible to directly declare a flask URL optional parameter?

是否可以直接声明flask URL可选参数?

Currently I'm proceeding the following way:

目前我正在进行以下工作:

@user.route('/<userId>')
@user.route('/<userId>/<username>')
def show(userId, username=None):
    .................

Is there anything that can allow me to directly say that "username" is optional?

有什么可以让我直接说“用户名”是可选的吗?

10 个解决方案

#1


193  

Another way is to write

另一种方法是写作。

@user.route('/<user_id>', defaults={'username': None})
@user.route('/<user_id>/<username>')
def show(user_id, username):
    pass

But I guess that you want to write a single route and mark username as optional? If that's the case, I don't think it's possible.

但是我猜你想写一条路径,并把用户名标记为可选?如果是这样的话,我认为这是不可能的。

#2


130  

Almost the same as Audrius cooked up some months ago, but you might find it a bit more readable with the defaults in the function head - the way you are used to with python:

几乎和几个月前Audrius做的一样,但是你可能会发现它在函数头的默认值下更容易读懂——就像你在python中习惯的那样:

@app.route('/<user_id>')
@app.route('/<user_id>/<username>')
def show(user_id, username='Anonymous'):
    return user_id + ':' + username

#3


42  

If you are using Flask-Restful like me, it is also possible this way:

如果你像我一样使用Flask-Restful,也可以这样:

api.add_resource(UserAPI, '/<userId>', '/<userId>/<username>', endpoint = 'user')

a then in your Resource class:

a那么在你的资源类:

class UserAPI(Resource):

  def get(self, userId, username=None):
    pass

#4


9  

@app.route('/', defaults={'path': ''})
@app.route('/< path:path >')
def catch_all(path):
    return 'You want path: %s' % path

http://flask.pocoo.org/snippets/57/

http://flask.pocoo.org/snippets/57/

#5


7  

@user.route('/<userId>/')  # NEED '/' AFTER LINK
@user.route('/<userId>/<username>')
def show(userId, username=None):
    pass

http://flask.pocoo.org/docs/0.10/quickstart/#routing

http://flask.pocoo.org/docs/0.10/quickstart/路由

#6


5  

@user.route('/<user_id>', defaults={'username': default_value})
@user.route('/<user_id>/<username>')
def show(user_id, username):
   #
   pass

#7


0  

You can write as you show in example, but than you get build-error.

您可以像示例中所示的那样编写,但不能获得构建错误。

For fix this:

为解决这个问题:

  1. print app.url_map () in you root .py
  2. 在根.py中打印app.url_map ()
  3. you see something like:
  4. 你看到类似:

<Rule '/<userId>/<username>' (HEAD, POST, OPTIONS, GET) -> user.show_0>

/ ' (HEAD, POST, OPTIONS, GET) ->用户。show_0>。

and

<Rule '/<userId>' (HEAD, POST, OPTIONS, GET) -> .show_1>

' (HEAD, POST, OPTIONS, GET) -> .show_1>

  1. than in template you can {{ url_for('.show_0', args) }} and {{ url_for('.show_1', args) }}
  2. 在模板中,您可以{url_for(')。show_0', args)}和{url_for('。show_1 ',args)} }

#8


0  

I know this post is really old but I worked on a package that does this called flask_optional_routes. The code is located at: https://github.com/sudouser2010/flask_optional_routes.

我知道这篇文章很老,但是我做了一个包,叫做flask_optional_route。代码位于:https://github.com/sudouser2010/flask_optional_path。

from flask import Flask

from flask_optional_routes import OptionalRoutes


app = Flask(__name__)
optional = OptionalRoutes(app)

@optional.routes('/<user_id>/<user_name>?/')
def foobar(user_id, user_name=None):
    return 'it worked!'

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)

#9


-5  

I think you can use Blueprint and that's will make ur code look better and neatly.

我认为您可以使用Blueprint,这将使您的代码看起来更好更整洁。

example:

例子:

from flask import Blueprint

bp = Blueprint(__name__, "example")

@bp.route("/example", methods=["POST"])
def example(self):
   print("example")

#10


-6  

Since Flask 0.10 you can`t add multiple routes to one endpoint. But you can add fake endpoint

由于Flask 0.10,您不能将多个路由添加到一个端点。但是可以添加伪端点

@user.route('/<userId>')
def show(userId):
   return show_with_username(userId)

@user.route('/<userId>/<username>')
def show_with_username(userId,username=None):
   pass

#1


193  

Another way is to write

另一种方法是写作。

@user.route('/<user_id>', defaults={'username': None})
@user.route('/<user_id>/<username>')
def show(user_id, username):
    pass

But I guess that you want to write a single route and mark username as optional? If that's the case, I don't think it's possible.

但是我猜你想写一条路径,并把用户名标记为可选?如果是这样的话,我认为这是不可能的。

#2


130  

Almost the same as Audrius cooked up some months ago, but you might find it a bit more readable with the defaults in the function head - the way you are used to with python:

几乎和几个月前Audrius做的一样,但是你可能会发现它在函数头的默认值下更容易读懂——就像你在python中习惯的那样:

@app.route('/<user_id>')
@app.route('/<user_id>/<username>')
def show(user_id, username='Anonymous'):
    return user_id + ':' + username

#3


42  

If you are using Flask-Restful like me, it is also possible this way:

如果你像我一样使用Flask-Restful,也可以这样:

api.add_resource(UserAPI, '/<userId>', '/<userId>/<username>', endpoint = 'user')

a then in your Resource class:

a那么在你的资源类:

class UserAPI(Resource):

  def get(self, userId, username=None):
    pass

#4


9  

@app.route('/', defaults={'path': ''})
@app.route('/< path:path >')
def catch_all(path):
    return 'You want path: %s' % path

http://flask.pocoo.org/snippets/57/

http://flask.pocoo.org/snippets/57/

#5


7  

@user.route('/<userId>/')  # NEED '/' AFTER LINK
@user.route('/<userId>/<username>')
def show(userId, username=None):
    pass

http://flask.pocoo.org/docs/0.10/quickstart/#routing

http://flask.pocoo.org/docs/0.10/quickstart/路由

#6


5  

@user.route('/<user_id>', defaults={'username': default_value})
@user.route('/<user_id>/<username>')
def show(user_id, username):
   #
   pass

#7


0  

You can write as you show in example, but than you get build-error.

您可以像示例中所示的那样编写,但不能获得构建错误。

For fix this:

为解决这个问题:

  1. print app.url_map () in you root .py
  2. 在根.py中打印app.url_map ()
  3. you see something like:
  4. 你看到类似:

<Rule '/<userId>/<username>' (HEAD, POST, OPTIONS, GET) -> user.show_0>

/ ' (HEAD, POST, OPTIONS, GET) ->用户。show_0>。

and

<Rule '/<userId>' (HEAD, POST, OPTIONS, GET) -> .show_1>

' (HEAD, POST, OPTIONS, GET) -> .show_1>

  1. than in template you can {{ url_for('.show_0', args) }} and {{ url_for('.show_1', args) }}
  2. 在模板中,您可以{url_for(')。show_0', args)}和{url_for('。show_1 ',args)} }

#8


0  

I know this post is really old but I worked on a package that does this called flask_optional_routes. The code is located at: https://github.com/sudouser2010/flask_optional_routes.

我知道这篇文章很老,但是我做了一个包,叫做flask_optional_route。代码位于:https://github.com/sudouser2010/flask_optional_path。

from flask import Flask

from flask_optional_routes import OptionalRoutes


app = Flask(__name__)
optional = OptionalRoutes(app)

@optional.routes('/<user_id>/<user_name>?/')
def foobar(user_id, user_name=None):
    return 'it worked!'

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)

#9


-5  

I think you can use Blueprint and that's will make ur code look better and neatly.

我认为您可以使用Blueprint,这将使您的代码看起来更好更整洁。

example:

例子:

from flask import Blueprint

bp = Blueprint(__name__, "example")

@bp.route("/example", methods=["POST"])
def example(self):
   print("example")

#10


-6  

Since Flask 0.10 you can`t add multiple routes to one endpoint. But you can add fake endpoint

由于Flask 0.10,您不能将多个路由添加到一个端点。但是可以添加伪端点

@user.route('/<userId>')
def show(userId):
   return show_with_username(userId)

@user.route('/<userId>/<username>')
def show_with_username(userId,username=None):
   pass