1

我正在使用 Amazon 的 SES 从我的 Python Google App Engine 应用程序发送电子邮件。我想保存 SES 连接,而不是为我发送的每封电子邮件创建它。

对于多线程应用程序,这是一种合理的方法吗?:

SES = None

def send_email_AWS(sender, to_addresses, subject, body):
    global SES
    if not SES:
        SES = SESConnection(aws_key, aws_secret)
    [other code for sending the email]

我对什么是线程安全和什么不是线程安全没有很好的理解。

4

2 回答 2

3

这是一个可以帮助您的示例:http: //blog.notdot.net/2011/10/Migrating-to-Python-2-7-part-1-Threadsafe

class SesConnection(object):

    _SES = None
    _aws_key = ....
    _aws_secret = ....

    _ses_lock = threading.Lock()

    @classmethod
    def get_ses(cls):

        with cls._ses_lock:

            if not cls._SES:
                cls._SES = SESConnection(cls._aws_key, cls._aws_secret)  # or put the code here
            return cls._SES

或使用 webapp2 应用注册表:http ://webapp-improved.appspot.com/guide/app.html#registry

于 2012-12-15T20:50:13.850 回答
1

从您的示例中,如果您只是其视为常数, 则不会有任何问题。您的公共变量 SES 不是线程安全的。这意味着,例如,如果有许多用户写入该全局,那么您将始终读取发生的最后一次写入,而不是每个实例。

线程是人的图像。无法想象您的全局变量是公共 WC。线程安全有一个门(锁)。如果我们没有锁,否则每个人都会在另一个人在里面时尝试做他的工作。

对于您的示例,我看到:

SES = NONE 

这意味着您的应用程序的每个实例都将重置 SES 全局变量。不是什么好事。

global SES
    if not SES:

Then the first request will set it again to something. But its not safe because at the same time some other request might override it. If that is not a problem then its ok. What you need is to create it locally per request handler if that is the intention to be thread safe.

Answer by @voscausa shows you a good implementation example. Check it out

于 2012-12-23T19:12:52.350 回答