本文整理汇总了Python中aiohttp.web.HTTPForbidden方法的典型用法代码示例。如果您正苦于以下问题:Python web.HTTPForbidden方法的具体用法?Python web.HTTPForbidden怎么用?Python web.HTTPForbidden使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类aiohttp.web
的用法示例。
在下文中一共展示了web.HTTPForbidden方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getguild
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def getguild(self, request: web.Request):
guild = int(request.match_info['guild'])
req = f"""SELECT info FROM guilddata WHERE UUID = $1"""
async with self.bot.db._conn.acquire() as connection:
response = await connection.fetchval(req, guild)
if response:
data = json.loads(response)
fdata = data
if request.match_info['tail']:
for item in request.match_info['tail'].split("/"):
if not item:
continue
try:
key = unquote(item)
if isinstance(fdata, list):
key = int(key)
fdata = fdata[key]
except:
raise web.HTTPNotFound()
return web.json_response(fdata)
raise web.HTTPForbidden()
# @server.route("/", methods=["GET"])
示例2: test_403_not_captured
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def test_403_not_captured(sentry_init, aiohttp_client, loop, capture_events):
sentry_init(integrations=[AioHttpIntegration()])
async def hello(request):
raise web.HTTPForbidden()
app = web.Application()
app.router.add_get("/", hello)
events = capture_events()
client = await aiohttp_client(app)
resp = await client.get("/")
assert resp.status == 403
assert not events
示例3: check_permission
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def check_permission(request, permission, context=None):
"""Checks permissions
Custom implementation replacing aiohttp-security one. This one
adds the requested permissions to the request so they can
be presented in the error handler.
Raises:
HTTPForbidden
"""
await check_authorized(request)
allowed = await permits(request, permission, context)
if not allowed:
request['permission_required'] = permission
raise web.HTTPForbidden()
示例4: rotate_public_did_keypair
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def rotate_public_did_keypair(request: web.BaseRequest):
"""
Request handler for rotating key pair associated with public DID.
Args:
request: aiohttp request object
"""
context = request.app["request_context"]
ledger = await context.inject(BaseLedger, required=False)
if not ledger:
reason = "No ledger available"
if not context.settings.get_value("wallet.type"):
reason += ": missing wallet-type?"
raise web.HTTPForbidden(reason=reason)
async with ledger:
try:
await ledger.rotate_public_did_keypair() # do not take seed over the wire
except (WalletError, BadLedgerRequestError) as err:
raise web.HTTPBadRequest(reason=err.roll_up) from err
return web.json_response({})
示例5: actionmenu_perform
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def actionmenu_perform(request: web.BaseRequest):
"""
Request handler for performing a menu action.
Args:
request: aiohttp request object
"""
context = request.app["request_context"]
connection_id = request.match_info["conn_id"]
outbound_handler = request.app["outbound_message_router"]
params = await request.json()
try:
connection = await ConnectionRecord.retrieve_by_id(context, connection_id)
except StorageNotFoundError as err:
raise web.HTTPNotFound(reason=err.roll_up) from err
if connection.is_ready:
msg = Perform(name=params["name"], params=params.get("params"))
await outbound_handler(msg, connection_id=connection_id)
return web.json_response({})
raise web.HTTPForbidden(reason=f"Connection {connection_id} not ready")
示例6: actionmenu_request
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def actionmenu_request(request: web.BaseRequest):
"""
Request handler for requesting a menu from the connection target.
Args:
request: aiohttp request object
"""
context = request.app["request_context"]
connection_id = request.match_info["conn_id"]
outbound_handler = request.app["outbound_message_router"]
try:
connection = await ConnectionRecord.retrieve_by_id(context, connection_id)
except StorageNotFoundError as err:
LOGGER.debug("Connection not found for action menu request: %s", connection_id)
raise web.HTTPNotFound(reason=err.roll_up) from err
if connection.is_ready:
msg = MenuRequest()
await outbound_handler(msg, connection_id=connection_id)
return web.json_response({})
raise web.HTTPForbidden(reason=f"Connection {connection_id} not ready")
示例7: wallet_create_did
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def wallet_create_did(request: web.BaseRequest):
"""
Request handler for creating a new local DID in the wallet.
Args:
request: aiohttp request object
Returns:
The DID info
"""
context = request.app["request_context"]
wallet: BaseWallet = await context.inject(BaseWallet, required=False)
if not wallet:
raise web.HTTPForbidden(reason="No wallet available")
try:
info = await wallet.create_local_did()
except WalletError as err:
raise web.HTTPBadRequest(reason=err.roll_up) from err
return web.json_response({"result": format_did_info(info)})
示例8: test_missing_wallet
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def test_missing_wallet(self):
request = async_mock.MagicMock()
request.app = self.app
self.context.injector.clear_binding(BaseWallet)
with self.assertRaises(HTTPForbidden):
await test_module.wallet_create_did(request)
with self.assertRaises(HTTPForbidden):
await test_module.wallet_did_list(request)
with self.assertRaises(HTTPForbidden):
await test_module.wallet_get_public_did(request)
with self.assertRaises(HTTPForbidden):
await test_module.wallet_set_public_did(request)
with self.assertRaises(HTTPForbidden):
await test_module.wallet_set_did_endpoint(request)
with self.assertRaises(HTTPForbidden):
await test_module.wallet_get_did_endpoint(request)
示例9: test_set_did_endpoint_public_did_no_ledger
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def test_set_did_endpoint_public_did_no_ledger(self):
request = async_mock.MagicMock()
request.app = self.app
request.json = async_mock.CoroutineMock(
return_value={
"did": self.test_did,
"endpoint": "https://my-endpoint.ca:8020",
}
)
self.wallet.get_local_did.return_value = DIDInfo(
self.test_did,
self.test_verkey,
{"public": False, "endpoint": "http://old-endpoint.ca"},
)
self.wallet.get_public_did.return_value = DIDInfo(
self.test_did, self.test_verkey, {}
)
with self.assertRaises(test_module.web.HTTPForbidden):
await test_module.wallet_set_did_endpoint(request)
示例10: check_token
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def check_token(self, request: web.Request) -> Optional['u.User']:
try:
token = request.headers["Authorization"]
token = token[len("Bearer "):]
except KeyError:
raise web.HTTPBadRequest(body='{"error": "Missing Authorization header"}',
headers=self._headers)
except IndexError:
raise web.HTTPBadRequest(body='{"error": "Malformed Authorization header"}',
headers=self._headers)
if self.shared_secret and token == self.shared_secret:
try:
user_id = request.query["user_id"]
except KeyError:
raise web.HTTPBadRequest(body='{"error": "Missing user_id query param"}',
headers=self._headers)
else:
user_id = self.verify_token(token)
if not user_id:
raise web.HTTPForbidden(body='{"error": "Invalid token"}', headers=self._headers)
user = u.User.get_by_mxid(user_id)
return user
示例11: ensure_request_allowed
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def ensure_request_allowed(request, conf):
if is_request_allowed(request, conf):
return
if conf.allowed_origin:
log.warning(
"API requests with Origin '%s' are not allowed, "
"configuration 'allowed_origin' limits requests to: '%s'",
request.headers.get('Origin'), conf.allowed_origin
)
else:
log.warning(
"API requests with Origin '%s' are not allowed, "
"update configuration 'allowed_origin' to enable this origin.",
request.headers.get('Origin')
)
raise web.HTTPForbidden()
示例12: _parse_request_headers
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def _parse_request_headers(request: web.Request):
"""Parse Access-Control-Request-Headers header or the preflight request
Returns set of headers in upper case.
"""
headers = request.headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS)
if headers is None:
return frozenset()
# FIXME: validate each header string, if parsing fails, raise
# HTTPForbidden.
# FIXME: check, that headers split and stripped correctly (according
# to ABNF).
headers = (h.strip(" \t").upper() for h in headers.split(","))
# pylint: disable=bad-builtin
return frozenset(filter(None, headers))
示例13: adapt_cluster
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def adapt_cluster(request):
user = request["user"]
cluster_name = request.match_info["cluster_name"]
backend = request.app["backend"]
cluster = await backend.get_cluster(cluster_name)
if cluster is None:
raise web.HTTPNotFound(reason=f"Cluster {cluster_name} not found")
if not user.has_permissions(cluster):
raise web.HTTPForbidden(
reason=f"User {user.name} lacks permissions to view cluster {cluster_name}"
)
msg = await request.json()
minimum = msg.get("minimum", None)
maximum = msg.get("maximum", None)
active = msg.get("active", True)
try:
await backend.forward_message_to_scheduler(
cluster,
{"op": "adapt", "minimum": minimum, "maximum": maximum, "active": active},
)
except PublicException as exc:
raise web.HTTPConflict(reason=str(exc))
return web.Response()
示例14: user_login
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def user_login(request, email, password, connection=None):
models = request.app.models
user = await models.user.get_user_by_email(email, connection=connection)
if user:
if not user.is_active:
raise web.HTTPForbidden(reason="User disabled")
elif check_password(password, user.password):
await models.user_action_log_entry.create_login(
request, user_id=user.pk, connection=connection)
token = request.app.context.jwt.generate(uid=user.id)
return web.json_response(
{
'uid': user.id,
'profile': await user.get_profile(connection=connection),
'token': token,
}, headers={'Authorization': 'Bearer %s' % token},
)
raise web.HTTPUnauthorized(reason="Login incorrect")
示例15: static_request_handler
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPForbidden [as 别名]
def static_request_handler(cls: Any, obj: Any, context: Dict, func: Any, path: str, base_url: str, ignore_logging: Union[bool, List[int], Tuple[int]] = False) -> Any:
if '?P<filename>' not in base_url:
pattern = r'^{}(?P<filename>.+?)$'.format(re.sub(r'\$$', '', re.sub(r'^\^?(.*)$', r'\1', base_url)))
else:
pattern = r'^{}$'.format(re.sub(r'\$$', '', re.sub(r'^\^?(.*)$', r'\1', base_url)))
compiled_pattern = re.compile(pattern)
if path.startswith('/'):
path = os.path.dirname(path)
else:
path = '{}/{}'.format(os.path.dirname(context.get('context', {}).get('_service_file_path')), path)
if not path.endswith('/'):
path = '{}/'.format(path)
async def handler(request: web.Request) -> web.Response:
result = compiled_pattern.match(request.path)
filename = result.groupdict()['filename'] if result else ''
filepath = '{}{}'.format(path, filename)
try:
if os.path.commonprefix((os.path.realpath(filepath), os.path.realpath(path))) != os.path.realpath(path) or os.path.isdir(filepath) or not os.path.exists(filepath):
raise web.HTTPNotFound() # type: ignore
pathlib.Path(filepath).open('r')
response = FileResponse(path=filepath, # type: ignore
chunk_size=256 * 1024) # type: web.Response
return response
except PermissionError as e:
raise web.HTTPForbidden() # type: ignore
route_context = {'ignore_logging': ignore_logging}
context['_http_routes'] = context.get('_http_routes', [])
context['_http_routes'].append(('GET', pattern, handler, route_context))
start_func = cls.start_server(obj, context)
return (await start_func) if start_func else None