name
name

Reputation: 19

how to use parameters in add_url_rule flask

I am trying to create a script to basically create all the flask endpoint from existing python classes/methods.

one way which i came across was app.add_url_rule

but it is not working for me

@app.route('/username/<username>')
def userstatus(username):
    print("user is logged in")
app.add_url_rule('/username/', 'userstatus', defaults={"username":None})**

the above one is working but if i remove @app.route('/username/<username>') and try juust with add_url_rule, it is not working.

Upvotes: 0

Views: 3906

Answers (1)

oschlueter
oschlueter

Reputation: 2698

You have to provide the rule, the end point and the view function to add_url_rule (see API doc):

from flask import Flask

app = Flask(__name__)


def userstatus(username):
    return f'Hello {username}!'


app.add_url_rule('/username/<username>', '/username/<username>', userstatus)

Then you can start your flask app:

(venv) $ FLASK_APP=url_rule.py flask run
 * Serving Flask app "url_rule.py"
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

And send queries in a different shell (or your browser):

$ curl http://localhost:5000/username/alice && echo
Hello alice!
$ curl http://localhost:5000/username/bob && echo
Hello bob!

You could then use your existing python files and call add_url_rule for the endpoints you want to create dynamically.

Upvotes: 3

Related Questions