Python Klein-非阻塞API [英] Python Klein - Non Blocking API

查看:63
本文介绍了Python Klein-非阻塞API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要有关Klein API for Non-blocking的帮助.这是一个简单的测试应用程序:

Need help with Klein API for Non-blocking. This is a simple test app:

# -*- 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 ,然后同时向 http://127.0.0.1:8080/发送2个请求.结果是:

Then simply run my server.py followed by 2 request at the same time to the http://127.0.0.1:8080/. The results are:

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

每个响应之间的间隔时间为

5秒.

5 seconds delay between each response.

问题:

如何使此代码同时处理2个请求,现在它正在一个接一个地工作...

How make this code working with 2 requests at the same time, now it's working one by one...

也尝试使用扭曲的,结果相同

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

谢谢

推荐答案

所以,问题出在您的 delay 函数-它是一个阻塞函数,因为python的 time.sleep -正在阻止.关于此的更多信息,您可以在此处阅读.

So, the problem is your delay function - its a blocking function, because python's time.sleep - is blocking. More on this you can read here.

您应该使用 task.deferLater ,您可以将其视为Twisted框架的非阻塞睡眠功能,类似于

You should use task.deferLater which you can think of as the non-blocking sleep function of Twisted framework, similar to 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秒钟,输出应为

wait 10 seconds and the output should be

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"}]

这篇关于Python Klein-非阻塞API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