How to use the wsgiref.handlers.SimpleHandler function in wsgiref

To help you get started, we’ve selected a few wsgiref examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github gevent / gevent / src / greentest / 3.5 / test_wsgiref.py View on Github external
def testPartialWrite(self):
        written = bytearray()

        class PartialWriter:
            def write(self, b):
                partial = b[:7]
                written.extend(partial)
                return len(partial)

            def flush(self):
                pass

        environ = {"SERVER_PROTOCOL": "HTTP/1.0"}
        h = SimpleHandler(BytesIO(), PartialWriter(), sys.stderr, environ)
        msg = "should not do partial writes"
        with self.assertWarnsRegex(DeprecationWarning, msg):
            h.run(hello_app)
        self.assertEqual(b"HTTP/1.0 200 OK\r\n"
            b"Content-Type: text/plain\r\n"
            b"Date: Mon, 05 Jun 2006 18:49:54 GMT\r\n"
            b"Content-Length: 13\r\n"
            b"\r\n"
            b"Hello, world!",
            written)
github zim-desktop-wiki / zim-desktop-wiki / tests / www.py View on Github external
#print("CALL:", command, path)
			environ = {
				'REQUEST_METHOD': command,
				'SCRIPT_NAME': '',
				'PATH_INFO': path,
				'QUERY_STRING': '',
				'SERVER_NAME': 'localhost',
				'SERVER_PORT': '80',
				'SERVER_PROTOCOL': '1.0'
			}
			if auth_creds:
				auth_creds_string = auth_creds[0] + ':' + auth_creds[1]
				environ['HTTP_AUTHORIZATION'] = 'Basic ' + base64.b64encode(auth_creds_string.encode('ASCII')).decode('UTF-8')
			rfile = BytesIO(b'')
			wfile = BytesIO()
			handler = wsgiref.handlers.SimpleHandler(rfile, wfile, sys.stderr, environ)
			handler.run(validator)
			return wfile.getvalue()
github gevent / gevent / src / greentest / 3.8 / test_wsgiref.py View on Github external
def testClientConnectionTerminations(self):
        environ = {"SERVER_PROTOCOL": "HTTP/1.0"}
        for exception in (
            ConnectionAbortedError,
            BrokenPipeError,
            ConnectionResetError,
        ):
            with self.subTest(exception=exception):
                class AbortingWriter:
                    def write(self, b):
                        raise exception

                stderr = StringIO()
                h = SimpleHandler(BytesIO(), AbortingWriter(), stderr, environ)
                h.run(hello_app)

                self.assertFalse(stderr.getvalue())
github bruderstein / PythonScript / PythonLib / full / wsgiref / simple_server.py View on Github external
from http.server import BaseHTTPRequestHandler, HTTPServer
import sys
import urllib.parse
from wsgiref.handlers import SimpleHandler
from platform import python_implementation

__version__ = "0.2"
__all__ = ['WSGIServer', 'WSGIRequestHandler', 'demo_app', 'make_server']


server_version = "WSGIServer/" + __version__
sys_version = python_implementation() + "/" + sys.version.split()[0]
software_version = server_version + ' ' + sys_version


class ServerHandler(SimpleHandler):

    server_software = software_version

    def close(self):
        try:
            self.request_handler.log_request(
                self.status.split(' ',1)[0], self.bytes_sent
            )
        finally:
            SimpleHandler.close(self)



class WSGIServer(HTTPServer):

    """BaseHTTPServer that implements the Python WSGI protocol"""
github minixalpha / SourceLearning / wsgiref-0.1.2 / src / wsgiref / simple_server.py View on Github external
# M:
#        +-------------+
#        | BaseHandler |   start_response(status, headers, exc_info)
#        +-------------+
#               |
#               V
#       +----------------+
#       | SimpleHandler  |
#       +----------------+
#               |
#               V
#       +---------------+
#       | ServerHandler |
#       +---------------+
# 
class ServerHandler(SimpleHandler):

    server_software = software_version

    def close(self):
        # M:
        # S.split([sep [,maxsplit]]) -> list of strings
        # >>> status
        # '200 OK'
        # >>> status.split(' ', 0)
        # ['200 OK']
        # >>> status.split(' ', 1)
        # ['200', 'OK']
        # >>> status.split(' ', 2)
        # ['200', 'OK']
