Question

Here is the sample code from flask-restful doc

from flask import Flask
from flask.ext import restful

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

class HelloWorld(restful.Resource):
    def get(self):
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/')

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

The HelloWorld class is in the same python file, say app.py, it works.

Now I am going to put the HelloWorld class to a separate class file, like following layout:

app
app/__init__.py # hold above code except the HelloWorld class.
app/resource
app/resource/__init__.py # empty
app/resource/HelloWorld.py # hold the above HelloWorld class.

The app/__init__.py contains :

from flask import Flask
from flask.ext import restful
from resource.HelloWorld import HelloWorld

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

api.add_resource(HelloWorld, '/')

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

And the HelloWorld.py is:

from flask.ext import restful
from app import app

class HelloWorld(restful.Resource):
    def get(self):
        return {'hello': 'world'}

Running the app would get exception:

ImportError: No module named app on HelloWorld.py

I do need to access app to read some information like app.config, how can i make it work?

Was it helpful?

Solution

You have a circular import; when the line from resource.HelloWorld import HelloWorld executes, app has not yet been assigned to, so in Helloworld.py the line from app import app fails.

Either import HelloWorld later:

from flask import Flask
from flask.ext import restful

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

from resource.HelloWorld import HelloWorld
api.add_resource(HelloWorld, '/')

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

or import just the app module in HelloWorld.py:

from flask.ext import restful
import app

class HelloWorld(restful.Resource):
    def get(self):
        return {'hello': 'world'}

and refer to app.app within a function or method called at a later time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top