¿Puede Flask tener parámetros de URL opcionales?
¿Es posible declarar directamente un parámetro opcional de URL de frasco?
Actualmente estoy procediendo de la siguiente manera:
@user.route('/<userId>')
@user.route('/<userId>/<username>')
def show(userId, username=None):
.................
¿Hay algo que me permita decir directamente que "nombre de usuario" es opcional?
10 answers
Otra forma es escribir
@user.route('/<user_id>', defaults={'username': None})
@user.route('/<user_id>/<username>')
def show(user_id, username):
pass
Pero supongo que quieres escribir una sola ruta y marcar username
como opcional? Si ese es el caso, no creo que sea posible.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-25 16:26:59
Casi lo mismo que Audrius cocinó hace algunos meses, pero es posible que lo encuentre un poco más legible con los valores predeterminados en la cabeza de la función, de la manera en que está acostumbrado con python:
@app.route('/<user_id>')
@app.route('/<user_id>/<username>')
def show(user_id, username='Anonymous'):
return user_id + ':' + username
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-15 15:42:59
Si estás usando Flask-Restful como yo, también es posible de esta manera:
api.add_resource(UserAPI, '/<userId>', '/<userId>/<username>', endpoint = 'user')
A luego en su clase de recurso:
class UserAPI(Resource):
def get(self, userId, username=None):
pass
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-15 09:39:18
@app.route('/', defaults={'path': ''})
@app.route('/< path:path >')
def catch_all(path):
return 'You want path: %s' % path
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-22 19:28:31
@user.route('/<userId>/') # NEED '/' AFTER LINK
@user.route('/<userId>/<username>')
def show(userId, username=None):
pass
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-28 09:25:17
@user.route('/<user_id>', defaults={'username': default_value})
@user.route('/<user_id>/<username>')
def show(user_id, username):
#
pass
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-21 10:40:18
Puede escribir como se muestra en el ejemplo, pero luego obtiene build-error.
Para arreglar esto:
- imprimir aplicación.url_map () en tu root. py
- ves algo como:
<Rule '/<userId>/<username>' (HEAD, POST, OPTIONS, GET) -> user.show_0>
Y
<Rule '/<userId>' (HEAD, POST, OPTIONS, GET) -> .show_1>
- que en la plantilla se puede
{{ url_for('.show_0', args) }}
y{{ url_for('.show_1', args) }}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-06 21:19:46
Sé que este post es muy antiguo, pero trabajé en un paquete que hace esto llamado flask_optional_routes. El código se encuentra en: 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)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-12 02:08:20
Creo que puedes usar Blueprint y eso hará que tu código se vea mejor y prolijamente.
Ejemplo:
from flask import Blueprint
bp = Blueprint(__name__, "example")
@bp.route("/example", methods=["POST"])
def example(self):
print("example")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-24 04:12:40
Desde Flask 0.10 no puede agregar varias rutas a un extremo. Pero puede agregar un punto final falso
@user.route('/<userId>')
def show(userId):
return show_with_username(userId)
@user.route('/<userId>/<username>')
def show_with_username(userId,username=None):
pass
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-06 10:05:10