Python tornado.wsgi.WSGIContainer() Examples

The following are 30 code examples of tornado.wsgi.WSGIContainer(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado.wsgi , or try the search function .
Example #1
Source File: wsgi_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello world!")

        class PathQuotingHandler(RequestHandler):
            def get(self, path):
                self.write(path)

        # It would be better to run the wsgiref server implementation in
        # another thread instead of using our own WSGIContainer, but this
        # fits better in our async testing framework and the wsgiref
        # validator should keep us honest
        return WSGIContainer(validator(WSGIApplication([
            ("/", HelloHandler),
            ("/path/(.*)", PathQuotingHandler),
            ("/typecheck", TypeCheckHandler),
        ]))) 
Example #2
Source File: sessions.py    From boofuzz with GNU General Public License v2.0 6 votes vote down vote up
def build_webapp_thread(self, port=constants.DEFAULT_WEB_UI_PORT):
        app.session = self
        http_server = HTTPServer(WSGIContainer(app))
        while True:
            try:
                http_server.listen(port)
            except socket.error as exc:
                # Only handle "Address already in use"
                if exc.errno != errno.EADDRINUSE:
                    raise
                port += 1
            else:
                self._fuzz_data_logger.log_info("Web interface can be found at http://localhost:%d" % port)
                break
        flask_thread = threading.Thread(target=IOLoop.instance().start)
        flask_thread.daemon = True
        return flask_thread 
Example #3
Source File: routing_test.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def get_app(self):
        wsgi_app = WSGIContainer(self.wsgi_app)

        class Handler(RequestHandler):
            def get(self, *args, **kwargs):
                self.finish(self.reverse_url("tornado"))

        return RuleRouter(
            [
                (
                    PathMatches("/tornado.*"),
                    Application([(r"/tornado/test", Handler, {}, "tornado")]),
                ),
                (PathMatches("/wsgi"), wsgi_app),
            ]
        ) 
Example #4
Source File: wsgi_test.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello world!")

        class PathQuotingHandler(RequestHandler):
            def get(self, path):
                self.write(path)

        # It would be better to run the wsgiref server implementation in
        # another thread instead of using our own WSGIContainer, but this
        # fits better in our async testing framework and the wsgiref
        # validator should keep us honest
        return WSGIContainer(validator(WSGIApplication([
            ("/", HelloHandler),
            ("/path/(.*)", PathQuotingHandler),
            ("/typecheck", TypeCheckHandler),
        ]))) 
Example #5
Source File: serve.py    From denspi with Apache License 2.0 6 votes vote down vote up
def serve(get_vec, port):
    app = Flask(__name__)

    app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
    CORS(app)

    @app.route('/api', methods=['GET'])
    def api():
        query = request.args['query']
        start = time()
        out = get_vec(query)
        end = time()
        print('latency: %dms' % int((end - start) * 1000))
        return jsonify(out)

    print('Starting server at %d' % port)
    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(port)
    IOLoop.instance().start() 
Example #6
Source File: snap.py    From pypot with GNU General Public License v3.0 6 votes vote down vote up
def run(self, quiet=None, server=''):
        """ Start the tornado server, run forever.
            'quiet' and 'server' arguments are no longer used, they are keep only for backward compatibility
        """

        try:
            loop = IOLoop()
            http_server = HTTPServer(WSGIContainer(self.app))
            http_server.listen(self.port)
            loop.start()

        except socket.error as serr:
            # Re raise the socket error if not "[Errno 98] Address already in use"
            if serr.errno != errno.EADDRINUSE:
                raise serr
            else:
                logger.warning("""The webserver port {} is already used.
The SnapRobotServer is maybe already run or another software use this port.""".format(self.port)) 
Example #7
Source File: __init__.py    From AstroBox with GNU Affero General Public License v3.0 6 votes vote down vote up
def access_validation_factory(validator):
			"""
			Creates an access validation wrapper using the supplied validator.

			:param validator: the access validator to use inside the validation wrapper
			:return: an access validation wrapper taking a request as parameter and performing the request validation
			"""
			def f(request):
				"""
				Creates a custom wsgi and Flask request context in order to be able to process user information
				stored in the current session.

				:param request: The Tornado request for which to create the environment and context
				"""
				wsgi_environ = tornado.wsgi.WSGIContainer.environ(request)
				with app.request_context(wsgi_environ):
					app.session_interface.open_session(app, request)
					loginManager.reload_user()
					validator(request)
			return f 
Example #8
Source File: wsgi_test.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello world!")

        class PathQuotingHandler(RequestHandler):
            def get(self, path):
                self.write(path)

        # It would be better to run the wsgiref server implementation in
        # another thread instead of using our own WSGIContainer, but this
        # fits better in our async testing framework and the wsgiref
        # validator should keep us honest
        return WSGIContainer(validator(WSGIApplication([
                        ("/", HelloHandler),
                        ("/path/(.*)", PathQuotingHandler),
                        ("/typecheck", TypeCheckHandler),
                        ]))) 
Example #9
Source File: wsgi_test.py    From pySINDy with MIT License 6 votes vote down vote up
def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello world!")

        class PathQuotingHandler(RequestHandler):
            def get(self, path):
                self.write(path)

        # It would be better to run the wsgiref server implementation in
        # another thread instead of using our own WSGIContainer, but this
        # fits better in our async testing framework and the wsgiref
        # validator should keep us honest
        with ignore_deprecation():
            return WSGIContainer(validator(WSGIAdapter(
                Application([
                    ("/", HelloHandler),
                    ("/path/(.*)", PathQuotingHandler),
                    ("/typecheck", TypeCheckHandler),
                ])))) 
Example #10
Source File: wsgi_test.py    From teleport with Apache License 2.0 6 votes vote down vote up
def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello world!")

        class PathQuotingHandler(RequestHandler):
            def get(self, path):
                self.write(path)

        # It would be better to run the wsgiref server implementation in
        # another thread instead of using our own WSGIContainer, but this
        # fits better in our async testing framework and the wsgiref
        # validator should keep us honest
        with ignore_deprecation():
            return WSGIContainer(validator(WSGIAdapter(
                Application([
                    ("/", HelloHandler),
                    ("/path/(.*)", PathQuotingHandler),
                    ("/typecheck", TypeCheckHandler),
                ])))) 
Example #11
Source File: wsgi_test.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello world!")

        class PathQuotingHandler(RequestHandler):
            def get(self, path):
                self.write(path)

        # It would be better to run the wsgiref server implementation in
        # another thread instead of using our own WSGIContainer, but this
        # fits better in our async testing framework and the wsgiref
        # validator should keep us honest
        return WSGIContainer(validator(WSGIApplication([
            ("/", HelloHandler),
            ("/path/(.*)", PathQuotingHandler),
            ("/typecheck", TypeCheckHandler),
        ]))) 
Example #12
Source File: wsgi_test.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello world!")

        class PathQuotingHandler(RequestHandler):
            def get(self, path):
                self.write(path)

        # It would be better to run the wsgiref server implementation in
        # another thread instead of using our own WSGIContainer, but this
        # fits better in our async testing framework and the wsgiref
        # validator should keep us honest
        return WSGIContainer(validator(WSGIApplication([
            ("/", HelloHandler),
            ("/path/(.*)", PathQuotingHandler),
            ("/typecheck", TypeCheckHandler),
        ]))) 
Example #13
Source File: routing_test.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def get_app(self):
        wsgi_app = WSGIContainer(self.wsgi_app)

        class Handler(RequestHandler):
            def get(self, *args, **kwargs):
                self.finish(self.reverse_url("tornado"))

        return RuleRouter(
            [
                (
                    PathMatches("/tornado.*"),
                    Application([(r"/tornado/test", Handler, {}, "tornado")]),
                ),
                (PathMatches("/wsgi"), wsgi_app),
            ]
        ) 
Example #14
Source File: wsgi_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello world!")

        class PathQuotingHandler(RequestHandler):
            def get(self, path):
                self.write(path)

        # It would be better to run the wsgiref server implementation in
        # another thread instead of using our own WSGIContainer, but this
        # fits better in our async testing framework and the wsgiref
        # validator should keep us honest
        return WSGIContainer(validator(WSGIApplication([
            ("/", HelloHandler),
            ("/path/(.*)", PathQuotingHandler),
            ("/typecheck", TypeCheckHandler),
        ]))) 
Example #15
Source File: wsgi_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def wrap_web_tests_application():
    result = {}
    for cls in web_test.wsgi_safe_tests:
        class WSGIApplicationWrappedTest(cls):
            def get_app(self):
                self.app = WSGIApplication(self.get_handlers(),
                                           **self.get_app_kwargs())
                return WSGIContainer(validator(self.app))
        result["WSGIApplication_" + cls.__name__] = WSGIApplicationWrappedTest
    return result 
Example #16
Source File: manage.py    From Flask-Large-Application-Example with MIT License 5 votes vote down vote up
def tornadoserver():
    setup_logging('tornadoserver')
    app = create_app(parse_options())
    fsh_folder = app.blueprints['flask_statics_helper'].static_folder
    log_messages(app, OPTIONS['--port'], fsh_folder)

    # Setup the application.
    container = wsgi.WSGIContainer(app)
    application = web.Application([
        (r'/static/flask_statics_helper/(.*)', web.StaticFileHandler, dict(path=fsh_folder)),
        (r'/(favicon\.ico)', web.StaticFileHandler, dict(path=app.static_folder)),
        (r'/static/(.*)', web.StaticFileHandler, dict(path=app.static_folder)),
        (r'.*', web.FallbackHandler, dict(fallback=container))
    ])  # From http://maxburstein.com/blog/django-static-files-heroku/
    http_server = httpserver.HTTPServer(application)
    http_server.bind(OPTIONS['--port'])

    # Start the server.
    http_server.start(0)  # Forks multiple sub-processes
    ioloop.IOLoop.instance().start() 
Example #17
Source File: wsgi_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_types(self):
        headers = {"Cookie": "foo=bar"}
        response = self.fetch("/typecheck?foo=bar", headers=headers)
        data = json_decode(response.body)
        self.assertEqual(data, {})

        response = self.fetch("/typecheck", method="POST", body="foo=bar", headers=headers)
        data = json_decode(response.body)
        self.assertEqual(data, {})

# This is kind of hacky, but run some of the HTTPServer tests through
# WSGIContainer and WSGIApplication to make sure everything survives
# repeated disassembly and reassembly. 
Example #18
Source File: wsgi_test.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def test_types(self):
        headers = {"Cookie": "foo=bar"}
        response = self.fetch("/typecheck?foo=bar", headers=headers)
        data = json_decode(response.body)
        self.assertEqual(data, {})

        response = self.fetch("/typecheck", method="POST", body="foo=bar", headers=headers)
        data = json_decode(response.body)
        self.assertEqual(data, {})

# This is kind of hacky, but run some of the HTTPServer tests through
# WSGIContainer and WSGIApplication to make sure everything survives
# repeated disassembly and reassembly. 
Example #19
Source File: wsgi_test.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def get_app(self):
        return WSGIContainer(validator(WSGIApplication(self.get_handlers()))) 
Example #20
Source File: tornado_wsgi.py    From web_develop with GNU General Public License v3.0 5 votes vote down vote up
def main():
    define('port', default=9000, type=int, help='Port on which to listen.')
    parse_command_line()

    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(options.port)
    IOLoop.instance().start() 
Example #21
Source File: pysdr_app.py    From pysdr with GNU General Public License v3.0 5 votes vote down vote up
def create_web_server(self):
        # Create the web server using tornado (separate from Bokeh server)
        print('Opening Flask app with embedded Bokeh application on http://localhost:8080/')
        http_server = HTTPServer(WSGIContainer(self.flask_app)) # A non-blocking, single-threaded HTTP server. serves the WSGI app that flask provides. WSGI was created as a low-level interface between web servers and web applications or frameworks to promote common ground for portable web application development
        http_server.listen(8080) # this is the single-process version, there are multi-process ones as well
        # Open browser to main page
        self.io_loop.add_callback(view, "http://localhost:8080/") # calls the given callback (Opens browser to specified location) on the next I/O loop iteration. provides thread-safety 
Example #22
Source File: origami.py    From origami-lib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run(self):
        """
        Starts the flask server over Tornados WSGI Container interface
        Also provide websocket interface at /websocket for persistent
        connections

        To run this server just create an instance of Origami Class and call
        this function

        .. code-block:: python

            from origami_lib.origami import Origami

            app = Origami("My Model")
            app.run()


        Raises:
            OrigamiServerException: Exception when the port we are trying to \
                bind to is already in use.
        """
        try:
            port = constants.DEFAULT_PORT
            http_server = WSGIContainer(self.server)

            # Register a web application with websocket at /websocket
            server = Application([(r'/websocket', OrigamiWebSocketHandler),
                                  (r'/fass', FunctionServiceHandler),
                                  (r'.*', FallbackHandler,
                                   dict(fallback=http_server))])

            server.listen(port)
            print("Origami server running on port: {}".format(port))
            IOLoop.instance().start()
        except OSError:
            raise exceptions.OrigamiServerException(
                "ORIGAMI SERVER ERROR: Port {0} already in use.".format(port)) 
Example #23
Source File: wsgi_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def get_app(self):
        return WSGIContainer(validator(self.wsgi_app)) 
Example #24
Source File: app.py    From robotframework-hub with Apache License 2.0 5 votes vote down vote up
def start(self):
        """Start the app"""
        if self.args.debug:
            self.app.run(port=self.args.port, debug=self.args.debug, host=self.args.interface)
        else:
            root = "http://%s:%s" % (self.args.interface, self.args.port)
            print("tornado web server running on " + root)
            self.shutdown_requested = False
            http_server = HTTPServer(WSGIContainer(self.app))
            http_server.listen(port=self.args.port, address=self.args.interface)

            signal.signal(signal.SIGINT, self.signal_handler)
            tornado.ioloop.PeriodicCallback(self.check_shutdown_flag, 500).start()
            tornado.ioloop.IOLoop.instance().start() 
Example #25
Source File: wsgi_test.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def get_app(self):
        return WSGIContainer(validator(self.wsgi_app)) 
Example #26
Source File: wsgi_test.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def get_app(self):
        return WSGIContainer(validator(self.wsgi_app)) 
Example #27
Source File: wsgi_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def get_app(self):
        return WSGIContainer(validator(WSGIApplication(self.get_handlers()))) 
Example #28
Source File: wsgi_test.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def test_types(self):
        headers = {"Cookie": "foo=bar"}
        response = self.fetch("/typecheck?foo=bar", headers=headers)
        data = json_decode(response.body)
        self.assertEqual(data, {})

        response = self.fetch("/typecheck", method="POST", body="foo=bar", headers=headers)
        data = json_decode(response.body)
        self.assertEqual(data, {})

# This is kind of hacky, but run some of the HTTPServer tests through
# WSGIContainer and WSGIApplication to make sure everything survives
# repeated disassembly and reassembly. 
Example #29
Source File: wsgi_test.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def get_app(self):
        return WSGIContainer(validator(WSGIApplication(self.get_handlers()))) 
Example #30
Source File: wsgi_test.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def wrap_web_tests_application():
    result = {}
    for cls in web_test.wsgi_safe_tests:
        class WSGIApplicationWrappedTest(cls):
            def get_app(self):
                self.app = WSGIApplication(self.get_handlers(),
                                           **self.get_app_kwargs())
                return WSGIContainer(validator(self.app))
        result["WSGIApplication_" + cls.__name__] = WSGIApplicationWrappedTest
    return result