python-3.x - 使用 aiohttp 阻止请求

标签 python-3.x server aiohttp

当我运行 http://0.0.0.0:8080/run1 时,请检查以下脚本(python3 -m main)并行在两个不同的选项卡中。 request2 仅在 request1 结束后才开始。每个新请求都会被前一个请求阻止。 如有任何帮助,我们将不胜感激。

from aiohttp import web
import random
import time
from datetime import datetime


async def f1(request):
    res_text = "Starting count for name" + str(random.randint(1, 1000))
    res_text += "\n"
    res_text += str(datetime.now())
    res_text += "\n"
    for i in range(10):
        res_text += f"Value {i}"
        res_text += "\n"
        time.sleep(1)
    res_text += str(datetime.now())
    return web.Response(text=res_text)

app = web.Application()
app.router.add_get('/run1', f1)

if __name__ == '__main__':
    web.run_app(app)

根据建议更新了请求:

from aiohttp import web
import random
import time
from datetime import datetime
import asyncio

async def f1(request):
    res_text = "Starting count for name" + str(random.randint(1, 1000))
    res_text += "\n"
    res_text += str(datetime.now())
    res_text += "\n"
    for i in range(10):
        res_text += f"Value {i}"
        res_text += "\n"
        await asyncio.sleep(1)
    res_text += str(datetime.now())
    return web.Response(text=res_text)

app = web.Application()
app.router.add_get('/run1', f1)

async def start_app():
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner)
    await site.start()
    return runner, site

loop = asyncio.get_event_loop()
runner, site = loop.run_until_complete(start_app())
try:
    loop.run_forever()
except KeyboardInterrupt as err:
    loop.run_until_complete(runner.cleanup())

loop.close()

最佳答案

这出人意料地难以确定,但事实证明 run_app 正在阻塞。 documentation对此有点模糊,但在另一个页面上它明确地将其称为阻塞 process 。该文档有很多关于在生产中为应用程序提供更好服务的不同方法。

编辑:评论的第二点:从不同选项卡发送请求将不会被识别为不同的来源,因此这不会按预期方式工作。但是,如果您使用隐身选项卡,它就会起作用。如果您使用 run_app (1 个正常选项卡,1 个隐身模式)对原始示例执行此操作,您将看到它仍然处于阻塞状态。如果您将第二个示例的 AppRunner 与两个选项卡(1 个正常选项卡,1 个隐身选项卡)一起使用,您将看到它不再阻塞。如果您在同一浏览器 session 中使用带有两个选项卡的 AppRunner,那么它将被阻止。

关于python-3.x - 使用 aiohttp 阻止请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61717238/

相关文章:

python - 压平深度嵌套的 JSON 以获取 Dataframe 的最快且通用的方法是什么?

python-3.x - NLTK - 类型错误 : tagged_words() got an unexpected keyword argument 'simplify_tags'

javascript - 从前端编辑用户信息

python - 将 Autobahn|Python 与 aiohttp 集成

python - 无法从网页的不同深度抓取相似的链接

python - 在Python中使用for循环创建一个倒置的星号三角形

r - Plumber R,将 'localhost' 更改为本地计算机 IP 作为测试

java - Udp 服务器太慢?

python - 带有 ssl 客户端证书的 aiohttp

python - 安装基于 pyproject.toml 的项目所需的错误 : Could not build wheels for aiohttp,