V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
sonack
V2EX  ›  问与答

python 服务器端怎么实现当有某个 get 请求时才返回之前的某个请求的结果呢?

  •  
  •   sonack · 2017-01-03 17:44:16 +08:00 · 1937 次点击
    这是一个创建于 2641 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如客户端有 A 和 B ,服务端是 S A 向 S 请求某个数据,但 S 还没有该数据,于是一直等待或挂起当前进程,直到 B 用 post 方法向 S 传送了某些数据 data 以后, S 处理 A 的进程或线程才返回呢?

    我用的 Flask 好像做不到啊,有什么简单的 demo 可以参考吗?

    谢谢

    8 条回复    2017-01-04 10:25:31 +08:00
    wwqgtxx
        1
    wwqgtxx  
       2017-01-03 18:25:12 +08:00 via iPhone
    用个 queue 不就行了,不过这样很容易造成 http 超时以及程序死锁,请谨慎使用
    Kilerd
        2
    Kilerd  
       2017-01-03 18:25:29 +08:00
    1 、 可以考虑下 socket 或者 websocket 这些的双向传输的方法

    2 、 队列处理问题。

    A 向 S 发送一个事件, S 登记事件之后,返回一个 事件 ID 。 之后 A 定时向 S 查询 事件是否完毕。 S 收到查询信息,完毕了就返回事件处理结果。
    sonack
        3
    sonack  
    OP
       2017-01-03 19:19:40 +08:00
    我现在这样实现的。。。
    用 python 的 aiohttp

    import asyncio

    from aiohttp import web

    test = False

    async def index(request):
    global test
    print('index test=',test)
    test = True
    print('index changed=',test)
    return web.Response(body=b'<h1>Index</h1>',content_type='text/html')

    async def hello(request):
    print("start");
    while True:
    await asyncio.sleep(0.5)
    print('test = ' , test)
    if test:
    break
    print("end");
    text = '<h1>Hello, %s!</h1>' % request.match_info['name']
    return web.Response(body=text.encode('utf-8'),content_type='text/html')

    async def init(loop):
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', index)
    app.router.add_route('GET', '/hello/{name}', hello)
    srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8000)
    print('Server started at http://127.0.0.1:8000...')
    return srv

    loop = asyncio.get_event_loop()
    loop.run_until_complete(init(loop))
    loop.run_forever()


    访问 hello 不会立即返回。除非另外一个访问了 index 。。。。

    不知道这样做有没有什么问题
    zmj1316
        4
    zmj1316  
       2017-01-03 21:03:17 +08:00
    为什么不让 a 定时轮询呢?一直挂起阻塞着不好吧 ,又不是 websocket
    tonghuashuai
        5
    tonghuashuai  
       2017-01-04 00:19:36 +08:00
    这不就是 websocket 的应用场景吗?
    sonack
        6
    sonack  
    OP
       2017-01-04 00:45:42 +08:00 via Android
    请问有什么推荐的书来学习 websocket 吗
    binux
        7
    binux  
       2017-01-04 01:29:43 +08:00
    概念上没有问题,细节上还能够提升。
    appleorchard2000
        8
    appleorchard2000  
       2017-01-04 10:25:31 +08:00
    不必让 hello 一直死等吧,在 index 仍未被访问的情况下,可以让 hello 返回空的结果; index 访问的结果,都暂存在一个数据容器里,临时列表之类的,等街 hello 来取。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1488 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 23:52 · PVG 07:52 · LAX 16:52 · JFK 19:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.