0

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.

4
  • You can't remove the @app.route..., period. It has to be there. Commented Sep 29, 2020 at 19:43
  • so is there any way to use existing python files and its function and generate all the endpoints dynamically? Commented Sep 29, 2020 at 19:49
  • uhh... that's what you're doing... Commented Sep 29, 2020 at 19:50
  • So i have a python class Users. I want to change all its methods to endpoints without changing anything in this Users class. So i want to access all the methods of Users class in another python class and use app.add_url_rule('/username/', 'userstatus', defaults={"username":None}, there are other classes with many methods, and endpoint generation should be common for all. so i dont want to add "@app.route" in every class on every method. Is there a way to do that?? I am able to pull the classes and its methods + arguments already Commented Sep 29, 2020 at 19:57

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.