<p>在Python3.7中,您将能够编写:</p>
<pre><code>from contextlib import asynccontextmanager
@asynccontextmanager
async def smtp_connection():
client = SMTPAsync()
...
try:
await client.connect(smtp_url, smtp_port)
await client.starttls()
await client.login(smtp_username, smtp_password)
yield client
finally:
await client.quit()
</code></pre>
<p>在3.7版本出来之前,您可以使用<a href="https://pypi.python.org/pypi/async_generator" rel="noreferrer">^{<cd1>}</a>包来实现这一点。在3.6中,您可以编写:</p>
<pre><code># This import changed, everything else is the same
from async_generator import asynccontextmanager
@asynccontextmanager
async def smtp_connection():
client = SMTPAsync()
...
try:
await client.connect(smtp_url, smtp_port)
await client.starttls()
await client.login(smtp_username, smtp_password)
yield client
finally:
await client.quit()
</code></pre>
<p>如果你想一直工作到3.5,你可以写:</p>
<pre><code># This import changed again:
from async_generator import asynccontextmanager, async_generator, yield_
@asynccontextmanager
@async_generator # <-- added this
async def smtp_connection():
client = SMTPAsync()
...
try:
await client.connect(smtp_url, smtp_port)
await client.starttls()
await client.login(smtp_username, smtp_password)
await yield_(client) # <-- this line changed
finally:
await client.quit()
</code></pre>