Skip to content

Commit aed2ed4

Browse files
committed
Introduce middleware to convert data to bytes
Signed-off-by: Ivan Kanakarakis <[email protected]>
1 parent c4c58ae commit aed2ed4

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

example/sp-wsgi/sp.py

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -704,13 +704,6 @@ def main(environ, start_response, sp):
704704
)
705705
body.append("<br><a href='/logout'>logout</a>")
706706

707-
body = [
708-
item
709-
if isinstance(item, six.binary_type)
710-
else item.encode("utf-8")
711-
for item in body
712-
]
713-
714707
resp = Response(body)
715708
return resp(environ, start_response)
716709

@@ -882,6 +875,28 @@ def application(environ, start_response):
882875
return resp(environ, start_response)
883876

884877

878+
class ToBytesMiddleware(object):
879+
"""Converts a message to bytes to be sent by WSGI server."""
880+
881+
def __init__(self, app):
882+
self.app = app
883+
884+
def __call__(self, environ, start_response):
885+
data = self.app(environ, start_response)
886+
887+
if isinstance(data, list):
888+
return (
889+
d
890+
if isinstance(d, bytes)
891+
else d.encode("utf-8")
892+
for d in data
893+
)
894+
elif isinstance(data, str):
895+
return data.encode("utf-8")
896+
897+
return data
898+
899+
885900
if __name__ == "__main__":
886901
try:
887902
from cheroot.wsgi import Server as WSGIServer
@@ -966,7 +981,7 @@ def application(environ, start_response):
966981
pass
967982
ds.DefaultSignature(sign_alg, digest_alg)
968983

969-
SRV = WSGIServer((HOST, PORT), application)
984+
SRV = WSGIServer((HOST, PORT), ToBytesMiddleware(application))
970985

971986
_https = ""
972987
if service_conf.HTTPS:

0 commit comments

Comments
 (0)