Esempio n. 1
0
def main():

    settings = {
        'debug': options.debug,
    }

    if options.server == 'default':
        application = tornado.web.Application([
            (r'/httplib', HttpLibHandler),
            (r'/httplib_multi', HttpLibMultiHandler),
            (r'/requests', RequestsHandler),
            (r'/requests_multi', RequestsMultiHandler),
            (r'/async', AsyncHandler),
            (r'/async_multi', AsyncMultiHandler),
            (r'/gen', GenHandler),
            (r'/gen_multi', GenMultiHandler),
        ], **settings)

        application.listen(options.port)
        tornado.ioloop.IOLoop.instance().start()

    elif options.server == 'gevent':
        monkey.patch_all()
        application = WSGIApplication([
            (r'/httplib', GHttpLibHandler),
            (r'/httplib_multi', GHttpLibMultiHandler),
            (r'/requests', GRequestsHandler),
            (r'/requests_multi', GRequestsMultiHandler),
        ], **settings)

        server = wsgi.WSGIServer(('0.0.0.0', options.port), application)
        server.backlog = 256
        server.serve_forever()
Esempio n. 2
0
def run(port, worker='gevent', threads=False, **kwargs):
    '''
    @summary: 启动 tornado 服务
    @param {int} port: web服务绑定的访问端口
    @param {string} worker: 启动的worker,默认使用 gevent 的,以便使用协程
    @param {bool} threads: 是否线程启动,且返回此线程
    '''
    global Wsgi_Application
    add_not_found()
    app = get_apps()
    logger.info(u'监听端口:%s,程序正在启动......', port)
    # gevent + tornado 启动
    if worker == 'gevent':
        from tornado.wsgi import WSGIApplication
        from gevent.pywsgi import WSGIServer
        Wsgi_Application = WSGIApplication(app)
        server = WSGIServer(('', port), Wsgi_Application)
        logger.info(u'程序启动成功.')  # 启动后没法输出日志,所以只能提前了
        server.serve_forever()
    # 纯 tornado 启动
    else:
        from tornado.web import Application
        from tornado.httpserver import HTTPServer
        from tornado.ioloop import IOLoop
        Wsgi_Application = Application(app)
        http_server = HTTPServer(Wsgi_Application)  # 加载配置
        http_server.listen(port)  # 监听端口号
        logger.info(u'程序启动成功.')  # 启动后没法输出日志,所以只能提前了
        instance = IOLoop.instance()
        if threads:
            th = threading.Thread(target=instance.start)
            th.start()  # 启动这个线程
            return th  # 返回这个线程
        else:
            instance.start()  # 启动
 def _create(self):
     application = WSGIApplication([
         (r'/(favicon.ico)', StaticFileHandler, {
             'path': ''
         }),
         (r'/(.*)', NonCacheStaticFileHandler, {
             'path': self._opts.path,
             'default_filename': 'index.html'
         }),
     ])
     return application
Esempio n. 4
0
 def __call__(self):
     kwargs = {}
     if 'autoescape' in self.settings:
         kwargs['autoescape'] = self.settings['autoescape']
     path = self.settings.pop('template_path')
     loader = JulyLoader(path, **kwargs)
     self.settings['template_loader'] = loader
     if self.wsgi:
         app = WSGIApplication(self.handlers, self.default_host,
                               **self.settings)
         return app
     app = Application(
         self.handlers, self.default_host, self.transforms,
         self.wsgi, **self.settings
     )
     return app
Esempio n. 5
0
    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),
                        ])))
Esempio n. 6
0
def get_application():
    kwargs = dict(
        handlers=[
            (r'^/(index)?(.html)?$', IndexHandler),  # homePage
            (r'^/syncup$', SyncUpHandler),  # sync up database
            (r'^/featureDifference$', ShowFeatureDifferenceHandler
             ),  # show features difference among selected Exps
        ],
        template_path=path.join(BASE_DIR, 'web/template'),
        static_path=path.join(BASE_DIR, 'web/static'),
        cookie_secret='C4+ZSGiq/gRm06wcOo=',
        debug=DEBUG_PROJECT,
        # xsrf_cookies=True
    )
    if DEBUG_PROJECT:
        return Application(**kwargs)
    else:
        return WSGIApplication(**kwargs)
Esempio n. 7
0
    def __call__(self):
        kwargs = {}
        if 'autoescape' in self.settings:
            kwargs['autoescape'] = self.settings['autoescape']
        path = self.settings.pop('template_path')
        loader = DojangLoader(path, **kwargs)
        self.settings['template_loader'] = loader
        if self.wsgi:
            app = WSGIApplication(self.handlers, self.default_host,
                                  **self.settings)
            return app
        
        app = Application(
            handlers=self.handlers, default_host=self.default_host, transforms=self.transforms,
            wsgi=self.wsgi, **self.settings
        )
        for handler in self.sub_handlers:
            app.add_handlers(handler[0], handler[1])

        return app
Esempio n. 8
0
def make_app():
    ActionManager()
    ResourcesManager()

    am = ActionManager()

    app = WSGIApplication(
        handlers=[
            url(r"/gui/panorama", PanoramaGUIHandler, name='/gui/panorama'),
            url(r"/", IndexHandler, name='/index'),
            # url(r"/gui/tracking", TrackingGUIHandler, name='/gui/tracking'),
            url(r"/gui/logger", LoggerGUIHandler, name='/gui/logger'),
            url(r"/gui/config", ConfigGUIHandler, name='/gui/config'),
            url(r"/state", StateHandler, name='/state'),
            # url(r"/plot/(.*)?/?", PlotHandler, name='plot'),
        ],
        debug=True,
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
    )

    return app
