本文整理汇总了Python中aiohttp.web.HTTPInternalServerError方法的典型用法代码示例。如果您正苦于以下问题:Python web.HTTPInternalServerError方法的具体用法?Python web.HTTPInternalServerError怎么用?Python web.HTTPInternalServerError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类aiohttp.web
的用法示例。
在下文中一共展示了web.HTTPInternalServerError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: restart
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPInternalServerError [as 别名]
def restart(request: web.Request) -> web.Response:
registry = request.app['registry']
session_name = request.match_info['session_name']
requester_access_key, owner_access_key = await get_access_key_scopes(request)
log.info('RESTART (ak:{0}/{1}, s:{2})',
requester_access_key, owner_access_key, session_name)
try:
await registry.increment_session_usage(session_name, owner_access_key)
await registry.restart_session(session_name, owner_access_key)
except BackendError:
log.exception('RESTART: exception')
raise
except:
await request.app['error_monitor'].capture_exception(user=request['user']['uuid'])
log.exception('RESTART: unexpected error')
raise web.HTTPInternalServerError
return web.Response(status=204)
示例2: test_render_not_initialized
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPInternalServerError [as 别名]
def test_render_not_initialized():
async def func(request):
return aiohttp_jinja2.render_template('template', request, {})
app = web.Application()
app.router.add_route('GET', '/', func)
req = make_mocked_request('GET', '/', app=app)
msg = "Template engine is not initialized, " \
"call aiohttp_jinja2.setup(..., app_key={}" \
") first".format(aiohttp_jinja2.APP_KEY)
with pytest.raises(web.HTTPInternalServerError) as ctx:
await func(req)
assert msg == ctx.value.text
示例3: test_template_not_found
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPInternalServerError [as 别名]
def test_template_not_found():
async def func(request):
return aiohttp_jinja2.render_template('template', request, {})
app = web.Application()
aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({}))
app.router.add_route('GET', '/', func)
req = make_mocked_request('GET', '/', app=app)
with pytest.raises(web.HTTPInternalServerError) as ctx:
await func(req)
t = "Template 'template' not found"
assert t == ctx.value.text
assert t == ctx.value.reason
示例4: test_render_not_mapping
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPInternalServerError [as 别名]
def test_render_not_mapping():
@aiohttp_jinja2.template('tmpl.jinja2')
async def func(request):
return 123
app = web.Application()
aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
{'tmpl.jinja2': 'tmpl'}))
app.router.add_route('GET', '/', func)
req = make_mocked_request('GET', '/', app=app)
msg = "context should be mapping, not <class 'int'>"
with pytest.raises(web.HTTPInternalServerError) as ctx:
await func(req)
assert msg == ctx.value.text
示例5: test_fail_transport
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPInternalServerError [as 别名]
def test_fail_transport(make_route, make_request):
request = make_request(
"GET",
"/sm/",
match_info={"transport": "test", "session": "session", "server": "000"},
)
params = []
class Transport:
def __init__(self, manager, session, request):
params.append((manager, session, request))
def process(self):
raise Exception("Error")
route = make_route(handlers={"test": (True, Transport)})
res = await route.handler(request)
assert isinstance(res, web.HTTPInternalServerError)
示例6: test_release_session_for_failed_transport
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPInternalServerError [as 别名]
def test_release_session_for_failed_transport(make_route, make_request):
request = make_request(
"GET",
"/sm/",
match_info={"transport": "test", "session": "s1", "server": "000"},
)
class Transport:
def __init__(self, manager, session, request):
self.manager = manager
self.session = session
async def process(self):
await self.manager.acquire(self.session)
raise Exception("Error")
route = make_route(handlers={"test": (True, Transport)})
res = await route.handler(request)
assert isinstance(res, web.HTTPInternalServerError)
s1 = route.manager["s1"]
assert not route.manager.is_acquired(s1)
示例7: test_render_not_initialized
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPInternalServerError [as 别名]
def test_render_not_initialized():
async def func(request):
return aiohttp_mako.render_template('template', request, {})
app = web.Application()
app.router.add_route('GET', '/', func)
req = make_mocked_request('GET', '/', app=app)
with pytest.raises(web.HTTPInternalServerError) as ctx:
await func(req)
assert "Template engine is not initialized, " \
"call aiohttp_mako.setup(app_key={}) first" \
"".format(aiohttp_mako.APP_KEY) == ctx.value.text
示例8: test_template_not_mapping
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPInternalServerError [as 别名]
def test_template_not_mapping():
@aiohttp_mako.template('tmpl.html')
async def func(request):
return 'data'
app = web.Application()
lookup = aiohttp_mako.setup(app, input_encoding='utf-8',
output_encoding='utf-8',
default_filters=['decode.utf8'])
tplt = "<html><body><h1>${head}</h1>${text}</body></html>"
lookup.put_string('tmpl.html', tplt)
app.router.add_route('GET', '/', func)
req = make_mocked_request('GET', '/', app=app)
with pytest.raises(web.HTTPInternalServerError) as ctx:
await func(req)
assert "context should be mapping, not" \
" <class 'str'>" == ctx.value.text
示例9: remember
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPInternalServerError [as 别名]
def remember(request, response, identity, **kwargs):
"""Remember identity into response.
The action is performed by identity_policy.remember()
Usually the identity is stored in user cookies somehow but may be
pushed into custom header also.
"""
assert isinstance(identity, str), identity
assert identity
identity_policy = request.config_dict.get(IDENTITY_KEY)
if identity_policy is None:
text = ("Security subsystem is not initialized, "
"call aiohttp_security.setup(...) first")
# in order to see meaningful exception message both: on console
# output and rendered page we add same message to *reason* and
# *text* arguments.
raise web.HTTPInternalServerError(reason=text, text=text)
await identity_policy.remember(request, response, identity, **kwargs)
示例10: spans_handler
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPInternalServerError [as 别名]
def spans_handler(self, request: web.Request) -> web.Response:
if len(self.next_errors) > 0:
err = self.next_errors.pop(0)
if err == 'disconnect':
request.transport.close()
await asyncio.sleep(1, loop=self._loop)
elif err == 'timeout':
await asyncio.sleep(60, loop=self._loop)
return web.HTTPInternalServerError()
data = await request.json()
if self._wait_count is not None:
self._wait_count -= 1
self._received_data.append(data)
if self._wait_fut is not None and self._wait_count == 0:
self._wait_fut.set_result(None)
return aiohttp.web.Response(text='', status=200)
示例11: get_aiohttp_response
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPInternalServerError [as 别名]
def get_aiohttp_response(self, context: Dict, default_charset: Optional[str] = None, default_content_type: Optional[str] = None) -> web.Response:
if self.missing_content_type:
self.charset = default_charset
self.content_type = default_content_type
charset = self.charset
if hdrs.CONTENT_TYPE in self._headers and ';' in self._headers[hdrs.CONTENT_TYPE]:
try:
charset = str([v for v in self._headers[hdrs.CONTENT_TYPE].split(';') if 'charset=' in v][0]).replace('charset=', '').strip()
except IndexError:
pass
elif hdrs.CONTENT_TYPE in self._headers and ';' not in self._headers[hdrs.CONTENT_TYPE]:
charset = None
if self._body and not isinstance(self._body, bytes) and charset:
body = self._body
try:
body_value = body.encode(charset.lower())
except (ValueError, LookupError, UnicodeEncodeError) as e:
logging.getLogger('exception').exception('Uncaught exception: {}'.format(str(e)))
raise web.HTTPInternalServerError() from e # type: ignore
elif self._body:
body_value = self._body.encode() if not isinstance(self._body, bytes) else self._body
else:
body_value = b''
response = web.Response(body=body_value, # type: ignore
status=self._status,
reason=self._reason,
headers=self._headers,
content_type=self.content_type,
charset=self.charset) # type: web.Response
return response
示例12: performance
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPInternalServerError [as 别名]
def performance(request: web.Request) -> web.Response:
# Emulate bad performance on certain input type
# This endpoint is for Schemathesis targeted testing, the failure should be discovered
decoded = await request.json()
number = str(decoded).count("0")
if number > 0:
await asyncio.sleep(0.01 * number)
if number > 10:
raise web.HTTPInternalServerError
return web.json_response({"slow": True})
示例13: flaky
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPInternalServerError [as 别名]
def flaky(request: web.Request) -> web.Response:
config = request.app["config"]
if config["should_fail"]:
config["should_fail"] = False
raise web.HTTPInternalServerError
return web.json_response({"result": "flaky!"})
示例14: multiple_failures
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPInternalServerError [as 别名]
def multiple_failures(request: web.Request) -> web.Response:
id_value = int(request.query["id"])
if id_value == 0:
raise web.HTTPInternalServerError
if id_value > 0:
raise web.HTTPGatewayTimeout
return web.json_response({"result": "OK"})
示例15: render_string
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPInternalServerError [as 别名]
def render_string(
template_name: str,
request: web.Request,
context: Dict[str, Any],
*,
app_key: str = APP_KEY
) -> str:
env = request.config_dict.get(app_key)
if env is None:
text = ("Template engine is not initialized, "
"call aiohttp_jinja2.setup(..., app_key={}) first"
"".format(app_key))
# in order to see meaningful exception message both: on console
# output and rendered page we add same message to *reason* and
# *text* arguments.
raise web.HTTPInternalServerError(reason=text, text=text)
try:
template = env.get_template(template_name)
except jinja2.TemplateNotFound as e:
text = "Template '{}' not found".format(template_name)
raise web.HTTPInternalServerError(reason=text, text=text) from e
if not isinstance(context, Mapping):
text = "context should be mapping, not {}".format(type(context))
# same reason as above
raise web.HTTPInternalServerError(reason=text, text=text)
if request.get(REQUEST_CONTEXT_KEY):
context = dict(request[REQUEST_CONTEXT_KEY], **context)
text = template.render(context)
return text