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='))
python类WSGIApplication()的实例源码
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 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 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 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 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))