本文整理汇总了Python中pyramid.interfaces.IRequest类的典型用法代码示例。如果您正苦于以下问题:Python IRequest类的具体用法?Python IRequest怎么用?Python IRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了IRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _options
def _options(self, context: IResource, request: IRequest) -> dict:
empty = {} # tiny performance tweak
cstruct = deepcopy(options_resource_response_data_dict)
if request.has_permission('edit_some', context):
edits = self.content.get_sheets_edit(context, request)
put_sheets = [(s.meta.isheet.__identifier__, empty) for s in edits]
if put_sheets:
put_sheets_dict = dict(put_sheets)
self._add_metadata_edit_permission_info(put_sheets_dict)
self._add_workflow_edit_permission_info(put_sheets_dict, edits)
cstruct['PUT']['request_body']['data'] = put_sheets_dict
else:
del cstruct['PUT']
else:
del cstruct['PUT']
if request.has_permission('view', context):
views = self.content.get_sheets_read(context, request)
get_sheets = [(s.meta.isheet.__identifier__, empty) for s in views]
if get_sheets:
cstruct['GET']['response_body']['data'] = dict(get_sheets)
else:
del cstruct['GET']
else:
del cstruct['GET']
if not request.has_permission('delete', context):
del cstruct['DELETE']
is_users = IUsersService.providedBy(context) \
and request.has_permission('create_user', context)
# TODO move the is_user specific part the UsersRestView
if request.has_permission('create', self.context) or is_users:
addables = self.content.get_resources_meta_addable(context,
request)
if addables:
for resource_meta in addables:
iresource = resource_meta.iresource
resource_typ = iresource.__identifier__
creates = self.content.get_sheets_create(context,
request,
iresource)
sheet_typs = [s.meta.isheet.__identifier__ for s
in creates]
sheets_dict = dict.fromkeys(sheet_typs, empty)
post_data = {'content_type': resource_typ,
'data': sheets_dict}
cstruct['POST']['request_body'].append(post_data)
else:
del cstruct['POST']
else:
del cstruct['POST']
return cstruct
示例2: test_subclass_mutate_before_providedBy
def test_subclass_mutate_before_providedBy(self):
from pyramid.interfaces import IRequest
from pyramid.request import Request
from pyramid.util import InstancePropertyHelper
class RequestSub(Request):
pass
req = RequestSub({})
helper = InstancePropertyHelper()
helper.apply_properties(req, {'b': 'b'})
self.assertTrue(IRequest.providedBy(req))
self.assertTrue(IRequest.implementedBy(RequestSub))
示例3: apply_async_web_process
def apply_async_web_process(self, args, kwargs):
"""Schedule a task from web process.
Do not trigger the task until transaction commit. Check that we pass Request to the task as the first argument always. This is an extra complex sanity check.
"""
# Intercept request argumetn going to the function
args_ = kwargs.get("args", [])
kwargs_ = kwargs.get("kwargs", {})
request, args_, kwargs_ = _pop_request_argument(args_, kwargs_)
kwargs["args"] = args_
kwargs["kwargs"] = kwargs_
if not IRequest.providedBy(request):
raise BadAsyncLifeCycleException("You must explicitly pass request as the first argument to asynchronous tasks as these tasks are bound to happen when the database transaction tied to the request lifecycle completes.")
# If for whatever reason we were unable to get a request we'll just
# skip this and call the original method to send this immediately.
if not hasattr(request, "tm"):
return super().apply_async(*args, **kwargs)
# This will break things that expect to get an AsyncResult because
# we're no longer going to be returning an async result from this when
# called from within a request, response cycle. Ideally we shouldn't be
# waiting for responses in a request/response cycle anyways though.
request.tm.get().addAfterCommitHook(
self._after_commit_hook,
args=args,
kws=kwargs,
)
示例4: allows
def allows(self, principals, permission=None):
""" ``principals`` may either be 1) a sequence of principal
indentifiers, 2) a single principal identifier, or 3) a Pyramid
request, which indicates that all the effective principals implied by
the request are used.
``permission`` may be ``None`` if this index is configured with
only a single permission. Otherwise a permission name must be passed
or an error will be raised.
"""
permissions = self.discriminator.permissions
if permission is None:
if len(permissions) > 1:
raise ValueError('Must pass a permission')
else:
permission = list(permissions)[0]
else:
if permissions is not None and not permission in permissions:
raise ValueError(
'This index does not support the %s '
'permission' % (permission,)
)
if IRequest.providedBy(principals):
principals = effective_principals(principals)
elif not is_nonstr_iter(principals):
principals = (principals,)
principals = [ get_principal_repr(p) for p in principals ]
values = [(principal, permission) for principal in principals]
return hypatia.query.Any(self, values)
示例5: _authorize
def _authorize(*args, **kwargs):
login_required = HTTPUnauthorized()
login_required.headers['WWW-Authenticate'] = \
'Basic realm="Manage bridge"'
if IRequest.providedBy(args[0]):
request = args[0]
else:
request = args[0].request
authorization = request.headers.get('Authorization', None)
if not authorization:
raise login_required
_basic, authorization = authorization.split(' ', 1)
username, password = authorization.decode('base64').split(':', 1)
settings = getUtility(ISettings)
admin_user = settings.get('bridge.admin.username', object())
admin_pass = settings.get('bridge.admin.password', object())
if username != admin_user or password != admin_pass:
raise login_required
return fun(*args, **kwargs)
示例6: get_domain
def get_domain(request):
if IRequest.providedBy(request):
referrer = get_referrer(request)
else:
referrer = request
if not referrer:
return ''
return urlsplit(referrer).netloc.split(':')[0]
示例7: _validate_list_schema
def _validate_list_schema(schema: SequenceSchema, cstruct: list,
request: IRequest, location='body'):
if location != 'body': # for now we only support location == body
return
child_cstructs = schema.cstruct_children(cstruct)
try:
request.validated = schema.deserialize(child_cstructs)
except Invalid as err:
_add_colander_invalid_error(err, request, location)
示例8: _get_api_auth_data
def _get_api_auth_data(headers: [tuple], request: IRequest, user: IResource)\
-> dict:
token_headers = dict([(x, y) for x, y in headers if x == UserTokenHeader])
token = token_headers[UserTokenHeader]
user_url = request.resource_url(user)
# TODO: use colander schema to create cstruct
return {'status': 'success',
'user_path': user_url,
'user_token': token,
}
示例9: guess_request
def guess_request(view, *args, **kwargs):
"""Extract request from view arguments.
Pyramid may place request as the first or second argumetn depending if view gets a context argument."""
request = kwargs.get("request")
if request:
return request
first_arg = args[0]
if IRequest.providedBy(first_arg):
return first_arg
if len(args) >= 2:
second_arg = args[1]
if IRequest.providedBy(second_arg):
return second_arg
raise AssertionError("Could not determine request argument for view: {} args: {} kwargs: {}".format(view, args, kwargs))
示例10: __init__
def __init__(self, request: Request, obj: object):
"""
:param obj: The underlying object we wish to wrap for traversing. Usually SQLALchemy model instance.
"""
# Some safety checks we get arguments correctly.n
assert IRequest.providedBy(request)
self.request = request
self.obj = obj
示例11: _extract_json_body
def _extract_json_body(request: IRequest) -> object:
json_body = {}
if request.body == '':
request.body = '{}'
try:
json_body = request.json_body
except (ValueError, TypeError) as err:
error = error_entry('body', None,
'Invalid JSON request body'.format(err))
request.errors.append(error)
return json_body
示例12: query_layout
def query_layout(context, request, name=''):
""" query named layout for context """
assert IRequest.providedBy(request), u"must pass in a request object"
for context in lineage(context):
layout = request.registry.queryMultiAdapter(
(context, request), ILayout, name)
if layout is not None:
return layout
return None
示例13: effective_principals
def effective_principals(self, request: IRequest) -> list:
"""Return userid, roles and groups for the authenticated user.
THE RESULT IS CACHED for the current request in the request attribute
called: __cached_principals__ .
"""
cached_principals = getattr(request, '__cached_principals__', None)
if cached_principals:
return cached_principals
principals = super().effective_principals(request)
request.__cached_principals__ = principals
return principals
示例14: get_choices_by_interface
def get_choices_by_interface(interface: IInterface,
context: IResource,
request: IRequest,
) -> []:
"""Get choices for resource paths by interface."""
catalogs = find_service(context, 'catalogs')
query = search_query._replace(interfaces=interface)
resources = catalogs.search(query).elements
choices = [(request.resource_url(r,
route_name=API_ROUTE_NAME),
resource_path(r)) for r in resources]
return choices
示例15: allows
def allows(self, principals, permission):
""" ``principals`` may either be 1) a sequence of principal
indentifiers, 2) a single principal identifier, or 3) a Pyramid
request, which indicates that all the effective principals implied by
the request are used.
``permission`` must be a permission name.
"""
if IRequest.providedBy(principals):
principals = effective_principals(principals)
elif not is_nonstr_iter(principals):
principals = (principals,)
return AllowsComparator(self, (principals, permission))