github ossobv / asterisklint / web / wsgi.py View on Github external
}


MessageDefManager.muted = True  # no messages to stderr

middleware = [EnvironmentCheckMiddleware()]

application = falcon.API(middleware=middleware)
application.req_options.strip_url_path_trailing_slash = True  # allow /healthz/
application.add_route('/', Index())
application.add_route('/healthz', Healthz())
application.add_route('/dialplan-check', DialplanCheck())


if __name__ == '__main__':
    class MySimpleHandler(SimpleHandler):
        def close(self):
            try:
                # Add request logging.
                self.request_handler.log_request(
                    self.status.split(' ', 1)[0], self.bytes_sent)
            finally:
                super().close()

    class MyWSGIRequestHandler(WSGIRequestHandler):
        def handle(self):
            """
            Handle a single HTTP request. Shamelessly copied from Python
            3.5 wsgiref simple_server. Adjusted the SimpleHandler to set
            multithread=False.
            """
            self.raw_requestline = self.rfile.readline(65537)
github realpython / book2-exercises / py2manager / anyserver.py View on Github external
if 'Content-Length' in environ:
            environ['CONTENT_LENGTH'] = environ[
                'Content-Length']  # necessary for POST to work with Django
        environ['wsgi.input'] = req.body

        if debug:
            print "ENVIRON: %r\n" % environ

        # SimpleHandler needs file-like stream objects for
        # requests, errors and responses
        reqIO = StringIO.StringIO(req.body)
        errIO = StringIO.StringIO()
        respIO = StringIO.StringIO()

        # execute the application
        handler = SimpleHandler(reqIO, respIO, errIO, environ,
                                multithread=False, multiprocess=False)
        handler.run(application)

        # Get the response and filter out the response (=data) itself,
        # the response headers,
        # the response status code and the response status description
        response = respIO.getvalue()
        response = response.split("\r\n")
        data = response[-1]
        headers = dict([r.split(": ") for r in response[1:-2]])
        code = response[0][9:12]
        status = response[0][13:]

        # strip BOM's from response data
        # Especially the WSGI handler from Django seems to generate them (2 actually, huh?)
        # a BOM isn't really necessary and cause HTML parsing errors in Chrome and Safari
github ialbert / pyblue-central / pyblue_old / main.py View on Github external
def get(self, f):
        """
        Get the content of a file, indentified by its path relative to the folder configured
        in PyGreen. If the file extension is one of the extensions that should be processed
        through Mako, it will be processed.
        """
        handler = wsgiref.handlers.SimpleHandler(sys.stdin, sys.stdout, sys.stderr, {})
        handler.setup_environ()
        env = handler.environ
        env.update({'PATH_INFO': "/%s" % f.fname, 'REQUEST_METHOD': "GET"})
        out = b"".join(self.app(env, lambda *args: None))
        return out
github ialbert / pyblue-central / pyhp.py View on Github external
def get(self, path):
        handler = wsgiref.handlers.SimpleHandler(sys.stdin, sys.stdout, sys.stderr, {})
        handler.setup_environ()
        env = handler.environ
        env.update({'PATH_INFO': "/%s" % path, 'REQUEST_METHOD': "GET"})
        out = b"".join(pyhp.app(env, lambda *args: None))
        return out
github h3llrais3r / Auto-Subliminal / lib / ws4py / server / wsgirefserver.py View on Github external
- Attach the returned websocket, if any, to the WSGI server
          using its ``link_websocket_to_server`` method.
        """
        # force execution of the result iterator until first actual content
        rest = iter(self.result)
        first = list(itertools.islice(rest, 1))
        self.result = itertools.chain(first, rest)

        # now it's safe to look if environ was modified
        ws = None
        if self.environ:
            self.environ.pop('ws4py.socket', None)
            ws = self.environ.pop('ws4py.websocket', None)

        try:
            SimpleHandler.finish_response(self)
        except:
            if ws:
                ws.close(1011, reason='Something broke')
            raise
        else:
            if ws:
                self.request_handler.server.link_websocket_to_server(ws)