本文整理汇总了Python中pyramid.interfaces.IRequest类的典型用法代码示例。如果您正苦于以下问题:Python IRequest类的具体用法?Python IRequest怎么用?Python IRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了IRequest类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:Janaba,项目名称:adhocracy3,代码行数:54,代码来源:views.py
示例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))
开发者ID:AlanMachado,项目名称:pyramid,代码行数:14,代码来源:test_request.py
示例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,
)
开发者ID:agronholm,项目名称:websauna,代码行数:30,代码来源:tasks.py
示例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)
开发者ID:Web5design,项目名称:substanced,代码行数:29,代码来源:indexes.py
示例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)
开发者ID:4teamwork,项目名称:ftw.bridge.proxy,代码行数:25,代码来源:utils.py
示例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]
开发者ID:sixfeetup,项目名称:speak_friend,代码行数:8,代码来源:utils.py
示例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)
开发者ID:Janaba,项目名称:adhocracy3,代码行数:9,代码来源:schemas.py
示例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,
}
开发者ID:Janaba,项目名称:adhocracy3,代码行数:10,代码来源:views.py
示例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))
开发者ID:agronholm,项目名称:websauna,代码行数:19,代码来源:csrf.py
示例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
开发者ID:LukeSwart,项目名称:websauna,代码行数:10,代码来源:__init__.py
示例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
开发者ID:Janaba,项目名称:adhocracy3,代码行数:11,代码来源:schemas.py
示例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
开发者ID:WouterVH,项目名称:ptah,代码行数:11,代码来源:layout.py
示例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
开发者ID:Janaba,项目名称:adhocracy3,代码行数:12,代码来源:__init__.py
示例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
开发者ID:liqd,项目名称:adhocracy3,代码行数:12,代码来源:__init__.py
示例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))
开发者ID:Pylons,项目名称:substanced,代码行数:13,代码来源:indexes.py
示例16: test_subclass_with_implementer
def test_subclass_with_implementer(self):
from pyramid.interfaces import IRequest
from pyramid.request import Request
from pyramid.util import InstancePropertyHelper
from zope.interface import implementer
@implementer(IRequest)
class RequestSub(Request):
pass
self.assertTrue(hasattr(Request, '__provides__'))
self.assertTrue(hasattr(Request, '__implemented__'))
self.assertTrue(hasattr(Request, '__providedBy__'))
self.assertTrue(hasattr(RequestSub, '__provides__'))
self.assertTrue(hasattr(RequestSub, '__providedBy__'))
self.assertTrue(hasattr(RequestSub, '__implemented__'))
req = RequestSub({})
helper = InstancePropertyHelper()
helper.apply_properties(req, {'b': 'b'})
self.assertTrue(IRequest.providedBy(req))
self.assertTrue(IRequest.implementedBy(RequestSub))
开发者ID:AlanMachado,项目名称:pyramid,代码行数:23,代码来源:test_request.py
示例17: test_subclass
def test_subclass(self):
from pyramid.interfaces import IRequest
from pyramid.request import Request
class RequestSub(Request):
pass
self.assertTrue(hasattr(Request, '__provides__'))
self.assertTrue(hasattr(Request, '__implemented__'))
self.assertTrue(hasattr(Request, '__providedBy__'))
self.assertFalse(hasattr(RequestSub, '__provides__'))
self.assertTrue(hasattr(RequestSub, '__providedBy__'))
self.assertTrue(hasattr(RequestSub, '__implemented__'))
self.assertTrue(IRequest.implementedBy(RequestSub))
# The call to implementedBy will add __provides__ to the class
self.assertTrue(hasattr(RequestSub, '__provides__'))
开发者ID:AlanMachado,项目名称:pyramid,代码行数:17,代码来源:test_request.py
示例18: query_layout
def query_layout(context, request, name=''):
""" query named layout for context """
assert IRequest.providedBy(request), "must pass in a request object"
try:
iface = request.request_iface
except AttributeError:
iface = IRequest
adapters = request.registry.adapters
for context in lineage(context):
layout_factory = adapters.lookup(
(providedBy(context), iface), ILayout, name=name)
if layout_factory is not None:
return layout_factory, context
return None, None
开发者ID:runyaga,项目名称:ptah,代码行数:19,代码来源:layout.py
示例19: embed_code_config_adapter
def embed_code_config_adapter(context: IResource,
request: IRequest) -> {}:
"""Return mapping to render `adhocracy_core:templates/embed_code.html`."""
settings = request.registry.settings
frontend_url = settings.get('adhocracy.frontend_url',
'http://localhost:6551')
sdk_url = os.path.join(frontend_url, 'AdhocracySDK.js')
path = request.resource_url(context)
locale = settings.get('pyramid.default_locale_name', 'en')
return {'sdk_url': sdk_url,
'frontend_url': frontend_url,
'path': path,
'widget': '',
'autoresize': 'false',
'locale': locale,
'autourl': 'false',
'nocenter': 'true',
'style': 'height: 650px',
}
开发者ID:Janaba,项目名称:adhocracy3,代码行数:19,代码来源:embed.py
示例20: embed_code_config_adapter
def embed_code_config_adapter(context: IResource,
request: IRequest) -> {}:
"""Return mapping to render `adhocracy_core:templates/embed_code.html`."""
settings = request.registry['config']
frontend_url = settings.adhocracy.frontend_url
sdk_url = os.path.join(frontend_url, 'AdhocracySDK.js')
path = request.resource_url(context, route_name=API_ROUTE_NAME)
# TODO use frontend.locale instead
locale = settings.configurator.pyramid.default_locale_name
return {'sdk_url': sdk_url,
'frontend_url': frontend_url,
'path': path,
'widget': '',
'autoresize': 'false',
'locale': locale,
'autourl': 'false',
'initial_url': '',
'nocenter': 'true',
'noheader': 'false',
'style': 'height: 650px',
}
开发者ID:liqd,项目名称:adhocracy3,代码行数:21,代码来源:embed.py
注:本文中的pyramid.interfaces.IRequest类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论