简体   繁体   中英

Unable to add resources using a Flask Application Factory and Flask-Restful

I'm writing in a bit of desperation. I have an application that uses Flask, Flask Restful, JWT, Flask SQLAlchemy.

It's a personal project which is quite large and is suffering from lack of unit testing - so I've been adding unit testing using pytest and tox.

I realized that to do this properly, I needed to move from the

from flask import Flask
app = Flask(__name__)

to using an application factory so I can setup different environments easily. I am completely stuck and feeling more than a little stupid. To get help and show the issue, I have stripped things down to this:

The 'old' way:

resources/talk.py:

from flask_restful import Resource

class Talk(Resource):
    def get(self):
        return { 'msg' : 'Talking' }

app.py:

from flask import Flask
from flask_restful import Api
from resources.talk import Talk

app = Flask(__name__)
api = Api(app)

api.add_resource(Talk, '/talk')

if __name__ == "__main__":
    app.run(debug=True)

If I run this and go to http://localhost:5000/talk I get the { 'msg': 'Talking' } response.

However, I cannot get it to work using an application factory.

I have looked at the docs from Flask, which are here: https://flask.palletsprojects.com/en/1.1.x/patterns/appfactories/#

And it makes sense. However, I can't get the url to work.

app_factory.py:

from flask import Flask
from flask_restful import Api

api = Api()

def create_app():
    app = Flask(__name__)    
    api.init_app(app)
    
    from resources.talk import Talk

    api.add_resource(Talk, '/talk')

    return app

run.py:

from app_factory import create_app
app = create_app()

127.0.0.1 - - [09/Jan/2021 22:07:09] "GET /talk HTTP/1.1" 404

I also tried using


def create_app():
    app = Flask(__name__)    
    api.init_app(app)
    
    from resources.talk import Talk
    with app.app_context():
        api.add_resource(Talk, '/talk')

    return app

but realized I'm just guessing and not understanding.

Does anyone have any pointers on how to set this up correctly? If I can' get this working then the JWT, database and other things stand no chance!

Thank you in advance.

I ran into the same problem. You have to bind the resources before initializing, like so:

from resources.talk import Talk
api.add_resource(Talk, '/talk')
api.init_app(app)

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