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?
@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
@user.route('/<user_id>', defaults={'username': default_value})
@user.route('/<user_id>/<username>')
def show(user_id, username):
#
pass
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
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.
You can write as you show in example, but than you get build-error.
For fix this:
<Rule '/<userId>/<username>' (HEAD, POST, OPTIONS, GET) -> user.show_0>
and
<Rule '/<userId>' (HEAD, POST, OPTIONS, GET) -> .show_1>
{{ url_for('.show_0', args) }}
and {{ url_for('.show_1', args) }}
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
@app.route('/', defaults={'path': ''})
@app.route('/< path:path >')
def catch_all(path):
return 'You want path: %s' % path
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
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)
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")
Source: Stackoverflow.com