[英]python flask-restful cannot get app access in resource class
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. HelloWorld
类位于同一python文件中,例如app.py
,它可以工作。
Now I am going to put the HelloWorld
class to a separate class file, like following layout: 现在,我将把HelloWorld
类放到一个单独的类文件中,如下所示:
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 : app/__init__.py
包含:
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: 而HelloWorld.py
是:
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? 我确实需要访问app才能读取一些信息,例如app.config
,我该如何使其工作?
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. 当from resource.HelloWorld import HelloWorld
的行执行时,尚未分配app
,因此在Helloworld.py
中from app import app
的行失败。
Either import HelloWorld
later: 稍后再导入HelloWorld
:
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
: 或仅将app
模块导入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. 并在稍后调用的函数或方法中引用app.app
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.