Python中的全局“连接”变量

时间:2013-01-07 17:23:29

标签: python python-2.7 cloudfiles

完整脚本:https://gist.github.com/4476526

有问题的具体代码是

# Cloud Files username & API key
username = ''
key = ''

# Source and destination container names
originContainerName = ''
targetContainerName = ''

...

def cloudConnect():
    global originContainer
    global targetContainer
    global connection
    print "Creating connection"
    connection = cloudfiles.get_connection(username,key,servicenet=True)
    print "-- [DONE]"
    print "Accessing containers"
    originContainer = connection.create_container(originContainerName)
    targetContainer = connection.create_container(targetContainerName)
    print "-- [DONE]"
    return

脚本工作得非常好,但是我已经在多个地方读过全局变量应该犹豫不决的使用,并且几乎总有一种更好的方法可以在没有它们的情况下做同样的事情。这是真的?如果是这样,我应该如何修复此脚本?对我来说,使用全局连接和容器变量似乎要容易得多,而不是将这些对象作为参数传递给多个函数。

2 个答案:

答案 0 :(得分:5)

您应该创建一个类(称为CloudContainer),将所有这些全局变量包含为成员,并将其重写为(仅作为开头):

class CloudContainers(object):
    def __init__(self, username, key, originContainerName, targetContainerName):
        self.username = username
        self.key = key     
        self.originContainerName = originContainerName
        self.targetContainerName = targetContainerName

    def cloudConnect(self):
        print "Creating connection"
        self.connection = cloudfiles.get_connection(self.username,self.key,servicenet=True)
        print "-- [DONE]"
        print "Accessing containers"
        self.originContainer = connection.create_container(self.originContainerName)
        self.targetContainer = connection.create_container(self.targetContainerName)
        print "-- [DONE]"
        return

    def uploadImg(self, new_name):
        new_obj = self.targetContainer.create_object(new_name)
        new_obj.content_type = 'image/jpeg'
        new_obj.load_from_filename("up/"+new_name)

    def getImg(name):
        obj = self.originContainer.get_object(name)
        obj.save_to_filename("down/"+name)

因此,任何使用这些全局变量的函数(如上面的getImguploadImg)都将作为该类的方法包含在内。

答案 1 :(得分:1)

更简单,是的,但这意味着很难判断这些变量何时以及为何会发生变化。我认为最好的答案就是你在问题中给出的答案 - 将它们作为一个对象传递给你。 E.g:

def cloud_connect(origin_container_name, target_container_name):
    print "Creating connection"
    connection = cloudfiles.get_connection(username, key, servicenet=True)
    print "-- [DONE]"
    print "Accessing containers"
    origin_container = connection.create_container(origin_container_name)
    target_container = connection.create_container(target_container_name)
    print "-- [DONE]"
    return connection, origin_container, target_container

然后简单地传递那个元组。