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?
You have a circular import; when the line
from resource.HelloWorld import HelloWorld
executes,app
has not yet been assigned to, so inHelloworld.py
the linefrom app import app
fails.Either import
HelloWorld
later:or import just the
app
module inHelloWorld.py
:and refer to
app.app
within a function or method called at a later time.