Esempio n. 9
0
 def get_app(self):
     self.app = WSGIApplication(self.get_handlers(), **self.get_app_kwargs())
     return WSGIContainer(validator(self.app))
Esempio n. 10
0
 def get_app(self):
     return WSGIContainer(validator(WSGIApplication(self.get_handlers())))
Esempio n. 11
0
 def get_app(self):
     return WSGIContainer(validator(WSGIApplication([
                     ("/multipart", MultipartTestHandler)])))
Esempio n. 12
0
def run_gevent():
    application = WSGIApplication(gevent_handlers)
    server = WSGIServer(('', 9010), application)
    server.serve_forever()
Esempio n. 13
0
os.environ['PYTHON_EGG_CACHE'] = os.path.join(virtenv,
                                              'lib/python3.3/site-packages')
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
    exec(compile(open(virtualenv).read(), virtualenv, 'exec'),
         dict(__file__=virtualenv))
    exec_namespace = dict(__file__=virtualenv)
    with open(virtualenv, 'rb') as exec_file:
        file_contents = exec_file.read()
    compiled_code = compile(file_contents, virtualenv, 'exec')
    exec(compiled_code, exec_namespace)
except IOError:
    pass

settings = {
    'static_path': os.path.join(os.path.dirname(__file__), 'static'),
    'name': 'bot',
}

application = WSGIApplication([(r'/', MainHandler),
                               (r'/api/search', SearchHandler)], **settings)

if __name__ == '__main__':

    from wsgiref.simple_server import make_server

    ip = os.environ.get('OPENSHIFT_PYTHON_IP', 'localhost')
    port = int(os.environ.get('OPENSHIFT_PYTHON_PORT', 8051))
    httpd = make_server(ip, port, application)
    httpd.serve_forever()
Esempio n. 14
0
    def get(self):
        r = requests.get(url)
        result = r.text

        r1 = requests.get(url)
        result = r1.text

        r2 = requests.get(url)
        result = r2.text

        self.write(result)


if __name__ == '__main__':
    define('port', type=int, default=8888)
    define('debug', type=bool, default=True)
    monkey.patch_all()
    parse_command_line()
    settings = {
        'debug': options.debug,
    }

    application = WSGIApplication([
        (r'/requests', RequestsHandler),
        (r'/requests_multi', RequestsMultiHandler),
    ], **settings)

    server = wsgi.WSGIServer(('0.0.0.0', options.port), application)
    server.backlog = 256
    server.serve_forever()
Esempio n. 15
0
                          permanent=True)

    def get(self):
        raise HTTPError(404, 'Http is not supported, only https')


http_application = Application([
    (r'.*', HttpHandler),
])

tr = WSGIContainer(app)

settings = {"static_path": STATIC_PATH, "debug": IS_DEBUG}

https_application = WSGIApplication([
    (r".*", FallbackHandler, dict(fallback=tr)),
], **settings)

if __name__ == "__main__":
    ssl_settings = dict(
        ssl_options={
            "certfile": os.path.join("client/ssl/server.crt"),
            "keyfile": os.path.join("client/ssl/server.key")
        })
    https_server = HTTPServer(https_application, **ssl_settings)
    https_server.listen(PORT)

    http_server = HTTPServer(http_application)
    http_server.listen(80)

    print 'Listening on port %d' % PORT
Esempio n. 16
0
        conn1 = httplib.HTTPConnection(host)
        conn1.request('GET', path)
        r1 = conn1.getresponse()
        result = r1.read()

        conn2 = httplib.HTTPConnection(host)
        conn2.request('GET', path)
        r2 = conn2.getresponse()
        result = r2.read()

        self.write(result)


if __name__ == '__main__':
    define('port', type=int, default=8888)
    define('debug', type=bool, default=True)
    monkey.patch_all()
    parse_command_line()
    settings = {
        'debug': options.debug,
    }

    application = WSGIApplication([
        (r'/httplib', HttpLibHandler),
        (r'/httplib_multi', HttpLibMultiHandler),
    ], **settings)

    server = wsgi.WSGIServer(('0.0.0.0', options.port), application)
    server.backlog = 256
    server.serve_forever()
Esempio n. 17
0
class HelloServer(TCPServer):
    def handle_stream(self, stream, address):
        stream.write(b"Hello, World\n")
        stream.close()


# serve a tornado app like:
#   chaussette --backend tornado examples.tornado.app.tornadoapp
# test is with:
#   curl http://127.0.0.1:8080/
tornadoapp = Application([('/', HelloHandler)])

# serve a wsgi app:
#   chaussette --backend tornado examples.tornado.app.wsgiapp
# test is with:
#   curl http://127.0.0.1:8080/
wsgiapp = WSGIApplication([('/', HelloHandler)])

# serve a tornado HTTPServer:
#   chaussette --backend tornado examples.tornado.app.hellohttp
# test is with:
#   curl http://127.0.0.1:8080/
hellohttp = HTTPServer(tornadoapp)

# serve a tornado TCPServer:
#   chaussette --backend tornado examples.tornado.app.hellotcp
# beware this is NOT a HTTP server, test it with:
#   nc 127.0.0.1 8080
hellotcp = HelloServer()
Esempio n. 18
0
sys.path.append('../libs')  # 导入第三方库, tornado + gevent

import tornado
import tornado.web

from gevent import monkey
monkey.patch_all()


# 有多个耗时请求
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        start = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        time.sleep(5)
        end = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        self.finish({'result': 0, 'start': start, 'end': end})
        return


application = [
    (r"/test", MainHandler),
]

if __name__ == "__main__":
    from tornado.wsgi import WSGIApplication
    from gevent.pywsgi import WSGIServer
    server = WSGIServer(('', 13161), WSGIApplication(application))
    server.serve_forever()

# http://127.0.0.1:13161/test