def add_rules(self, rules): if hasattr(self, 'wildcard_router'): # Tornado 4.5+ self.wildcard_router.add_rules(rules) elif not self.handlers: self.add_handlers(r'.*$', rules) else: rules = [tornadoweb.URLSpec(*r) for r in rules] self.handlers[0][1].extend(rules)
def __init__(self, external_handlers, queue, build_manager): """ external_handlers: (url, handlercls) -> [cfg, cfg, ...] queue: the jobqueue.Queue where new builds/jobs are put in build_manager: build_manager.BuildManager for caching and restoring buils from disk. """ # this dict will be the kwargs of each urlhandler handler_args = { "queue": queue, "build_manager": build_manager, } # url handler configuration dict # (urlmatch, requesthandlerclass) => custom_args urlhandlers = dict() urlhandlers[("/", PlainStreamHandler)] = None urlhandlers[("/ws", WebSocketHandler)] = None urlhandlers[("/robots.txt", RobotsHandler)] = None urlhandlers.update(external_handlers) # create the tornado application # that serves assigned urls to handlers: # [web.URLSpec(match, handler, kwargs)] handlers = list() for (url, handler), custom_args in urlhandlers.items(): logging.info(f"registering url handler for {url}...") # custom handlers may have custom kwargs if custom_args is not None: kwargs = handler_args.copy() kwargs.update(custom_args) handler = web.URLSpec(url, handler, kwargs) else: handler = web.URLSpec(url, handler, handler_args) handlers.append(handler) app = web.Application(handlers) # bind http server to tcp port self.server = httpserver.HTTPServer(app) self.server.listen(port=CFG.dyn_port, address=str(CFG.dyn_address))
def add_favicon_path(self, path: str) -> None: """Add path to serve favicon file. ``path`` should be a directory, which contains favicon file (``favicon.ico``) for your app. """ spec = web.URLSpec('/(favicon.ico)', StaticFileHandler, dict(path=path)) # Need some check handlers = self.handlers[0][1] handlers.append(spec)
def _parse_handlers_urlspec(self, handlers_list): result = [] for item in handlers_list: if isinstance(item, web.URLSpec): result.append(item) elif isinstance(item, compat.list_type) and len(item) in (2, 3, 4): item = web.URLSpec(*item) result.append(item) if item.name: self.named_handlers[item.name] = item else: raise ConfigurationError('Element not supported: %s' % item) return result
def __init__(self): handlers = [ url(r'/', EnterHandler, name='enterPoint'), url(r'/login', LoginHandler, dict(database=clientMy)), web.URLSpec(r'/help', HelpHandler, name='help'), url(r'/welcome', WelcomeHandler, dict(database=clientMon), name='welcome'), web.URLSpec(r'/logout', LogoutHandler, name='logout') ] settings = { "static_path": os.path.join(os.path.dirname(__file__), "static"), "template_path": os.path.join(os.path.dirname(__file__), 'templates'), "xsrf_cookies": True, "debug": True, "cookie_secret": "*************************", "login_url": '/login', "static_url_prefix": "/static/" } tornado.web.Application.__init__(self, handlers=handlers, **settings)
def __init__(self, config): self._graph = tf.Graph() tf_config = None if not config.get("gpu", None): tf_config = tf.ConfigProto(device_count={"GPU": 0}) else: tf_config = tf.ConfigProto(device_count={"GPU": 1}) tf_config.gpu_options.allow_growth = True tf_config.gpu_options.per_process_gpu_memory_fraction = config[ "gpu_memory_fraction"] self._sess = tf.Session(config=tf_config, graph=self._graph) with self._sess.graph.as_default(): graph_def = tf.GraphDef() with open(config['model'], 'rb') as file: graph_def.ParseFromString(file.read()) tf.import_graph_def(graph_def, name="") self._input_x = self._sess.graph.get_operation_by_name( 'ph_input_x').outputs[0] self._pred = self._sess.graph.get_operation_by_name( 'predictions').outputs[0] self._softmax = self._sess.graph.get_operation_by_name( 'softmax').outputs[0] self._http_app = web.Application( handlers=[ web.URLSpec(r"/api/echo/(.*)", EchoHandler, dict(app=self)), web.URLSpec(r"/api/image", EchoHandler, dict(app=self)), web.URLSpec(r"/ui/segmentation", TestUIHandler, dict(app=self)) ], debug=config["debug"], )
def initialize(debug=False): """ Initialize something. """ global application, config settings = { 'debug': debug, "static_path": os.path.join(os.path.dirname(__file__), "static"), } if debug: config = libs.config.get_config(conf='offline.cfg') application = web.Application([ # ad handler (r'/instdown/resource', ResourceHandler), (r'/', IndexHandler), web.URLSpec(r"/(.*)", web.StaticFileHandler, {"path": "static"}), ], **settings)
def run(self): # Cannot access IOLoop until after fork, since the epoll FD is lost otherwise params = {'daemon': self} # Helper function to pass players into the connection handler def connection(*args): return PlayerClientConnection(self, self.config.players, *args) socket_router = SockJSRouter(connection, prefix='/client', io_loop=self.io_loop) urls = [ web.URLSpec('^/discs$', DiscListHandler, params), web.URLSpec('^/discs/([^/]+)$', DiscHandler, params), web.URLSpec('^/discs/([^/]+)/musicbrainz$', MusicbrainzHandler, params), web.URLSpec('^/players$', PlayerListHandler, params), web.URLSpec('^/players/([^/]+)$', PlayerHandler, params), web.URLSpec('^/players/([^/]+)/([^/]+)$', PlayerCommandHandler, params), web.URLSpec( '^/(.*)', web.StaticFileHandler, { 'path': resource_filename('codplayer', 'data/dbadmin'), 'default_filename': 'codadmin.html' }) ] self._app = web.Application(socket_router.urls + urls, serve_traceback=True, compress_response=not self._debug_mode, static_hash_cache=not self._debug_mode, log_function=self._log_request) server = httpserver.HTTPServer(self._app, io_loop=self.io_loop) server.add_sockets(self._server_sockets) for p in self.config.players: p.start(self, socket_router) self.log('listening on {}:{}', self.config.host, self.config.port) self.io_loop.start()
# -*- coding: utf-8 -*- import memcache from tornado import web from handlers import main application = web.Application([ web.URLSpec(r'/from_cache', main.Index, name='index'), ], debug=True) # Чтобы доступ к кэшу иметь из любого хендлера application.cache = memcache.Client(['127.0.0.1'])
email = message_form.email.data address = message_form.address.data msg = message_form.message message = Message() message.name = name message.email = email message.address = address message.message = msg message.save() self.render("message.html", message_form=message_form) settings = { "static_path": os.path.join(os.path.abspath(os.path.dirname(__file__)), "static"), "static_url_prefix": "/static/", "template_path": "templates", } if __name__ == "__main__": app = web.Application([ web.URLSpec(r'/', MainHandler, name="index"), ], debug=True, **settings) app.listen(8888) ioloop.IOLoop.current().start()
message=message) settings = { "static_path": os.path.join(os.path.abspath(os.path.dirname(__file__)), "static"), "static_url_prefix": "/static/", "template_path": "templates", } if __name__ == "__main__": db_config = { "host": "127.0.0.1", "port": 3306, "user": "******", "password": "******", "db": "mytest", "charset": "utf8", "autocommit": True, } app = web.Application([ web.URLSpec(r'/', MainHandler, {"db_config": db_config}, name="index"), ], debug=True, **settings) app.listen(8888) ioloop.IOLoop.current().start()
def add_routes(self, context, *handlers): self.url_specs[context] += [ web.URLSpec(*handler).regex for handler in handlers ] self.add_handlers(r'.*$', handlers)
from tornado import web from admin.handler.bijiaHandler import AdminBijiaHandler from admin.handler.companyHandler import AdminCompanyHandler, AdminCompanyAddHandler, AdminCompanyUpdateHandler, AdminCompanyDeleteHandler from admin.handler.countryHandler import AdminCountryAddHandler, AdminCountryUpdateHandler, AdminCountryDeleteHandler from admin.handler.countryHandler import AdminCountryHandler from admin.handler.loginHandler import AdminLoginHandler, AdminLogoutHandler from admin.handler.nodeHandler import AdminNodeHandler, AdminNodeAddHandler, AdminNodeUpdateHandler, \ AdminNodeDeleteHandler from admin.handler.priceHandler import AdminPriceHandler, AdminPriceAddHandler, AdminPriceUpdateHandler, AdminPriceDeleteHandler from admin.handler.roleHandler import AdminRoleHandler, AdminRoleAddHandler, AdminRoleUpdateHandler, \ AdminRoleDeleteHandler from admin.handler.userHandler import AdminUserHandler, AdminUserAddHandler, AdminUserUpdateHandler, AdminUserDeleteHandler admin_urls = [ # 首页 登录 登出 web.URLSpec(r"/", AdminBijiaHandler, name="index"), web.URLSpec(r"/admin", AdminBijiaHandler, name="admin"), web.URLSpec(r"/login", AdminLoginHandler, name="login"), web.URLSpec(r"/logout", AdminLogoutHandler, name="logout"), # 用户管理 web.URLSpec(r"/admin/user", AdminUserHandler, name="admin_user"), web.URLSpec(r"/admin/user/add", AdminUserAddHandler, name="admin_user_add"), web.URLSpec(r"/admin/user/update", AdminUserUpdateHandler, name="admin_user_update"), web.URLSpec(r"/admin/user/delete", AdminUserDeleteHandler, name="admin_user_delete"), # 角色管理 web.URLSpec(r"/admin/role", AdminRoleHandler, name="admin_role"),
from tornado import web from tornado import ioloop class MainHandler(web.RequestHandler): def get(self, *args, **kwargs): self.write('<a href="%s">link to story 1</a>' % self.reverse_url("story", "1")) class StoryHandler(web.RequestHandler): def initialize(self, db): self.db = db def get(self, story_id): self.write("this is story %s" % story_id) if __name__ == "__main__": app = web.Application([ web.URLSpec(r'/', MainHandler), web.URLSpec(r'/story/(?P<story_id>\d+)', StoryHandler, dict(db="mysql"), name="story") ]) app.listen(8000) ioloop.IOLoop.current().start()
from tornado import ioloop, web from parking.shared.rest_models import ParkingLotCreationResponse from parking.shared.util import serialize_model class MyHandler(web.RequestHandler): def post(self): print(self.request.body.rstrip()) self.write(serialize_model(ParkingLotCreationResponse(1))) app = web.Application([ web.URLSpec('/spaces', MyHandler), web.URLSpec('/spaces/1/price', MyHandler) ]) app.listen(port=5000) ioloop.IOLoop.current().start()
# -*- coding: utf-8 -*- from tornado import web from handlers import main from helpers import APP_SETTINGS application = web.Application([ web.URLSpec(r'/repos', main.ShowRepos, name='show'), web.URLSpec(r'/repos/create', main.CreateRepo, name='create'), web.URLSpec(r'/repos/(\d+)', main.ViewRepo, name='view'), web.URLSpec(r'/repos/(\d+)/update', main.UpdateRepo, name='update'), web.URLSpec(r'/', web.RedirectHandler, {'url': '/repos'}, name='index') ], **APP_SETTINGS)
class PeopleNameHandler(web.RequestHandler): async def get(self, id, *args, **kwargs): self.write("用户姓名:{}".format(id)) class PeopleInfoHandler(web.RequestHandler): async def get(self, id, name, age, gender, *args, **kwargs): self.write("用户姓名:{}\n年龄:{}\n性别:{}".format(name, age, gender)) peolpe_db = {"name": "people"} urls = [ web.URLSpec("/", MainHandler, name="index"), web.URLSpec(r"/people/(\d+)/?", PeopleIdHandler, name="people_id"), web.URLSpec(r"/people/(\w+)/?", PeopleNameHandler, name="people_name"), # web.URLSpec(r"/people/(\w+)/(\d+)/(\w+)/?", PeopleInfoHandler, name="people_info"), web.URLSpec(r"/people/(?P<name>\w+)/(?P<age>\d+)/(?P<gender>\w+)/?", PeopleInfoHandler, name="people_info"), ] if __name__ == '__main__': app = web.Application(urls, debug=True) app.listen(8888) ioloop.IOLoop.current().start() # 1.url的各种参数配置 # 2.url命名 reverse_url
class PeopleIdHandler(web.RequestHandler): def initialize(self, name): self.name = name def get(self, id, *args, **kwargs): # self.write("用户id:{}".format(id)) self.redirect(self.reverse_url("people_name", "bobby")) class PeopleNameHandler(web.RequestHandler): def get(self, name, *args, **kwargs): self.write("用户姓名:{}".format(name)) class PeopleInfoHanler(web.RequestHandler): def get(self, name, age, gender, *args, **kwargs): self.write("用户姓名:{}, 用户年龄:{}, 用户性别:{}".format(name, age, gender)) urls = [ web.URLSpec(r'/', MainHandler, name="index"), web.URLSpec(r'/people/(?P<id>\d+)/?', PeopleIdHandler, {"name": "wanlaji"}, name="people_id"), web.URLSpec(r'/people/(?P<name>\w+)/?', PeopleNameHandler, name="people_name"), web.URLSpec(r'/people/(\w+)/(\d+)/(\w+)/?', PeopleInfoHanler, name="people_info"), ] if __name__ == "__main__": app = web.Application(urls, debug=True) app.listen(8888) ioloop.IOLoop.current().start()
f"INSERT INTO msg(name, email, address, msg) " f"VALUES('{name}', '{email}', '{address}', '{msg}')" ) else: await cur.execute( f"UPDATE msg SET " f"name='{name}', email='{email}', address='{address}', msg='{msg}' WHERE id='{sid}'" ) await conn.commit() settings = { "static_path": "/home/zpf/workarea/realForum/MsgBoard/static", "static_prefix": "/static/", "template_path": "templates", "db": { 'host': '127.0.0.1', 'user': '******', 'password': '******', 'po rt': 3306, 'db': 'rfm' } } if __name__ == "__main__": app = web.Application([ web.URLSpec("/", IndexHandler, {"db": settings["db"]}, name="index"), ], debug=True, **settings) app.listen(8080) ioloop.IOLoop.current().start()
# data2 = self.get_query_arguments() data1 = self.get_argument('name') data2 = self.get_arguments('name') pass def post(self, *args, **kwargs): data1 = self.get_argument() data2 = self.get_arguments() pass def delete(self, *args, **kwargs): pass # 输出 # 1.set_status,write_error,finish,redirect,write def write_error(self, status_code: int, **kwargs) -> None: pass urls = [ web.URLSpec("/", MainHandler, name="index"), ] if __name__ == '__main__': # 声明APP # debug=true,修改自动生效 app = web.Application(urls, debug=True) # 监听端口 app.listen(8888) ioloop.IOLoop.current().start()
from tornado import web,httpserver,ioloop import argparse import os from handlers import * import config routes = [ web.URLSpec(r'/', HomepageHandler, { 'config': config }), web.URLSpec(r'/category/([a-z]+)/(?:([0-9]{1,3})/)?', CategoryHandler, { 'config': config }), web.URLSpec(r'/product/([0-9]{6,15})/', ProductHandler, { 'config': config }), web.URLSpec(r'/basket/', BasketHandler, { 'config': config }), web.URLSpec(r'/checkout/', CheckoutHandler, { 'config': config }), web.URLSpec(r'/captcha/([0-9]{1,3})/', ImageHandler, { 'config': config }), web.URLSpec(r'/download/([a-f0-9]{32,60})/', DownloadHandler, { 'config': config }), web.URLSpec(r'/search', SearchHandler, { 'config': config }) ] def main(args): application = web.Application( routes, debug=args.debug, cookie_secret=args.secret, template_path='templates', static_path='static' ) server = httpserver.HTTPServer(application) server.bind(args.port, address=args.address) server.start() ioloop.IOLoop.current().start()
try: port = int(args[0]) except IndexError: port = 8000 ctrl = Controller() tempmon = { 'usb': USBTempMonitor, 'sdr': SDRTempMonitor, 'mock': MockTempMonitor, }[settings.THERMOMETER](ctrl) tempmon.start() application = web.Application( [ web.URLSpec('/login', LoginHandler, name='login'), (r'/', MainHandler), (r'/socket/', WebsocketHandler, { 'controller': ctrl }), (r'/(.*)', web.StaticFileHandler, { 'path': 'static' }), ], template_path='templates', debug=True, cookie_secret=settings.COOKIE_SECRET, ) application.listen( port, ssl_options=settings.SSL_CONFIG if settings.ENABLE_SECURITY else None)
) #removing the thread lock, since impact is only with present user # lock = threading.Lock() # with lock: # clients.pop(self.id) logger.debug('closed: %s. total clients: %s' % (self.id, len(clients))) class CallHandler(WebRTCHandler): pass class RecieveHandler(WebRTCHandler): pass app = web.Application([ web.URLSpec(r'/wscall', CallHandler, name='caller_ws'), web.URLSpec(r'/wsrecieve', RecieveHandler, name='reciever_ws'), (r'/static/(.*)', web.StaticFileHandler, { 'path': STATIC_DIR }), web.URLSpec(r'/call', CallTemplateHandler, name='caller_page'), web.URLSpec(r'/recieve', RecieveTemplateHandler, name='reciever_page'), web.URLSpec(ICE_URL, ICEServerHandler, name='ice_url'), web.URLSpec(r'/connections', ClientConnectionsHandler, name='clients_url'), ]) if __name__ == '__main__': app.listen(APP_PORT) ioloop.IOLoop.instance().start()
setting={ 'template_path':op.join(op.dirname(__file__),'templates'), 'static_path':op.join(op.dirname(__file__),'static'), 'debug':True, 'login_url':'/login', #'xsrf_cookies':True, 'cookie_secret':'f825c9e08b' } app=tornado.web.Application( handlers=[ web.URLSpec(r'/',MainHandler, name='index'), (r'/login',LoginHandler), (r'/logout',LogoutHandler), (r'/register',RegisterHandler), (r'/confirm/(.*)/(.*)', ConfirmHandler), (r'/reconfirm/(.*)', ReconfirmHandler), (r'/change-password', ChangePasswordHandler), (r'/reset-password', ResetPasswordHandler), (r'/change-email', ChangeEmailHandler), (r'/user', UserprofileHandler), (r'/edit-profile', EditUserprofileHandler), (r'/post', PostHandler), (r'/post/(\d+)', PostHandler), (r'/edit/(\d+)', EditHandler), (r'/delete/(\d+)', DeleteHandler), (r'/upload', UploadHandler),
class PeopleNameHandler(web.RequestHandler): async def get(self, name, *args, **kwargs): self.write(f"用户name:{name},") class PeopleInfoHandler(web.RequestHandler): async def get(self, name, age, gender, *args, **kwargs): self.write(f"用户name:{name}, 用户age:{age}, 用户gender:{gender}, ") people_db = {"name": "people"} urls = [ web.URLSpec("/", MainHandler, name="index"), # web.URLSpec("/people/(\d+)/?", PeopleIdHandler, people_db, name="people_id"),# 配置如/people/1/ web.URLSpec("/people/(?P<id>\d+)/?", PeopleIdHandler, people_db, name="people_id"), # 配置如/people/1/ web.URLSpec("/people/(\w+)/?", PeopleNameHandler, name="people_name"), # 配置如/people/a/ web.URLSpec("/people/(\w+)/(\d+)/(\w+)/?", PeopleInfoHandler, name="people_info"), # 配置如/people/name/age/gender/ ] if __name__ == '__main__': app = web.Application(urls, debug=True) app.listen(8888)
def decorate(cls): _routes.append(web.URLSpec(r, cls, kwargs={'name': name}, name=name)) return cls