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')
python类Route()的实例源码
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 __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 _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' )
]