标签: python-asyncio

如何aiohttp请求post文件列表python请求模块?

我想使用 aiohttp 进行多帖子。而且,我需要用文件发布。但是,我的代码不起作用这是我的代码

import aiohttp

file = open('file/path', 'rb')
async with aiohttp.request('post', url, files=file) as response:
   return await response.text()
Run Code Online (Sandbox Code Playgroud)

和request.FILES is None

这是引用通告

    def post(self, url: StrOrURL,
             *, data: Any=None, **kwargs: Any) -> '_RequestContextManager':
        """Perform HTTP POST request."""
        return _RequestContextManager(
            self._request(hdrs.METH_POST, url,
                          data=data,
>                         **kwargs))
E       TypeError: _request() got an unexpected keyword argument 'files'

Run Code Online (Sandbox Code Playgroud)

拜托....这可能...?我需要解决方案...请...T^T

这是所需的输出

request.FILES['key'] == file

关键是html形式

    def post(self, url: StrOrURL,
             *, data: Any=None, **kwargs: Any) -> '_RequestContextManager':
        """Perform HTTP POST request."""
        return _RequestContextManager(
            self._request(hdrs.METH_POST, url, …
Run Code Online (Sandbox Code Playgroud)

python python-asyncio aiohttp

4
推荐指数
1
解决办法
2万
查看次数

使用Python的线程与async/await有什么区别

Im trying to get more familiar in the usage of asyncio in python3, but I dont see when i should use async/await or threading. Is there a difference or is one just easier to use than the other.

So for example between these two functions, is one better than the other?

Just generic code

def func1()
def func2()

threads = [threading.Thread(target=func1), threading.Thread(target=func2)]
for thread in threads:
    thread.start()

for thread in threads:
    thread.join()
Run Code Online (Sandbox Code Playgroud)

versus

async def func1()
async def func2()

await …
Run Code Online (Sandbox Code Playgroud)

python multithreading python-3.x async-await python-asyncio

4
推荐指数
1
解决办法
1794
查看次数

可取消的异步键盘输入

我正在尝试编写一个并发的Python程序,asyncio它也接受键盘输入。当我尝试关闭程序时出现问题。由于键盘输入最终是通过 完成的sys.stdin.readline,因此该函数仅在我按下 后返回ENTER,无论我是stop()事件循环还是cancel()函数的Future。

有什么办法可以提供asyncio可以取消的键盘输入吗?

这是我的 MWE。它将接受键盘输入 1 秒,然后stop():

import asyncio
import sys

async def console_input_loop():
    while True:
        inp = await loop.run_in_executor(None, sys.stdin.readline)
        print(f"[{inp.strip()}]")

async def sleeper():
    await asyncio.sleep(1)
    print("stop")
    loop.stop()

loop = asyncio.get_event_loop()
loop.create_task(console_input_loop())
loop.create_task(sleeper())
loop.run_forever()
Run Code Online (Sandbox Code Playgroud)

python python-asyncio

4
推荐指数
1
解决办法
1940
查看次数

有没有办法让 asyncio.create_task 返回异步函数之外的值?

我需要从异步函数外部的 asyncio.create_task(function()) 返回一个值。


import asyncio

async def hello():
    return("hello")

response = asyncio.get_event_loop().create_task(hello())
print(response)
Run Code Online (Sandbox Code Playgroud)

这是输出的内容:

<Task pending coro=<hello() running at C:\Users\\PycharmProjects\PCWebsite\fjdfjd.py:3>>
Run Code Online (Sandbox Code Playgroud)

当我想收到:

"Hello"
Run Code Online (Sandbox Code Playgroud)

请注意,我不能使用 .run()

RuntimeError: asyncio.run() cannot be called from a running event loop
Run Code Online (Sandbox Code Playgroud)

或者当我收到错误时 run_until_complete

RuntimeError: This event loop is already running
Run Code Online (Sandbox Code Playgroud)

python python-asyncio

4
推荐指数
1
解决办法
3153
查看次数

AWS lambda 与 python asyncio。事件循环闭合问题?

关闭 aws lambda 中的事件循环会影响未来的 lambda 运行吗?

  • 我有一些 aysncio python 代码在 aws lambda 服务中运行。代码逻辑如下

    def lambda_handler(event,context):
        loop = asyncio.get_event_loop()
        # perform all operations with the loop
        loop.close()
        return results
    
    Run Code Online (Sandbox Code Playgroud)
  • 如果我运行一次,它看起来工作正常。但是,如果我之后立即重新运行它,我会收到一条错误消息,指出事件循环已关闭

  • 为什么会发生这种情况?每个 lambda 运行不应该独立于最后一个吗?毕竟 lambda 应该是无状态的

python amazon-web-services python-asyncio aws-lambda

4
推荐指数
3
解决办法
4426
查看次数

异步请求的奇怪错误

async def rss_downloader(rss):\n    global counter\n    async with download_limit:\n        headers = {\n            \'User-Agent\': \'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36\'\n        }\n        try:\n            response = await httpx.get(rss, headers=headers, verify=False)\n            if response.status_code == 200:\n                r_text = response.text\n                await downloaded_rss.put({\'url\': rss, \'feed\': r_text})\n            else:\n                counter += 1\n                print(f\'\xe2\x84\x96{counter} - {response.status_code} - {rss}\')\n        except (\n            ConnectTimeout, ConnectionClosed\n        ):\n            not_found_rss.append(rss)\n        except Exception:\n            not_found_rss.append(rss)\n            logging.exception(f\'{rss}\')\n\n\nasync def main():\n    parser_task = asyncio.create_task(parser_queue())\n    tasks = [\n        asyncio.create_task(rss_downloader(item[\'url\'])) for item in db[config[\'mongodb\'][\'channels_collection\']].find({\'url\': {\'$ne\': \'No RSS\'}})\n    ]\n …
Run Code Online (Sandbox Code Playgroud)

python-3.x python-asyncio

4
推荐指数
1
解决办法
8665
查看次数

为什么 aiohttp 响应的 json() 方法需要等待?

我不明白为什么resp.json()需要等待。据我了解,async/await 在处理 I/O 时很有用。但是,当我在下面的示例中调用 resp.json() 时,Web 请求是否尚未使用上面行中的 session.get() 进行处理?

async with session.get('https://api.github.com/events') as resp:
    print(await resp.json())
Run Code Online (Sandbox Code Playgroud)

python-3.x python-asyncio aiohttp

4
推荐指数
1
解决办法
3176
查看次数

为什么我会得到“异步函数之外的异步理解”?

我正在使用 Python 3.7.4 和这段代码(MWE):

import asyncio


async def foo(x):
    await asyncio.sleep(1)
    return [i for i in range(10)]


async def big_foo():
    dict_of_lists = {'A': [i for i in range(10)], 'B': [i for i in range(10)]}
    return {
        key: [
            item
            for list_item in dict_of_lists[key]
            for item in await foo(list_item)
        ]
        for key in ['A', 'B']
    }
Run Code Online (Sandbox Code Playgroud)

抛出错误:

File "filename.py", line 13
    item
    ^
SyntaxError: asynchronous comprehension outside of an asynchronous function
Run Code Online (Sandbox Code Playgroud)

该错误消息没有多大帮助,因为它确实位于异步函数内。

for我通过定义显式循环而不是理解来解决这个问题,如下所示:

File "filename.py", line 13
    item
    ^
SyntaxError: …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension python-3.x python-asyncio

4
推荐指数
1
解决办法
2520
查看次数

如何在 python 3.8 的异步编程中使用“yield”语句?

在python的asyncio异步编程(3.7或以下版本)中,如果我想手动让协程将其控制权交还给主事件循环,我可以使用以下代码:

@asyncio.coroutine
def switch():
    yield
    return

async def task():
    # ...do something
    # ...
    await switch() # then this coroutine will be suspended and other will be triggered
    # ...
    # ... do something else when it's triggered again.
Run Code Online (Sandbox Code Playgroud)

然而,在 python3.8 中,“@coroutine”装饰器已被弃用。除此之外,我无法在“async def”中使用yield(因为它将定义异步生成器而不是协程)。那么我怎样才能实现同样的功能呢?

python python-asyncio

4
推荐指数
1
解决办法
2026
查看次数

python asyncio 无法同时运行两个无限函数

我一直在尝试同时运行两个功能,但一个功能似乎永远无法工作,除非我停止另一个功能。第一个函数每 30 秒发送一封电子邮件,而第二个函数每 5 秒打印一条简单的语句。组合起来,每 6 个“Hello Worlds”输出应发送一封电子邮件。

然而,我从来没有收到过电子邮件,除非将打印更改为提前停止,例如 10 秒后结束。我该怎么做才能让两者同时运行而不停止?

async def timer():
    end = time.time() + 30
    while True:
        if time.time() >= end:
            sendmail(name, filepath + "\\" + name, receiver)
            end = time.time() + 30

async def runs():
    while True:
        print("Hello World")
        time.sleep(5)


loop = asyncio.get_event_loop()
loop.create_task(runs())
loop.create_task(timer())
loop.run_forever()
Run Code Online (Sandbox Code Playgroud)

asynchronous python-3.x python-asyncio

4
推荐指数
1
解决办法
1613
查看次数