[Python] Error with flask server after installing CORS: AttributeError: 'FlaskApp' object has...

Discussão em 'Python' iniciado por Stack, Março 20, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following code for an flask server:

    from flask import render_template
    import connexion

    # Create the application instance
    app = connexion.App(__name__, specification_dir="./")

    # read the swagger.yml file to configure the endpoints
    app.add_api("swagger.yml")

    # Create a URL route in our application for "/"
    @app.route("/")
    def home():
    """
    This function just responds to the browser URL
    localhost:5000/

    :return: the rendered template "home.html"
    """
    return render_template("home.html")


    if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=5100)


    Which works fine, but I need to add CORS support, so I intalled the library:

    pip3 install -U flask-cors


    And the lines:

    from flask_cors import CORS
    CORS(app)


    The rest remains the same:

    from flask import render_template
    from flask_cors import CORS
    import connexion


    # Create the application instance
    app = connexion.App(__name__, specification_dir="./")

    # read the swagger.yml file to configure the endpoints
    app.add_api("swagger.yml")
    CORS(app)

    # Create a URL route in our application for "/"
    @app.route("/")
    def home():
    """
    This function just responds to the browser URL
    localhost:5000/

    :return: the rendered template "home.html"
    """
    return render_template("home.html")


    if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=5100)


    But now, when I try to run it I get, this error:

    Traceback (most recent call last):
    File "server.py", line 15, in <module>
    CORS(app)
    File "/home/luis/.local/lib/python3.6/site-packages/flask_cors/extension.py", line 129, in __init__
    self.init_app(app, **kwargs)
    File "/home/luis/.local/lib/python3.6/site-packages/flask_cors/extension.py", line 154, in init_app
    app.after_request(cors_after_request)
    AttributeError: 'FlaskApp' object has no attribute 'after_request'

    Continue reading...

Compartilhe esta Página