我想在异步函数中使用 boto3,python

hhk*_*hhk 8 python amazon-s3 amazon-web-services python-asyncio boto3

我正在 playwright 中开发网络爬虫,并希望将图像异步上传到 aws-s3。

但 boto3 不是异步函数..如何修复它?


class Boto3:
   def __init__(self, key, id):
       self.S3 = boto3.client('s3', aws_access_key_id=aws_key_id, aws_secret_access_key=aws_secret)

   def upload_stream(self, stream, bucket_name, key):
       self.S3.put_object(Body=stream, Bucket=bucket_name, Key=key)

...
...

class Scraper:
   def __init__(self, key, id):
      self.S3 = boto3.client('s3', aws_access_key_id=id, aws_secret_access_key=key)

   asnyc _save_image(res):
      buffer = await res.body()
      # S3.put_object is not an async function.
      self.S3.put_object(
            Body=buffer, 
            Bucket=bucket_name, 
            Key=bucket_key,
      )

   async def scrape():
      playwright = await async_playwright().start()
      browser = await playwright.chromium.launch( headless = True, devtools = False )
      page = browser.new_page()

      page.on('response', _save_image)
      await page.goto('https://www.example.com')

scraper = Scraper(key, id)
asyncio.run(scraper.scrape())

Run Code Online (Sandbox Code Playgroud)

self.S3.put_object :此函数不是 asnyc,因此想在异步版本中更改它。如何修复它?

提前致谢。

Mar*_*cin 12

如何修复它?

你不能,因为boto3它不是异步的。您最多可以尝试使用第三方非 AWS 库,例如aioboto3来代替boto3.