我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用webapp2.WSGIApplication()。
def test_config(self): app = webapp2.WSGIApplication() req = webapp2.Request.blank('/') req.app = app self.assertRaises(Exception, sessions.SessionStore, req) # Just to set a special config. app = webapp2.WSGIApplication() req = webapp2.Request.blank('/') req.app = app store = sessions.SessionStore(req, config={ 'secret_key': 'my-super-secret', 'cookie_name': 'foo' }) session = store.get_session(factory=self.factory) session['bar'] = 'bar' rsp = webapp2.Response() store.save_sessions(rsp) self.assertTrue(rsp.headers['Set-Cookie'].startswith('foo='))
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_handle_exception_with_error_debug(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=True) 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_render_template_with_i18n(self): app = webapp2.WSGIApplication(config={ 'webapp2_extras.jinja2': { 'template_path': template_path, 'environment_args': { 'autoescape': True, 'extensions': [ 'jinja2.ext.autoescape', 'jinja2.ext.with_', 'jinja2.ext.i18n', ], }, }, }) req = webapp2.Request.blank('/') app.set_globals(app=app, request=req) j = jinja2.Jinja2(app) message = 'Hello, i18n World!' res = j.render_template('template2.html', message=message) self.assertEqual(res, message)
def test_function_that_returns_tuple(self): def myfunction(request, *args, **kwargs): return 'Hello, custom response world!', 404 app = webapp2.WSGIApplication([ ('/', myfunction), ]) def custom_dispatcher(router, request, response): response_tuple = router.default_dispatcher(request, response) return request.app.response_class(*response_tuple) app.router.set_dispatcher(custom_dispatcher) req = webapp2.Request.blank('/') rsp = req.get_response(app) self.assertEqual(rsp.status_int, 404) self.assertEqual(rsp.body, b'Hello, custom response world!')
def test_set_adapter(self): def custom_adapter(router, handler): class MyAdapter(webapp2.BaseHandlerAdapter): def __call__(self, request, response): response.write('hello my adapter') return MyAdapter(handler) def myhandler(request, *args, **kwargs): return webapp2.Response('hello') app = webapp2.WSGIApplication([('/', myhandler)]) app.router.set_adapter(custom_adapter) rsp = app.get_response('/') self.assertEqual(rsp.status_int, 200) self.assertEqual(rsp.body, b'hello my adapter')
def test_validate_password(self): app = webapp2.WSGIApplication() req = webapp2.Request.blank('/') req.app = app s = auth.get_store(app=app) m = models.User success, user = m.create_user(auth_id='auth_id', password_raw='foo') u = s.validate_password('auth_id', 'foo') self.assertEqual(u, s.user_to_dict(user)) self.assertRaises(auth.InvalidPasswordError, s.validate_password, 'auth_id', 'bar') self.assertRaises(auth.InvalidAuthIdError, s.validate_password, 'auth_id_2', 'foo')
def test_extended_user(self): class MyUser(models.User): newsletter = model.BooleanProperty() age = model.IntegerProperty() auth_id = 'own:username' success, info = MyUser.create_user(auth_id, newsletter=True, age=22) self.assertTrue(success) app = webapp2.WSGIApplication(config={ 'webapp2_extras.auth': { 'user_model': MyUser, } }) s = auth.get_store(app=app) user = s.user_model.get_by_auth_id(auth_id) self.assertEqual(info, user) self.assertEqual(user.age, 22) self.assertTrue(user.newsletter is True)
def get_store(factory=I18nStore, key=_store_registry_key, app=None): """Returns an instance of :class:`I18nStore` from the app registry. It'll try to get it from the current app registry, and if it is not registered it'll be instantiated and registered. A second call to this function will return the same instance. :param factory: The callable used to build and register the instance if it is not yet registered. The default is the class :class:`I18nStore` itself. :param key: The key used to store the instance in the registry. A default is used if it is not set. :param app: A :class:`webapp2.WSGIApplication` instance used to store the instance. The active app is used if it is not set. """ app = app or webapp2.get_app() store = app.registry.get(key) if not store: store = app.registry[key] = factory(app) return store
def get_jinja2(factory=Jinja2, key=_registry_key, app=None): """Returns an instance of :class:`Jinja2` from the app registry. It'll try to get it from the current app registry, and if it is not registered it'll be instantiated and registered. A second call to this function will return the same instance. :param factory: The callable used to build and register the instance if it is not yet registered. The default is the class :class:`Jinja2` itself. :param key: The key used to store the instance in the registry. A default is used if it is not set. :param app: A :class:`webapp2.WSGIApplication` instance used to store the instance. The active app is used if it is not set. """ app = app or webapp2.get_app() jinja2 = app.registry.get(key) if not jinja2: jinja2 = app.registry[key] = factory(app) return jinja2
def get_store(factory=AuthStore, key=_store_registry_key, app=None): """Returns an instance of :class:`AuthStore` from the app registry. It'll try to get it from the current app registry, and if it is not registered it'll be instantiated and registered. A second call to this function will return the same instance. :param factory: The callable used to build and register the instance if it is not yet registered. The default is the class :class:`AuthStore` itself. :param key: The key used to store the instance in the registry. A default is used if it is not set. :param app: A :class:`webapp2.WSGIApplication` instance used to store the instance. The active app is used if it is not set. """ app = app or webapp2.get_app() store = app.registry.get(key) if not store: store = app.registry[key] = factory(app) return store
def get_mako(factory=Mako, key=_registry_key, app=None): """Returns an instance of :class:`Mako` from the app registry. It'll try to get it from the current app registry, and if it is not registered it'll be instantiated and registered. A second call to this function will return the same instance. :param factory: The callable used to build and register the instance if it is not yet registered. The default is the class :class:`Mako` itself. :param key: The key used to store the instance in the registry. A default is used if it is not set. :param app: A :class:`webapp2.WSGIApplication` instance used to store the instance. The active app is used if it is not set. """ app = app or webapp2.get_app() mako = app.registry.get(key) if not mako: mako = app.registry[key] = factory(app) return mako
def get_instance(): global _instance if _instance is not None: return _instance from webapp2 import WSGIApplication from argeweb.core import errors from argeweb.core import routing settings, s = get_setting() appstats_settings = s['appstats'] app_config_settings = s['app_config'] debug = True _instance = WSGIApplication( debug=debug, config=app_config_settings) # Custom Error Handlers if debug is False: _instance.error_handlers[400] = errors.handle_400 _instance.error_handlers[401] = errors.handle_401 _instance.error_handlers[403] = errors.handle_403 _instance.error_handlers[404] = errors.handle_404 _instance.error_handlers[500] = errors.handle_500 routing.auto_route(_instance.router, debug, version) return recording.appstats_wsgi_middleware(_instance)
def main(): parser = argparse.ArgumentParser() parser.add_argument('--listen', help='host:port to listen on', default='127.0.0.1:8083') args = parser.parse_args() host, port = args.listen.split(':') app = webapp2.WSGIApplication([ ('/kataster_info_location', KatasterInfoLocation), ('/kataster_info_company', KatasterInfoCompany), ('/kataster_info_person', KatasterInfoPerson), ('/kataster_info_politician', KatasterInfoPolitician), ('/list_politicians', ListPoliticians), ('/info_politician', InfoPolitician), ('/asset_declarations', AssetDeclarations), ], debug=False) httpserver.serve( app, host=host, port=port)
def main(): app = webapp2.WSGIApplication( [ ('/obstaravanie', ServeObstaravanie), ('/obstaravanieFirma', ServeCompany), ('/notifications', ServeNotifications), ('/updateNotifications', UpdateNotifications), ], debug=False) parser = argparse.ArgumentParser() parser.add_argument('--listen', help='host:port to listen on', default='127.0.0.1:8082') args = parser.parse_args() host, port = args.listen.split(':') httpserver.serve( app, host=host, port=port)
def main(): app = webapp2.WSGIApplication([ ('/connection', Connection), ('/shortest', ShortestPath), ('/neighbourhood', Neighbourhood) ], debug=False) parser = argparse.ArgumentParser() parser.add_argument('--listen', help='host:port to listen on', default='127.0.0.1:8081') args = parser.parse_args() host, port = args.listen.split(':') httpserver.serve( app, host=host, port=port)
def __init__(self, app, config=None): """Initializes the i18n store. :param app: A :class:`webapp2.WSGIApplication` instance. :param config: A dictionary of configuration values to be overridden. See the available keys in :data:`default_config`. """ config = app.config.load_config(self.config_key, default_values=default_config, user_values=config, required_keys=None) self.translations = {} self.translations_path = config['translations_path'] self.domains = config['domains'] self.default_locale = config['default_locale'] self.default_timezone = config['default_timezone'] self.date_formats = config['date_formats'] self.set_locale_selector(config['locale_selector']) self.set_timezone_selector(config['timezone_selector'])
def callback_application(self): """WSGI application for handling the OAuth 2.0 redirect callback. If you need finer grained control use `callback_handler` which returns just the webapp.RequestHandler. Returns: A webapp.WSGIApplication that handles the redirect back from the server during the OAuth 2.0 dance. """ return webapp.WSGIApplication([ (self.callback_path, self.callback_handler()) ])
def setUp(self): patch('googleapiclient.discovery.build').start() self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_memcache_stub() app = webapp2.WSGIApplication( [('/createModels', ModelCreatorHandler)] ) self.under_test = webtest.TestApp(app)
def test_set_session_store(self): app = webapp2.WSGIApplication(config={ 'webapp2_extras.sessions': { 'secret_key': 'my-super-secret', } }) req = webapp2.Request.blank('/') req.app = app store = sessions.SessionStore(req) self.assertEqual(len(req.registry), 0) sessions.set_store(store, request=req) self.assertEqual(len(req.registry), 1) s = sessions.get_store(request=req) self.assertTrue(isinstance(s, sessions.SessionStore))
def test_get_session_store(self): app = webapp2.WSGIApplication(config={ 'webapp2_extras.sessions': { 'secret_key': 'my-super-secret', } }) req = webapp2.Request.blank('/') req.app = app self.assertEqual(len(req.registry), 0) s = sessions.get_store(request=req) self.assertEqual(len(req.registry), 1) self.assertTrue(isinstance(s, sessions.SessionStore))
def setUp(self): super(I18nTestCase, self).setUp() app = webapp2.WSGIApplication() request = webapp2.Request.blank('/') request.app = app app.set_globals(app=app, request=request) self.app = app self.request = request # ========================================================================== # _(), gettext(), ngettext(), lazy_gettext(), lazy_ngettext() # ==========================================================================
def test_set_i18n_store(self): app = webapp2.WSGIApplication() req = webapp2.Request.blank('/') req.app = app store = i18n.I18nStore(app) self.assertEqual(len(app.registry), 0) i18n.set_store(store, app=app) self.assertEqual(len(app.registry), 1) s = i18n.get_store(app=app) self.assertTrue(isinstance(s, i18n.I18nStore))
def test_set_i18n(self): app = webapp2.WSGIApplication() req = webapp2.Request.blank('/') req.app = app store = i18n.I18n(req) self.assertEqual(len(app.registry), 1) self.assertEqual(len(req.registry), 0) i18n.set_i18n(store, request=req) self.assertEqual(len(app.registry), 1) self.assertEqual(len(req.registry), 1) i = i18n.get_i18n(request=req) self.assertTrue(isinstance(i, i18n.I18n))
def test_get_i18n(self): app = webapp2.WSGIApplication() req = webapp2.Request.blank('/') req.app = app self.assertEqual(len(app.registry), 0) self.assertEqual(len(req.registry), 0) i = i18n.get_i18n(request=req) self.assertEqual(len(app.registry), 1) self.assertEqual(len(req.registry), 1) self.assertTrue(isinstance(i, i18n.I18n))
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_render_template_force_compiled(self): app = webapp2.WSGIApplication(config={ 'webapp2_extras.jinja2': { 'template_path': template_path, 'compiled_path': compiled_path, 'force_compiled': True, } }) req = webapp2.Request.blank('/') app.set_globals(app=app, request=req) j = jinja2.Jinja2(app) message = 'Hello, World!' res = j.render_template('template1.html', message=message) self.assertEqual(res, message)
def test_get_template_attribute(self): app = webapp2.WSGIApplication(config={ 'webapp2_extras.jinja2': { 'template_path': template_path, } }) j = jinja2.Jinja2(app) hello = j.get_template_attribute('hello.html', 'hello') self.assertEqual(hello('World'), 'Hello, World!')
def test_set_jinja2(self): app = webapp2.WSGIApplication() self.assertEqual(len(app.registry), 0) jinja2.set_jinja2(jinja2.Jinja2(app), app=app) self.assertEqual(len(app.registry), 1) j = jinja2.get_jinja2(app=app) self.assertTrue(isinstance(j, jinja2.Jinja2))
def test_get_jinja2(self): app = webapp2.WSGIApplication() self.assertEqual(len(app.registry), 0) j = jinja2.get_jinja2(app=app) self.assertEqual(len(app.registry), 1) self.assertTrue(isinstance(j, jinja2.Jinja2))
def test_function_that_returns_response(self): def myfunction(request, *args, **kwargs): return webapp2.Response('Hello, custom response world!') app = webapp2.WSGIApplication([ ('/', myfunction), ]) req = webapp2.Request.blank('/') rsp = req.get_response(app) self.assertEqual(rsp.status_int, 200) self.assertEqual(rsp.body, b'Hello, custom response world!')
def test_handle_exception_that_returns_response(self): class HomeHandler(webapp2.RequestHandler): def get(self, **kwargs): raise TypeError() app = webapp2.WSGIApplication([ webapp2.Route('/', HomeHandler, name='home'), ]) app.error_handlers[500] = 'tests.resources.handlers.handle_exception' req = webapp2.Request.blank('/') rsp = req.get_response(app) self.assertEqual(rsp.status_int, 200) self.assertEqual(rsp.body, b'Hello, custom response world!')
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_render_template(self): app = webapp2.WSGIApplication(config={ 'webapp2_extras.mako': { 'template_path': template_path, }, }) req = webapp2.Request.blank('/') app.set_globals(app=app, request=req) m = mako.Mako(app) message = 'Hello, World!' res = m.render_template('template1.html', message=message) self.assertEqual(res, message + '\n')
def test_set_mako(self): app = webapp2.WSGIApplication() self.assertEqual(len(app.registry), 0) mako.set_mako(mako.Mako(app), app=app) self.assertEqual(len(app.registry), 1) j = mako.get_mako(app=app) self.assertTrue(isinstance(j, mako.Mako))
def test_set_auth_store(self): app = webapp2.WSGIApplication() req = webapp2.Request.blank('/') req.app = app store = auth.AuthStore(app) self.assertEqual(len(app.registry), 0) auth.set_store(store, app=app) self.assertEqual(len(app.registry), 1) s = auth.get_store(app=app) self.assertTrue(isinstance(s, auth.AuthStore))
def test_set_auth(self): app = webapp2.WSGIApplication() req = webapp2.Request.blank('/') req.app = app a = auth.Auth(req) self.assertEqual(len(req.registry), 0) auth.set_auth(a, request=req) self.assertEqual(len(req.registry), 1) a = auth.get_auth(request=req) self.assertTrue(isinstance(a, auth.Auth))
def test_get_auth(self): app = webapp2.WSGIApplication() req = webapp2.Request.blank('/') req.app = app self.assertEqual(len(req.registry), 0) a = auth.get_auth(request=req) self.assertEqual(len(req.registry), 1) self.assertTrue(isinstance(a, auth.Auth))
def test_redirect(self): app = webapp2.WSGIApplication() req = webapp2.Request.blank('/') req.app = app app.set_globals(app=app, request=req) rsp = webapp2.redirect('http://www.google.com/', code=301, body='Weee') self.assertEqual(rsp.status_int, 301) self.assertEqual(rsp.body, b'Weee') self.assertEqual(rsp.headers.get('Location'), 'http://www.google.com/')
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 set_store(store, key=_store_registry_key, app=None): """Sets an instance of :class:`I18nStore` in the app registry. :param store: An instance of :class:`I18nStore`. :param key: The key used to retrieve the instance from the registry. A default is used if it is not set. :param request: A :class:`webapp2.WSGIApplication` instance used to retrieve the instance. The active app is used if it is not set. """ app = app or webapp2.get_app() app.registry[key] = store