Is it possible to directly declare a flask URL optional parameter?
Currently I’m proceeding the following way:
@user.route('/<userId>')
@user.route('/<userId>/<username>')
def show(userId, username=None):
pass
How can I directly say that username is optional?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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:
@app.route('/<user_id>')
@app.route('/<user_id>/<username>')
def show(user_id, username='Anonymous'):
return user_id + ':' + username
Method 3
If you are using Flask-Restful like me, it is also possible this way:
api.add_resource(UserAPI, '/<userId>', '/<userId>/<username>', endpoint = 'user')
a then in your Resource class:
class UserAPI(Resource):
def get(self, userId, username=None):
pass
Method 4
@user.route('/<userId>/') # NEED '/' AFTER LINK
@user.route('/<userId>/<username>')
def show(userId, username=None):
pass
https://flask.palletsprojects.com/en/1.1.x/quickstart/#unique-urls-redirection-behavior
Method 5
@user.route('/<user_id>', defaults={'username': default_value})
@user.route('/<user_id>/<username>')
def show(user_id, username):
#
pass
Method 6
@app.route('/', defaults={'path': ''})
@app.route('/< path:path >')
def catch_all(path):
return 'You want path: %s' % path
http://flask.pocoo.org/snippets/57/
Method 7
Almost the same as skornos, but with variable declarations for a more explicit answer. It can work with Flask-RESTful extension:
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class UserAPI(Resource):
def show(userId, username=None):
pass
api.add_resource(UserAPI, '/<userId>', '/<userId>/<username>', endpoint='user')
if __name__ == '__main__':
app.run()
The add_resource method allows pass multiples URLs. Each one will be routed to your Resource.
Method 8
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.
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)
Method 9
You can write as you show in example, but than you get build-error.
For fix this:
- print app.url_map () in you root .py
- you see something like:
<Rule '/<userId>/<username>' (HEAD, POST, OPTIONS, GET) -> user.show_0>
and
<Rule '/<userId>' (HEAD, POST, OPTIONS, GET) -> .show_1>
- than in template you can
{{ url_for('.show_0', args) }}and{{ url_for('.show_1', args) }}
Method 10
Since Flask 0.10 you can`t add multiple routes to one endpoint. But you can add fake endpoint
@user.route('/<userId>')
def show(userId):
return show_with_username(userId)
@user.route('/<userId>/<username>')
def show_with_username(userId,username=None):
pass
Method 11
I think you can use Blueprint and that’s will make ur code look better and neatly.
example:
from flask import Blueprint
bp = Blueprint(__name__, "example")
@bp.route("/example", methods=["POST"])
def example(self):
print("example")
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0