我使用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")
这里有2个回调函数,用于上传视频转换过程中ffmpeg生成的帧和带有进度信息的JSON文件.
# 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
从理论上讲,我可以将uploaded_frame变量传递给upload_json函数,但它不会到达由Boto执行的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]:
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")
这有效.
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'.
谢谢.