[英]Python3 Flask - missing 1 required positional argument: 'self'
I have very simple python code to access Amazon Simple Queue Service. 我有非常简单的python代码来访问Amazon Simple Queue Service。 But I get
但是我明白了
builtins.TypeError
TypeError: get_queue() missing 1 required positional argument: 'self'
My code: 我的代码:
class CloudQueue(object):
conn = boto.sqs.connect_to_region("eu-west-1",
aws_access_key_id="abc",
aws_secret_access_key="abc")
@app.route('/get/<name>')
def get_queue(self, name):
if(name != None):
queue = self.conn.get_queue(str(name)) <--------- HERE
return conn.get_all_queues()
if __name__ == "__main__":
cq = CloudQueue()
app.debug = True
app.run()
You cannot register methods as routes; 您不能将方法注册为路由; at the time the decorator runs the class is still being defined and all you registered is the unbound function object.
在装饰器运行时,仍在定义该类,并且您注册的所有内容都是未绑定的函数对象。 Since it is not bound to an instance there is no
self
to pass in. 由于它没有绑定到实例,因此没有
self
可以传递。
Do not use a class here; 不要在这里使用课程; create the connection anew for each request:
为每个请求重新创建连接:
@app.route('/get/<name>')
def get_queue(name):
conn = boto.sqs.connect_to_region("eu-west-1",
aws_access_key_id="abc",
aws_secret_access_key="abc")
queue = conn.get_queue(name)
return 'some response string'
You could set it as a global but then you need to make sure you re-create the connection on the first request (so it continues to work even when using a WSGI server using child processes to handle requests): 您可以将其设置为全局,但随后需要确保在第一个请求上重新创建连接(因此即使使用子进程来处理请求的WSGI服务器,该连接仍可以继续工作):
@app.before_first_request()
def connect_to_boto():
global conn
conn = boto.sqs.connect_to_region("eu-west-1",
aws_access_key_id="abc",
aws_secret_access_key="abc")
@app.route('/get/<name>')
def get_queue(name):
queue = conn.get_queue(name)
return 'some response string'
Use this only if you are sure that boto
connection objects are thread-safe. 仅在确定
boto
连接对象是线程安全的时才使用此选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.