Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WSGI+ #1

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions examples/wsgi_plus.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import time
from concurrent.futures import Future
from threading import Thread


def application(environ, start_response):
def thread():
time.sleep(3)
fut.set_result(3)

Thread(target=thread).start()
fut = Future()
yield fut
body = b'Dzozdra!\n'
status = '200 OK'
headers = [('Content-type', 'text/plain')]
start_response(status, headers)
yield body
34 changes: 28 additions & 6 deletions gunicorn/workers/gthread.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import sys
import time
from collections import deque
from concurrent.futures import Future
from datetime import datetime
from functools import partial
from threading import RLock
Expand Down Expand Up @@ -113,9 +114,26 @@ def _wrap_future(self, fs, conn):

def enqueue_req(self, conn):
conn.init()
# submit the connection to a worker
fs = self.tpool.submit(self.handle, conn)
self._wrap_future(fs, conn)

def iterate():
gen = self.handle(conn)
while True:
try:
val = next(gen)
except StopIteration as e:
yield e.value
if isinstance(val, Future):
val.add_done_callback(resume)
yield (), ()

iterator = iterate()

def resume(fs=None):
if fs is None or not fs.exception():
fs = self.tpool.submit(next, iterator)
self._wrap_future(fs, conn)

resume()

def accept(self, server, listener):
try:
Expand Down Expand Up @@ -244,9 +262,11 @@ def finish_request(self, fs):
self.nr_conns -= 1
fs.conn.close()
return

try:
(keepalive, conn) = fs.result()
if keepalive == conn == ():
# the app was suspended
return
# if the connection should be kept alived add it
# to the eventloop and record it
if keepalive and self.alive:
Expand Down Expand Up @@ -279,7 +299,7 @@ def handle(self, conn):
return (False, conn)

# handle the request
keepalive = self.handle_request(req, conn)
keepalive = yield from self.handle_request(req, conn)
if keepalive:
return (keepalive, conn)
except http.errors.NoMoreData as e:
Expand Down Expand Up @@ -337,7 +357,9 @@ def handle_request(self, req, conn):
resp.write_file(respiter)
else:
for item in respiter:
resp.write(item)
yield item
if not isinstance(item, Future):
resp.write(item)

resp.close()
finally:
Expand Down