VPfB
VPfB

Reputation: 17332

Do I need a new ssl.create_default_context() every time?

This is my code using a SSL context:

with smtplib.SMTP(host, port) as smtpserver:
    smtpserver.ehlo()
    smtpserver.starttls(context=ssl.create_default_context())
    ... etc ...

Is the default context object a constant that can be shared and reused in a multi-threaded program? I mean creating it just once:

SSL_CONTEXT = ssl.create_default_context()

and then:

with smtplib.SMTP(host, port) as smtpserver:
    smtpserver.ehlo()
    smtpserver.starttls(context=SSL_CONTEXT)

for every message sent.

Upvotes: 3

Views: 11803

Answers (2)

user10414823
user10414823

Reputation: 19

Each connection should have its own context. You can see in the Python source code for http.client, that HTTPSConnection creates the new context for every connection.

https://github.com/python/cpython/blob/master/Lib/http/client.py

Upvotes: 1

l'L'l
l'L'l

Reputation: 47264

Indeed ssl.create_default_context() can be used again (as it's purpose) after initializing it:

import ssl, smtplib
>>> smtp = smtplib.SMTP("mail.python.org", port=587)
>>> context = ssl.create_default_context()
>>> smtp.starttls(context=context)

(220, b'2.0.0 Ready to start TLS')

https://docs.python.org/3/library/ssl.html#best-defaults

Upvotes: 1

Related Questions