【发布时间】:2017-12-20 15:23:27
【问题描述】:
我正在尝试使用新线程从项目中启动烧瓶应用程序。因此,我想从路由的函数中访问这个类对象的所有属性。
我的最小示例如下:
from flask import Flask
from threading import Thread
class WebApp():
def __init__(self, ip, port):
self.ip = ip
self.port = port
self.app = Flask(__name__)
self.some_attribute = 'test'
def some_function(self):
print('hello there')
def run(self):
@self.app.route('/test/', Methods=['POST'])
def test(self):
#do something with the data recieved in the post request
print request.json()
#run some method
self.some_function()
return self.some_attribute
t = Thread(target=self.app.run, args=(self.ip,self.port,False))
t.start()
if __name__ == '__main__':
webapp = WebApp('localhost', 8000)
webapp.run()
这个例子的问题是,“self”在函数测试中是未知的。
我已经考虑过使用 Flasks flask.views.MethodView 或 flask.view.View,但似乎我必须为每条路线定义一个全新的类。
有没有可能我可以那样做?
更新:通过从 test() 的签名中删除“self”,可以访问“self”。不过,从 POST 请求访问数据仍然是个问题。
【问题讨论】: