1

在 Klein API for Non-blocking 方面需要帮助。这是一个简单的测试应用程序:

# -*- coding: utf-8 -*-
import datetime
import json
import time
from klein import Klein

app = Klein()

async def delay(seconds):
    """Set some delay for test"""
    time.sleep(seconds)
    return "Works"

@app.route('/', branch=True)
async def main(request):
    some_data = await delay(5)

    return json.dumps([{
        "status": "200",
        "time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "data": some_data
    }])

app.run("localhost", 8080)

然后只需将我的server.py后跟 2 个请求同时运行到http://127.0.0.1:8080/. 结果是:

[ { "status": "200", "time": "2019-10-18 20:57:16", "data": "Works" } ]
[ { "status": "200", "time": "2019-10-18 20:57:21", "data": "Works" } ]

每个响应之间有 5 秒的延迟。

问题:

如何让这段代码同时处理 2 个请求,现在它正在一个一个地工作......

也试过用twistd,结果都一样

PYTHONPATH=. twistd --pidfile=apserver.pid -n web --class=api.resource --port tcp:8000:interface=0.0.0.0

谢谢

4

1 回答 1

1

所以,问题是你的delay函数 - 它是一个阻塞函数,因为 python 的time.sleep- 是阻塞的。更多关于这你可以在这里阅读。

您应该使用task.deferLater可以认为是 Twisted 框架的非阻塞睡眠功能,类似于asyncio.sleep()

# app.py
import datetime
import json

import treq
from klein import Klein
from twisted.internet import task, reactor

app = Klein()

async def delay1(secs):
    await task.deferLater(reactor, secs)
    return "Works"

def delay2(secs):
    return task.deferLater(reactor, secs, lambda: "Works")

@app.route('/', branch=True)
async def main(request):
    some_data = await delay1(5)  # or some_data = await delay2(5) 

    return json.dumps([{
        "status": "200",
        "time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "data": some_data
    }])

def send_requests():
    for i in range(2):
        print("request", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        d = treq.get('http://localhost:8080')
        d.addCallback(treq.content)
        d.addCallback(lambda x: print("response", x.decode()))

# send 2 concurrent requests every 10 seconds to test the code
repeating = task.LoopingCall(send_requests)
repeating.start(10, now=False)

app.run("localhost", 8080)

运行代码

$ pip3 install treq klein
$ python3 app.py

等待 10 秒,输出应该是

2019-10-21 17:17:11-0400 [-] request 2019-10-21 17:17:11
2019-10-21 17:17:11-0400 [-] request 2019-10-21 17:17:11
2019-10-21 17:17:16-0400 [-] "127.0.0.1" - - [21/Oct/2019:21:17:16 +0000] "GET / HTTP/1.1" 200 67 "-" "-"
2019-10-21 17:17:16-0400 [-] "127.0.0.1" - - [21/Oct/2019:21:17:16 +0000] "GET / HTTP/1.1" 200 67 "-" "-"
2019-10-21 17:17:16-0400 [-] response [{"status": "200", "time": "2019-10-21 17:17:16", "data": "Works"}]
2019-10-21 17:17:16-0400 [-] response [{"status": "200", "time": "2019-10-21 17:17:16", "data": "Works"}]
于 2019-10-21T21:15:41.343 回答