简体   繁体   中英

Register new module as a REST API in python-flask dynamically

Consider I have this following code:

from flask import Flask
from flask import request

app = Flask(__name__)


@app.route('/test', methods=['GET'])
def get():
    if request.method == 'GET':
    return 'hello'

@app.route('/post', methods=['POST'])
def post():
    if request.method == 'POST':
        name = request.form['name']
        return name

if __name__ == '__main__':
    app.run()

I run the code and the server starts with these two API endpoints.

Now, I want to register one more endpoint in the same flask app without restarting the currently server, so that any transactions going on the existing endpoints are not interrupted.

Is there a way I can register a new endpoint with closing/restarting the server on the same flask app?

You can register new rules at any point in your code using Flasks add_url_rule() function. This function is actually called by the route() decorator as well.

@app.route('/')
def index():
    pass

Is equivalent to:

def index():
    pass
app.add_url_rule('/', 'index', index)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM