我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用webapp2.Route()。
def test_handle_exception_with_error(self): class HomeHandler(webapp2.RequestHandler): def get(self, **kwargs): raise TypeError() def handle_exception(request, response, exception): raise ValueError() app = webapp2.WSGIApplication([ webapp2.Route('/', HomeHandler, name='home'), ], debug=False) app.error_handlers[500] = handle_exception req = webapp2.Request.blank('/') rsp = req.get_response(app) self.assertEqual(rsp.status_int, 500)
def test_custom_method(self): class MyHandler(webapp2.RequestHandler): def my_method(self): self.response.out.write('Hello, custom method world!') def my_other_method(self): self.response.out.write('Hello again, custom method world!') app = webapp2.WSGIApplication([ webapp2.Route('/', MyHandler, handler_method='my_method'), webapp2.Route('/other', MyHandler, handler_method='my_other_method'), ]) req = webapp2.Request.blank('/') rsp = req.get_response(app) self.assertEqual(rsp.status_int, 200) self.assertEqual(rsp.body, b'Hello, custom method world!') req = webapp2.Request.blank('/other') rsp = req.get_response(app) self.assertEqual(rsp.status_int, 200) self.assertEqual(rsp.body, b'Hello again, custom method world!')
def test_custom_method_with_string(self): handler = 'tests.resources.handlers.CustomMethodHandler:custom_method' app = webapp2.WSGIApplication([ webapp2.Route('/', handler=handler), webapp2.Route('/bleh', handler=handler), ]) req = webapp2.Request.blank('/') rsp = req.get_response(app) self.assertEqual(rsp.status_int, 200) self.assertEqual(rsp.body, b'I am a custom method.') req = webapp2.Request.blank('/bleh') rsp = req.get_response(app) self.assertEqual(rsp.status_int, 200) self.assertEqual(rsp.body, b'I am a custom method.') self.assertRaises( ValueError, webapp2.Route, '/', handler=handler, handler_method='custom_method' )
def test_repetition_operator(self): route = Route(r'/<:\d>', None) self.assertEqual( route.match(Request.blank('/1')), (route, ('1',), {}) ) self.assertEqual( route.match(Request.blank('/2')), (route, ('2',), {}) ) route = Route(r'/<:\d{2,3}>', None) self.assertEqual( route.match(Request.blank('/11')), (route, ('11',), {}) ) self.assertEqual( route.match(Request.blank('/111')), (route, ('111',), {}) ) self.assertEqual(route.match(Request.blank('/1111')), None)
def test_unnamed_variable(self): route = Route(r'/<:\d{4}>', None) self.assertEqual( route.match(Request.blank('/2010')), (route, ('2010',), {}) ) self.assertEqual(route.match(Request.blank('/aaaa')), None) route = Route(r'/<:\d{2}>.<:\d{2}>', None) self.assertEqual( route.match(Request.blank('/98.99')), (route, ('98', '99'), {}) ) self.assertEqual(route.match(Request.blank('/aa.aa')), None) route = Route(r'/<:\d{2}>.<:\d{2}>/<foo>', None) self.assertEqual( route.match(Request.blank('/98.99/test')), (route, ('98', '99'), {'foo': 'test'}) ) self.assertEqual(route.match(Request.blank('/aa.aa/test')), None)
def test_positions(self): template = '/<:\d+>' * 98 args = tuple(str(i) for i in range(98)) url_res = '/' + '/'.join(args) route = Route(template, None) self.assertEqual( route.match(Request.blank(url_res)), (route, args, {}) ) url = route.build(Request.blank('/'), args, {}) self.assertEqual(url_res, url) args = [str(i) for i in range(1000)] random.shuffle(args) args = tuple(args[:98]) url_res = '/' + '/'.join(args) self.assertEqual( route.match(Request.blank(url_res)), (route, args, {}) ) url = route.build(Request.blank('/'), args, {}) self.assertEqual(url_res, url)
def test_router_repr(self): router = Router(None) router.add(Route(r"/hello", None, name="hello", build_only=True)) router.add(Route(r"/world", None)) self.assertEqual( router.__repr__(), """<Router([<Route('/world', None, """ """name=None, """ """defaults={}, """ """build_only=False)>, """ """<Route('/hello', None, """ """name='hello', """ """defaults={}, """ """build_only=True)>])>""" )
def __init__(self): """Define routes to handlers.""" super(DnsSyncApplication, self).__init__([ ('/push_notification', ComputeEngineActivityPush), ('/start_audit_log_loop', audit_log.StartAuditLogLoop), ('/logout', auth.Logout), ('/auth', auth.Oauth2Callback), ('/stop_audit_log_loop', audit_log.StopAuditLogLoop), ('/get_zone_config', zones.GetZoneConfig), ('/get_projects', zones.GetProjects), ('/get_project_zones', zones.GetProjectZones), ('/set_zone_config', zones.SetZoneConfig), ('/get_audit_log_state', audit_log.GetAuditLogState), ('/static/(.+)', AdminStaticFileHandler), ('/sync_projects', SyncProjectsWithDns), webapp2.Route( '/', webapp2.RedirectHandler, defaults={'_uri': '/static/index.html'}), webapp2.Route( '/index.html', webapp2.RedirectHandler, defaults={'_uri': '/static/index.html'}), webapp2.Route( '/favicon.ico', webapp2.RedirectHandler, defaults={'_uri': '/static/images/favicon.ico'}), ])
def test_with_variables_name_and_handler(self): router = webapp2.Router([ PathPrefixRoute('/user/<username:\w+>', [ HandlerPrefixRoute('apps.users.', [ NamePrefixRoute('user-', [ webapp2.Route('/', 'UserOverviewHandler', 'overview'), webapp2.Route( '/profile', 'UserProfileHandler', 'profile'), webapp2.Route( '/projects', 'UserProjectsHandler', 'projects'), ]), ]), ]) ]) path = '/user/calvin/' match = ((), {'username': 'calvin'}) self.assertEqual(router.match(webapp2.Request.blank(path))[1:], match) self.assertEqual( router.build(webapp2.Request.blank('/'), 'user-overview', match[0], match[1]), path ) path = '/user/calvin/profile' match = ((), {'username': 'calvin'}) self.assertEqual(router.match(webapp2.Request.blank(path))[1:], match) self.assertEqual( router.build(webapp2.Request.blank('/'), 'user-profile', match[0], match[1]), path ) path = '/user/calvin/projects' match = ((), {'username': 'calvin'}) self.assertEqual(router.match(webapp2.Request.blank(path))[1:], match) self.assertEqual( router.build(webapp2.Request.blank('/'), 'user-projects', match[0], match[1]), path )
def test_simple(self): router = webapp2.Router([ DomainRoute('<subdomain>.<:.*>', [ webapp2.Route('/foo', 'FooHandler', 'subdomain-thingie'), ]) ]) self.assertRaises( webapp2.exc.HTTPNotFound, router.match, webapp2.Request.blank('/foo')) match = router.match( webapp2.Request.blank( 'http://my-subdomain.app-id.appspot.com/foo')) self.assertEqual(match[1:], ((), {'subdomain': 'my-subdomain'})) match = router.match( webapp2.Request.blank( 'http://another-subdomain.app-id.appspot.com/foo')) self.assertEqual(match[1:], ((), {'subdomain': 'another-subdomain'})) url = router.build( webapp2.Request.blank('/'), 'subdomain-thingie', (), {'_netloc': 'another-subdomain.app-id.appspot.com'} ) self.assertEqual( url, 'http://another-subdomain.app-id.appspot.com/foo' )
def test_debug_mode(self): app = webapp2.WSGIApplication([ webapp2.Route('/broken', BrokenHandler), ], debug=True) req = webapp2.Request.blank('/broken') rsp = req.get_response(app) self.assertEqual(rsp.status_int, 500)
def test_factory_2(self): """Very crazy stuff. Please ignore it.""" class MyHandler(object): def __init__(self, request, response): self.request = request self.response = response def __new__(cls, *args, **kwargs): return cls.create_instance(*args, **kwargs)() @classmethod def create_instance(cls, *args, **kwargs): obj = object.__new__(cls) if isinstance(obj, cls): obj.__init__(*args, **kwargs) return obj def __call__(self): return self def dispatch(self): self.response.write('hello') app = webapp2.WSGIApplication([ webapp2.Route('/', handler=MyHandler), ]) req = webapp2.Request.blank('/') rsp = req.get_response(app) self.assertEqual(rsp.status_int, 200) self.assertEqual(rsp.body, b'hello')
def test_encoding(self): class PostHandler(webapp2.RequestHandler): def post(self): foo = self.request.POST['foo'] if not foo: foo = 'empty' self.response.write(foo) app = webapp2.WSGIApplication([ webapp2.Route('/', PostHandler), ], debug=True) # foo with umlauts in the vowels. value = b'f\xc3\xb6\xc3\xb6' rsp = app.get_response( '/', POST={'foo': value}, headers=[('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8')] ) self.assertEqual(rsp.unicode_body, u'föö') self.assertEqual(rsp.body, value) rsp = app.get_response( '/', POST={'foo': value}, headers=[('Content-Type', 'application/x-www-form-urlencoded')] ) self.assertEqual(rsp.unicode_body, u'föö') self.assertEqual(rsp.body, value)
def test_return_is_not_wsgi_app(self): class HomeHandler(webapp2.RequestHandler): def get(self, **kwargs): return '' app = webapp2.WSGIApplication([ webapp2.Route('/', HomeHandler, name='home'), ], debug=False) req = webapp2.Request.blank('/') rsp = req.get_response(app) self.assertEqual(rsp.status_int, 500)
def test_no_variable(self): route = Route(r'/hello', None) route, args, kwargs = route.match(Request.blank('/hello')) self.assertEqual(kwargs, {}) url = route.build(Request.blank('/'), (), {}) self.assertEqual(url, '/hello') route = Route(r'/hello/world/', None) route, args, kwargs = route.match(Request.blank('/hello/world/')) self.assertEqual(kwargs, {}) url = route.build(Request.blank('/'), (), {}) self.assertEqual(url, '/hello/world/')
def test_simple_variable(self): route = Route(r'/<foo>', None) self.assertEqual( route.match(Request.blank('/bar')), (route, (), {'foo': 'bar'}) ) url = route.build(Request.blank('/'), (), dict(foo='baz')) self.assertEqual(url, '/baz')
def test_expr_variable2(self): route = Route(r'/<year:\d{4}>/foo/', None) url = route.build(Request.blank('/'), (), dict(year='2010')) self.assertEqual(url, '/2010/foo/')
def test_build_missing_argument(self): route = Route(r'/<:\d{4}>', None) self.assertRaises(KeyError, route.build, Request.blank('/'), (), {}) route = Route(r'/<:\d{4}>/<:\d{2}>', None) self.assertRaises( KeyError, route.build, Request.blank('/'), (2010,), {})
def test_build_invalid_argument(self): route = Route(r'/<:\d{4}>', None) self.assertRaises( ValueError, route.build, Request.blank('/'), ('20100',), {})
def test_build_invalid_argument2(self): route = Route(r'/<:\d{4}>', None) self.assertRaises( ValueError, route.build, Request.blank('/'), ('201a',), {})
def test_build_missing_keyword(self): route = Route(r'/<year:\d{4}>', None) self.assertRaises(KeyError, route.build, Request.blank('/'), (), {})
def test_build_invalid_keyword(self): route = Route(r'/<year:\d{4}>', None) self.assertRaises( ValueError, route.build, Request.blank('/'), (), dict(year='20100') )
def test_build_invalid_keyword2(self): route = Route(r'/<year:\d{4}>', None) self.assertRaises( ValueError, route.build, Request.blank('/'), (), dict(year='201a'))
def test_build_with_unnamed_variable(self): route = Route(r'/<:\d{4}>/<month:\d{2}>', None) url = route.build(Request.blank('/'), (2010,), dict(month=10)) self.assertEqual(url, '/2010/10') url = route.build(Request.blank('/'), ('1999',), dict(month='07')) self.assertEqual(url, '/1999/07')
def test_build_default_keyword(self): route = Route(r'/<year:\d{4}>/<month:\d{2}>', None, defaults={'month': 10}) r = Request.blank('/') url = route.build(r, (), dict(year='2010')) self.assertEqual(url, '/2010/10') route = Route(r'/<year:\d{4}>/<month:\d{2}>', None, defaults={'year': 1900}) url = route.build(Request.blank('/'), (), dict(month='07')) self.assertEqual(url, '/1900/07')
def test_build_extra_keyword(self): route = Route(r'/<year:\d{4}>', None) r = Request.blank('/') url = route.build(r, (), dict(year='2010', foo='bar')) self.assertEqual(url, '/2010?foo=bar') # Arguments are sorted. url = route.build( Request.blank('/'), (), dict(year='2010', foo='bar', baz='ding') ) self.assertEqual(url, '/2010?baz=ding&foo=bar')
def test_build_int_keyword(self): route = Route(r'/<year:\d{4}>', None) url = route.build(Request.blank('/'), (), dict(year=2010)) self.assertEqual(url, '/2010')
def test_build_int_variable(self): route = Route(r'/<:\d{4}>', None) url = route.build(Request.blank('/'), (2010,), {}) self.assertEqual(url, '/2010')
def test_router_build_error(self): router = Router(None) router.add(Route('/<year:\d{4}>', None, name='year-page')) url = router.build( Request.blank('/'), 'year-page', (), dict(year='2010')) self.assertEqual(url, '/2010') self.assertRaises( KeyError, router.build, Request.blank('/'), 'i-dont-exist', (), dict(year='2010') )
def test_reverse_template(self): route = Route('/foo', None) route.regex # Access route.regex just to set the lazy properties. self.assertEqual(route.reverse_template, '/foo') route = Route('/foo/<bar>', None) route.regex # Access route.regex just to set the lazy properties. self.assertEqual(route.reverse_template, '/foo/%(bar)s') route = Route('/foo/<bar>/<baz:\d>', None) route.regex # Access route.regex just to set the lazy properties. self.assertEqual(route.reverse_template, '/foo/%(bar)s/%(baz)s')
def test_invalid_template(self): # To break it: # <>foo:><bar<:baz> route = Route('/<foo/<:bar', None) route.regex # Access route.regex just to set the lazy properties. self.assertEqual(route.reverse_template, '/<foo/<:bar')
def test_build_only_without_name(self): self.assertRaises(ValueError, Route, r'/<foo>', None, build_only=True)
def test_route_repr(self): self.assertEqual( Route(r'/<foo>', None).__repr__(), "<Route('/<foo>', None, name=None, defaults={}, build_only=False)>" ) self.assertEqual( Route(r'/<foo>', None, name='bar', defaults={'baz': 'ding'}, build_only=True).__repr__(), """<Route('/<foo>', None, """ """name='bar', """ """defaults={'baz': 'ding'}, """ """build_only=True)>""" ) self.assertEqual( str(Route(r'/<foo>', None)), "<Route('/<foo>', None, name=None, defaults={}, build_only=False)>" ) self.assertEqual( str(Route(r"/<foo>", None, name="bar", defaults={"baz": "ding"}, build_only=True)), """<Route('/<foo>', None, """ """name='bar', """ """defaults={'baz': 'ding'}, """ """build_only=True)>""" )
def test_methods(self): route = Route(r'/', methods=['GET', 'POST']) router = Router([route]) req = Request.blank('/') req.method = 'GET' self.assertTrue(router.match(req) is not None) req.method = 'POST' self.assertTrue(router.match(req) is not None) req.method = 'PUT' self.assertRaises(webapp2.exc.HTTPMethodNotAllowed, router.match, req)
def test_redirect_to(self): app = webapp2.WSGIApplication([ webapp2.Route('/home', handler='', name='home'), ]) req = webapp2.Request.blank('/') req.app = app app.set_globals(app=app, request=req) rsp = webapp2.redirect_to('home', _code=301, _body='Weee') self.assertEqual(rsp.status_int, 301) self.assertEqual(rsp.body, b'Weee') self.assertEqual(rsp.headers.get('Location'), 'http://localhost/home')
def __init__(self, template, routes): """Initializes a URL route. :param template: A route template to match against ``environ['SERVER_NAME']``. See a syntax description in :meth:`webapp2.Route.__init__`. :param routes: A list of :class:`webapp2.Route` instances. """ super(DomainRoute, self).__init__(routes) self.template = template
def __init__(self, prefix, routes): """Initializes a URL route. :param prefix: The prefix to be prepended. :param routes: A list of :class:`webapp2.Route` instances. """ super(NamePrefixRoute, self).__init__(routes) self.prefix = prefix # Prepend a prefix to a route attribute. for route in self.get_routes(): setattr(route, self._attr, prefix + getattr(route, self._attr))
def __init__(self, prefix, routes): """Initializes a URL route. :param prefix: The prefix to be prepended. It must start with a slash but not end with a slash. :param routes: A list of :class:`webapp2.Route` instances. """ assert prefix.startswith('/') and not prefix.endswith('/'), \ 'Path prefixes must start with a slash but not end with a slash.' super(PathPrefixRoute, self).__init__(prefix, routes)
def __init__(self, dispatch, configuration): """Initializer for AdminApplication. Args: dispatch: A dispatcher.Dispatcher instance used to route requests and provide state about running servers. configuration: An application_configuration.ApplicationConfiguration instance containing the configuration for the application. """ super(AdminApplication, self).__init__( [('/datastore', datastore_viewer.DatastoreRequestHandler), ('/datastore/edit/(.*)', datastore_viewer.DatastoreEditRequestHandler), ('/datastore/edit', datastore_viewer.DatastoreEditRequestHandler), ('/datastore-indexes', datastore_indexes_viewer.DatastoreIndexesViewer), ('/datastore-stats', datastore_stats_handler.DatastoreStatsHandler), ('/console', console.ConsoleRequestHandler), ('/console/restart/(.+)', console.ConsoleRequestHandler.restart), ('/memcache', memcache_viewer.MemcacheViewerRequestHandler), ('/blobstore', blobstore_viewer.BlobstoreRequestHandler), ('/blobstore/blob/(.+)', blobstore_viewer.BlobRequestHandler), ('/taskqueue', taskqueue_queues_handler.TaskQueueQueuesHandler), ('/taskqueue/queue/(.+)', taskqueue_tasks_handler.TaskQueueTasksHandler), ('/cron', cron_handler.CronHandler), ('/xmpp', xmpp_request_handler.XmppRequestHandler), ('/mail', mail_request_handler.MailRequestHandler), ('/quit', quit_handler.QuitHandler), ('/search', search_handler.SearchIndexesListHandler), ('/search/document', search_handler.SearchDocumentHandler), ('/search/index', search_handler.SearchIndexHandler), ('/assets/(.+)', static_file_handler.StaticFileHandler), ('/instances', modules_handler.ModulesHandler), webapp2.Route('/', webapp2.RedirectHandler, defaults={'_uri': '/instances'})], debug=True) self.dispatcher = dispatch self.configuration = configuration
def _get_redirect_route(self, template=None, name=None): template = template or self.template name = name or self.name defaults = self.defaults.copy() defaults.update({ '_uri': self._redirect, '_name': name, }) new_route = webapp2.Route(template, webapp2.RedirectHandler, defaults=defaults) return new_route
def get_routes( self ): return [ webapp2.Route( '/admin/apps', HandlerApps, name = 'apps' ), webapp2.Route( '/appdatastores', HandlerAppDataStores, name = 'appdatastores' ), webapp2.Route( '/restapi', HandlerPageRestAPI, name = 'restapi' ), webapp2.Route( '/api/v1/connect', HandlerAPIv1Connect, name = 'apiv1connect' ), webapp2.Route( '/api/v1/logout', HandlerAPIv1Logout, name = 'apiv1logout' ), webapp2.Route( '/api/v1/authvalidate', HandlerAPIv1AuthValidate, name = 'apiv1authvalidate' ), webapp2.Route( '/api/v1/ownsproducts', HandlerAPIv1OwnsProducts, name = 'apiv1ownsproducts' ), webapp2.Route( '/api/v1/friends', HandlerAPIv1Friends, name = 'apiv1friends' ), webapp2.Route( '/api/v1/datastore/set', HandlerAPIv1DataStoreSet, name = 'apiv1datastoreset' ), webapp2.Route( '/api/v1/datastore/get', HandlerAPIv1DataStoreGet, name = 'apiv1datastoreget' ), webapp2.Route( '/api/v1/datastore/getlist', HandlerAPIv1DataStoreGetList, name = 'apiv1datastoregetlist' ), webapp2.Route( '/api/v1/datastore/del', HandlerAPIv1DataStoreDel, name = 'apiv1datastoredel' ), ]
def get_routes( cls ): routes = [ webapp2.Route( cls.AUTHREQUEST, handler = 'enki.handlersoauth.HandlerOAuthGoogle:auth_request', methods = [ 'GET' ] ), webapp2.Route( cls.AUTHCALLBACK, handler = 'enki.handlersoauth.HandlerOAuthGoogle:auth_callback', methods = [ 'GET' ] ), ] return routes
def get_routes( cls ): routes = [ webapp2.Route( cls.AUTHREQUEST, handler = 'enki.handlersoauth.HandlerOAuthFacebook:auth_request', methods = [ 'GET' ] ), webapp2.Route( cls.AUTHCALLBACK, handler = 'enki.handlersoauth.HandlerOAuthFacebook:auth_callback', methods = [ 'GET' ] ), ] return routes
def get_routes( cls ): routes = [ webapp2.Route( cls.AUTHREQUEST, handler = 'enki.handlersoauth.HandlerOAuthGithub:auth_request', methods = [ 'GET' ] ), webapp2.Route( cls.AUTHCALLBACK, handler = 'enki.handlersoauth.HandlerOAuthGithub:auth_callback', methods = [ 'GET' ] ), ] return routes
def get_routes( cls ): routes = [ webapp2.Route( cls.AUTHREQUEST, handler = 'enki.handlersoauth.HandlerOAuthSteam:auth_request', methods = [ 'GET' ] ), webapp2.Route( cls.AUTHCALLBACK, handler = 'enki.handlersoauth.HandlerOAuthSteam:auth_callback', methods = [ 'GET' ] ), ] return routes
def get_routes( self ): return [ webapp2.Route( '/forums', HandlerForums, name = 'forums' ), webapp2.Route( '/f/<forum>', HandlerForum, name = 'forum' ), webapp2.Route( '/t/<thread>', HandlerThread, name = 'thread' ), webapp2.Route( '/p/<post>', HandlerPost, name = 'post' ), ]
def get_routes( self ): return [ webapp2.Route( '/store', HandlerStore, name = 'store' ), webapp2.Route( '/generatelicencefastspring', HandlerGenerateLicenceFastSpring, name = 'generatelicencefastspring' ), webapp2.Route( '/ordercompletefastspring', HandlerOrderCompleteFastSpring, name = 'ordercompletefastspring' ), webapp2.Route( '/storeemulatefastspring', HandlerStoreEmulateFastSpring, name = 'storeemulatefastspring' ), webapp2.Route( '/admin/generatelicencefree', HandlerGenerateLicenceFree, name = 'generatelicencefree'), webapp2.Route( '/library', HandlerLibrary, name = 'library' ) ]