- Hi I am using
Klein
Python module for my web server. - I need to run each request separately as a thread and also need to return the result.
- But Klein waits until the completion of single request to process another request.
- I also tried using
deferToThread
from twisted module. But it also process the requests only after completion of the first request. - Similarly I also tried
@inlineCallbacks
method it also produce the same result.
Note: This methods works perfectly when there is nothing to return. But I need to return the result.
Here I attached a sample code snippet below,
import time
import klein
import requests
from twisted.internet import threads
def test():
print "started"
x = requests.get("http://google.com")
time.sleep(10)
return x.text
app = klein.Klein()
@app.route('/square/submit',methods = ['GET'])
def square_submit(request):
return threads.deferToThread(test)
app.run('localhost', 8000)
This is not true. In fact, there's absolutely nothing wrong with the code you've provided. Simply running your example server at
tcp:localhost:8000
and using the followingcurl
commands, invalidates your claim:Am I correct in assuming you're testing the code in a web browser? If you are, then you're experiencing a "feature" of most modern browsers. The browser will make single request per URL at a given time. One way around this in the browser would be to add a bogus query string at the end of the URL, like so:
However, a very common mistake new Twisted/Klein developers tend to make is to write blocking code, thinking that Twisted will magically make it async. Example:
Code like this will handle requests sequentially and should be modified with async alternatives.