Skip to content

Commit 65e064a

Browse files
committed
Refactor WSGI handlers and add new functionalities
1 parent 58344c8 commit 65e064a

File tree

1 file changed

+91
-38
lines changed

1 file changed

+91
-38
lines changed

src/grongier/pex/wsgi/handlers.py

Lines changed: 91 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,104 @@
1-
from wsgiref.handlers import BaseHandler
2-
import io
1+
import os, sys, importlib, urllib.parse
2+
from io import BytesIO
3+
4+
__ospath = os.getcwd()
5+
36
import iris
47

5-
class IrisHandler(BaseHandler):
6-
"""Handler that's just initialized with streams, environment, etc.
8+
os.chdir(__ospath)
9+
10+
enc, esc = sys.getfilesystemencoding(), 'surrogateescape'
11+
12+
rest_service = iris.cls('%REST.Impl')
13+
14+
def get_from_module(app_path, app_module, app_name):
15+
16+
# Add the path to the application
17+
if (app_path not in sys.path) :
18+
sys.path.append(app_path)
19+
20+
# retrieve the application
21+
return getattr(importlib.import_module(app_module), app_name)
22+
23+
# Changes the current working directory to the manager directory of the instance.
24+
def goto_manager_dir():
25+
iris.system.Process.CurrentDirectory(iris.system.Util.ManagerDirectory())
26+
27+
def unicode_to_wsgi(u):
28+
# Convert an environment variable to a WSGI "bytes-as-unicode" string
29+
return u.encode(enc, esc).decode('iso-8859-1')
30+
31+
def wsgi_to_bytes(s):
32+
return s.encode('iso-8859-1')
33+
34+
def write(chunk):
35+
rest_service._WriteResponse(chunk)
36+
37+
def start_response(status, response_headers, exc_info=None):
38+
'''WSGI start_response callable'''
39+
if exc_info:
40+
try:
41+
raise exc_info[1].with_traceback(exc_info[2])
42+
finally:
43+
exc_info = None
744

8-
This handler subclass is intended for synchronous HTTP/1.0 origin servers,
9-
and handles sending the entire response output, given the correct inputs.
45+
rest_service._SetStatusCode(status)
46+
for tuple in response_headers:
47+
rest_service._SetHeader(tuple[0], tuple[1])
48+
return write
1049

11-
Usage::
1250

13-
handler = SimpleHandler(
14-
inp,out,err,env, multithread=False, multiprocess=True
15-
)
16-
handler.run(app)"""
51+
# Make request to application
52+
def make_request(environ, stream, application, path):
1753

18-
server_software = "IrisWSGI/0.1"
19-
wsgi_file_wrapper = None
54+
# Change the working directory for logging purposes
55+
goto_manager_dir()
2056

21-
def __init__(self,stdin,stdout,stderr,environ,
22-
multithread=True, multiprocess=False
23-
):
24-
self.stdin = stdin
25-
self.stdout = stdout
26-
self.stderr = stderr
27-
self.base_env = environ
28-
self.wsgi_multithread = multithread
29-
self.wsgi_multiprocess = multiprocess
57+
error_log_file = open('WSGI.log', 'a+')
58+
59+
# We want the working directory to be the app's directory
60+
if (not path.endswith(os.path.sep)):
61+
path = path + os.path.sep
3062

31-
def get_stdin(self):
32-
if not self.stdin:
33-
return None
34-
else:
35-
self.environ["wsgi.input"] = io.BytesIO(self.stdin)
36-
self.environ["CONTENT_LENGTH"] = str(len(self.stdin))
37-
return io.BytesIO(self.stdin)
63+
#iris.system.Process.CurrentDirectory(path)
64+
65+
# Set up the body of the request
66+
if stream != '':
67+
bytestream = stream
68+
elif (environ['CONTENT_TYPE'] == 'application/x-www-form-urlencoded'):
69+
bytestream = BytesIO()
70+
part = urllib.parse.urlencode(environ['formdata'])
71+
bytestream.write(part.encode('utf-8'))
72+
bytestream.seek(0)
73+
else:
74+
bytestream = BytesIO(b'')
3875

76+
#for k,v in os.environ.items():
77+
#environ[k] = unicode_to_wsgi(v)
78+
environ['wsgi.input'] = bytestream
79+
environ['wsgi.errors'] = error_log_file
80+
environ['wsgi.version'] = (1, 0)
81+
environ['wsgi.multithread'] = False
82+
environ['wsgi.multiprocess'] = True
83+
environ['wsgi.run_once'] = True
3984

40-
def get_stderr(self):
41-
return self.stderr
4285

43-
def add_cgi_vars(self):
44-
self.environ.update(self.base_env)
86+
if environ.get('HTTPS', 'off') in ('on', '1'):
87+
environ['wsgi.url_scheme'] = 'https'
88+
else:
89+
environ['wsgi.url_scheme'] = 'http'
90+
91+
# Calling WSGI application
92+
response = application(environ, start_response)
4593

46-
def _write(self,data):
47-
iris.cls('Grongier.Service.WSGI').write(data)
94+
error_log_file.close()
4895

49-
def _flush(self):
50-
self.stdout.flush()
51-
self._flush = self.stdout.flush
96+
try:
97+
for data in response:
98+
if data:
99+
# (REST.Impl).Write() needs a utf-8 string
100+
write(data.decode('utf-8'))
101+
write(b'')
102+
finally:
103+
if hasattr(response, 'close'):
104+
response.close()

0 commit comments

Comments
 (0)