Optional routes in Flask

2

Is there any way to make optional routes?

For example:

@app.route(r'/contacts/<key>/<name>?', methods=['GET'])
def contact_deatils(key, name = None):
   print(key, name)

   return 'mensaje de prueba'

if you place parameters  to the routes yes, but also that it is optional for example. I have this in routes '/contacts/<key>/<name>?' if I place the url /contacts/1/ , that will let me see the page, but I get an error and it forces me to place the two parameters. And when placing the url /contacts/1/nombre/ , also show me the page

    
asked by Albert Arias 26.03.2018 в 23:26
source

1 answer

2

It is possible to use multiple routes for the same function so that you have something like this:

@app.route('/contacts/<key>/', methods=['GET'])
@app.route('/contacts/<key>/<name>', methods=['GET'])
def contact_deatils(key, name=None):
   # ...

You may have to validate, within the function, the parameters you have received. In this case key will always be present but name may be None :

@app.route('/contacts/<key>/', methods=['GET'])
@app.route('/contacts/<key>/<name>', methods=['GET'])
def contact_deatils(key, name=None):
   # ...
   if not name:
       # Hacer algo 
   else:
       # Hacer otra cosa

It's simple.

By the way, I do not think "raw string" is necessary for routes: r'...'

    
answered by 28.03.2018 / 16:44
source