我正在做一些例子来了解它是如何异步地运行python的.我读了三重奏的文档,我还以为只有一个任务可在循环每次执行,并且在每一个checkpoint在scheduler决定哪些任务将被执行.
我做了一个测试它的例子,在三个例子中,我没有在我生成的子节点中使用任何检查点,nursery但是这个例子比同步版本快两倍.
异步示例:
import time
import trio
results = []
async def sum_numbers(first, last):
result = 0
for i in range(first, last):
result += i
results.append(result)
async def main():
start_time = time.time()
async with trio.open_nursery() as nursery:
nursery.start_soon(sum_numbers, 0, 50000000)
nursery.start_soon(sum_numbers, 50000000, 100000000)
print(sum(results))
print("Total time:", time.time() - start_time)
trio.run(main)
Run Code Online (Sandbox Code Playgroud)
结果:
4999999950000000
Total time: 4.150018930435181
Run Code Online (Sandbox Code Playgroud)
同步示例:
import time
start_time = time.time()
result = 0
for i in range(0, 100000000):
result += i
print(result)
print("Total …Run Code Online (Sandbox Code Playgroud) 所以我有这个任务:您在位于 postgres://candidate.company.org/company 的 PostgreSQL 服务器上有两个可用的摘要报告
用户名 = 候选人密码 = abc
所以我使用此代码尝试连接到数据库:
import psycopg2 as db
conn = db.connect(host='postgres://candidate.suade.org/company', database='randomname', user='candidate', password='abc', port='5432')
Run Code Online (Sandbox Code Playgroud)
但后来我收到错误消息:
ProgrammingError: invalid dsn: invalid connection option "username"
Run Code Online (Sandbox Code Playgroud)
由于给出的用户名是正确的,有人可以帮忙吗?
我正在尝试使用async从URL列表(由ID标识)中获取HTML。我需要使用代理。
我正在尝试将aiohttp与以下代理一起使用:
import asyncio
import aiohttp
from bs4 import BeautifulSoup
ids = ['1', '2', '3']
async def fetch(session, id):
print('Starting {}'.format(id))
url = f'https://www.testing.com/{id}'
async with session.get(url) as response:
return BeautifulSoup(await response.content, 'html.parser')
async def main(id):
proxydict = {"http": 'xx.xx.x.xx:xxxx', "https": 'xx.xx.xxx.xx:xxxx'}
async with aiohttp.ClientSession(proxy=proxydict) as session:
soup = await fetch(session, id)
if 'No record found' in soup.title.text:
print(id, 'na')
loop = asyncio.get_event_loop()
future = [asyncio.ensure_future(main(id)) for id in ids]
loop.run_until_complete(asyncio.wait(future))
Run Code Online (Sandbox Code Playgroud)
根据这里的问题:https : //github.com/aio-libs/aiohttp/pull/2582,似乎ClientSession(proxy=proxydict)应该工作。
但是,我收到一个错误 "__init__() …
python ×3
aiohttp ×1
asynchronous ×1
database ×1
mysql ×1
postgresql ×1
psycopg2 ×1
python-3.x ×1
python-trio ×1