def __init__(self, port, is_https): WSGIApplication.__init__(self, self._gen_handlers(), "", **self.settings) self.jinja_env = self._gen_jinja_env() super(HttpRpcServer, self).__init__( PT_HTTPS if is_https else PT_HTTP, port, WSGIServer(('', port), self, **self.ssl_args if is_https else {}))
def __init__(self, rest_handlers, resource=None, handlers=None, default_host="", **settings): restservices = [] self.resource = resource for r in rest_handlers: svs = self._generateRestServices(r) restservices += svs if handlers != None: restservices += handlers WSGIApplication.__init__(self, restservices, default_host, **settings)
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()
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 __init__(self, ssl_args, port, handlers=None, default_host="", jinja_env=None, **settings): handlers += [url("/ping", HttpPingHandle, {}, "ping handler")] handlers += [ url("/set_logger_level", SetLoggerLevelHandle, {}, "Set Logger Level handler") ] WSGIApplication.__init__(self, handlers, default_host, **settings) self.server = WSGIServer(('', port), self, **ssl_args) self.port = port self.protocol = PT_HTTPS if ssl_args else PT_HTTP self.jinja_env = jinja_env
def __init__(self, port, host_name): self.port = port self.host_name = host_name #self.db = PangeaDb() self.db = PangeaDb() self.table_service = TableService(self.db) object_id_regex = "[0-9a-fA-F]{24}" if "OPENSHIFT_REPO_DIR" in os.environ: static_path = os.path.join(os.environ['OPENSHIFT_REPO_DIR'], "static") template_path = os.path.join(os.environ['OPENSHIFT_REPO_DIR'], "templates") else: static_path = os.path.join(os.path.dirname(__file__), "static") template_path = os.path.join(os.path.dirname(__file__), "templates") handlers = [ (r"/", IndexHandler), (r"/css/(.*)", StaticFileHandler, {"path": "./static/css"}), (r"/js/(.*)", StaticFileHandler, {"path": "./static/js"}), (r"/api/lobbies/({0})".format(object_id_regex), LobbyHandler), (r"/api/lobbies$", LobbyHandler), (r"/api/tables/({0})".format(object_id_regex), TableHandler), (r"/api/tables/status/({0})".format(object_id_regex), TableStatusHandler), (r"/api/tables$", TableHandler), (r"/api/players/({0})".format(object_id_regex), PlayerHandler), (r"/api/players$", PlayerHandler), (r"/api/seats$", SeatsHandler), (r"/api/bets$", BetHandler), (r"/api/chats$", ChatHandler) ] settings = dict( template_path=template_path, static_path=static_path, #debug=True ) WSGIApplication.__init__(self, handlers, **settings) #callback = PeriodicCallback(self.kick_timed_out_players, 30000) callback = PeriodicCallback(self.kick_timed_out_players, 5000) callback.start()
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
def _create(self): application = WSGIApplication([ (r'/(favicon.ico)', StaticFileHandler, { 'path': '' }), (r'/(.*)', NonCacheStaticFileHandler, { 'path': self._opts.path, 'default_filename': 'index.html' }), ]) return application
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
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), ])))
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)
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
def run_gevent(): application = WSGIApplication(gevent_handlers) server = WSGIServer(('', 9010), application) server.serve_forever()
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()
def get_app(self): return WSGIContainer(validator(WSGIApplication(self.get_handlers())))
def __init__(self, port, is_https): WSGIApplication.__init__(self, self._gen_handlers(), "", **self.settings) self.jinja_env = self._gen_jinja_env() super(HttpRpcServer, self).__init__(PT_HTTPS if is_https else PT_HTTP, port, WSGIServer(('', port), self, **self.ssl_args if is_https else {}))
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
def get_app(self): return WSGIContainer(validator(WSGIApplication([ ("/multipart", MultipartTestHandler)])))
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()
def get_app(self): self.app = WSGIApplication(self.get_handlers(), **self.get_app_kwargs()) return WSGIContainer(validator(self.app))
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()
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()
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