我使用Boto访问Amazon S3。而对于文件上传,我可以分配一个回调函数。问题是,我无法从该回调函数访问所需的变量,直到我使它们成为全局变量。另一方面,如果我使它们成为全局的,它们对于所有其他Celery任务也是全局的(直到我重新启动Celery),因为文件上传是从Celery任务执行的。如何从回调函数访问(和编辑)变量?
这是一个函数,可以上传带有视频转换进度信息的JSON文件。
def upload_json():
global current_frame
global path_to_progress_file
global bucket
json_file = Key(bucket)
json_file.key = path_to_progress_file
json_file.set_contents_from_string('{"progress": "%s"}' % current_frame,
cb=json_upload_callback, num_cb=2, policy="public-read")
这里是用于上载的视频转换和与所述进度信息的JSON文件期间由ffmpeg的生成的帧2个回调函数。
# Callback functions that are called by get_contents_to_filename.
# The first argument is representing the number of bytes that have
# been successfully transmitted from S3 and the second is representing
# the total number of bytes that need to be transmitted.
def frame_upload_callback(transmitted, to_transmit):
if transmitted == to_transmit:
upload_json()
def json_upload_callback(transmitted, to_transmit):
global uploading_frame
if transmitted == to_transmit:
print "Frame uploading finished"
uploading_frame = False
从理论上讲,我可以通过uploading_frame变量的upload_json功能,但它不会得到,因为它是由宝途执行json_upload_callback。
事实上,我可以写这样的东西。
In [1]: def make_function(message):
...: def function():
...: print message
...: return function
...:
In [2]: hello_function = make_function("hello")
In [3]: hello_function
Out[3]: <function function at 0x19f4c08>
In [4]: hello_function()
hello
但是,哪个不允许您编辑函数中的值,只是让您读取值。
def myfunc():
stuff = 17
def lfun(arg):
print "got arg", arg, "and stuff is", stuff
return lfun
my_function = myfunc()
my_function("hello")
This Works。
def myfunc():
stuff = 17
def lfun(arg):
print "got arg", arg, "and stuff is", stuff
stuff += 1
return lfun
my_function = myfunc()
my_function("hello")
而且这给了一个UnboundLocalError:在分配之前引用的局部变量'stuff'。
谢谢。
您的例子并不表明uploading_frame是如何使用的,所以很难理解为什么你的事件需要它。创建一个更简单的例子,如果没有任何更清楚地显示问题的S3相关内容,也可能会有所帮助。 – dkagedal 2011-01-27 10:48:46