简体   繁体   中英

Error with flask server after installing CORS: AttributeError: 'FlaskApp' object has no attribute 'after_request'

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'

It works below. I think it's solved...

https://github.com/zalando/connexion/issues/438

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.app) # this

# 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)

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