本文整理汇总了Python中pyramid.traversal.find_resource函数的典型用法代码示例。如果您正苦于以下问题:Python find_resource函数的具体用法?Python find_resource怎么用?Python find_resource使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了find_resource函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __call__
def __call__(self, node, value):
root = find_root(self.context)
try:
find_resource(root, value)
except KeyError:
raise colander.Invalid(
node, _("Not an existing valid path."))
示例2: _find_resources
def _find_resources(root,
entry: dict) -> (IUser, IBadge, sheets.badge.IBadgeable):
userpath = entry.get('user')
user = find_resource(root, userpath)
badgepath = entry.get('badge')
badge = find_resource(root, badgepath)
badgeablepath = entry.get('badgeable')
badgeable = find_resource(root, badgeablepath)
return user, badge, badgeable
示例3: linkFrom
def linkFrom(validator, linkFrom, instance, schema):
# avoid circular import
from snovault import Item, TYPES, COLLECTIONS
request = get_current_request()
collections = request.registry[COLLECTIONS]
linkType, linkProp = linkFrom.split('.')
if validator.is_type(instance, "string"):
base = collections[linkType]
try:
item = find_resource(base, instance.replace(':', '%3A'))
if item is None:
raise KeyError()
except KeyError:
error = "%r not found" % instance
yield ValidationError(error)
return
if not isinstance(item, Item):
error = "%r is not a linkable resource" % instance
yield ValidationError(error)
return
if linkType not in set([item.type_info.name] + item.type_info.base_types):
error = "%r is not of type %s" % (instance, repr(linkType))
yield ValidationError(error)
return
pass
else:
path = instance.get('@id')
if validator._serialize:
lv = len(validator._validated)
if '@id' in instance:
del instance['@id']
# treat the link property as not required
# because it will be filled in when the child is created/updated
subschema = request.registry[TYPES][linkType].schema
subschema = copy.deepcopy(subschema)
if linkProp in subschema['required']:
subschema['required'].remove(linkProp)
for error in validator.descend(instance, subschema):
yield error
if validator._serialize:
validated_instance = validator._validated[lv]
del validator._validated[lv:]
if path is not None:
item = find_resource(request.root, path.replace(':', '%3A'))
validated_instance['uuid'] = str(item.uuid)
elif 'uuid' in validated_instance: # where does this come from?
del validated_instance['uuid']
validator._validated[-1] = validated_instance
示例4: _deserialize_location_or_url
def _deserialize_location_or_url(self, node, value):
if value.startswith('/'):
context = node.bindings['context']
return find_resource(context, value)
else:
context = node.bindings['context']
request = node.bindings['request']
application_url_len = len(request.application_url)
if application_url_len > len(str(value)):
raise KeyError
# Fixme: This does not work with :term:`virtual hosting`
path = value[application_url_len:]
return find_resource(context, path)
示例5: isReport
def isReport(self, name):
""" See IMailinDispatcher.
"""
root = find_root(self.context)
if name in root.list_aliases:
return True
pd = find_peopledirectory(self.context)
tokens = name.split('+')
try:
find_resource(pd, tokens)
except KeyError:
return False
return True
示例6: _deserialize_location_or_url
def _deserialize_location_or_url(self, node, value):
if value.startswith('/'):
context = node.bindings['context']
return find_resource(context, value)
else:
context = node.bindings['context']
request = node.bindings['request']
root_url = request.resource_url(request.root,
route_name=API_ROUTE_NAME)
root_url_len = len(root_url)
if root_url_len > len(str(value)):
raise KeyError
path = value[root_url_len:]
return find_resource(context, path)
示例7: should_show_calendar_tab
def should_show_calendar_tab(self):
"""whether to show the calendar tab in the header menu
user must be staff, and the calendar object must exist"""
if self._should_show_calendar_tab is None:
if not self.user_is_staff:
self._should_show_calendar_tab = False
else:
calendar_path = "/offices/calendar"
try:
find_resource(self.site, calendar_path)
self._should_show_calendar_tab = True
except KeyError:
self._should_show_calendar_tab = False
return self._should_show_calendar_tab
示例8: batch_upgrade
def batch_upgrade(request):
request.datastore = 'database'
transaction.get().setExtendedInfo('upgrade', True)
batch = request.json['batch']
root = request.root
storage = request.registry[STORAGE].write
session = storage.DBSession()
results = []
for uuid in batch:
item_type = None
update = False
error = False
sp = session.begin_nested()
try:
item = find_resource(root, uuid)
item_type = item.type_info.item_type
update, errors = update_item(storage, item)
except Exception:
logger.exception('Error updating: /%s/%s', item_type, uuid)
sp.rollback()
error = True
else:
if errors:
errortext = [
'%s: %s' % ('/'.join(error.path) or '<root>', error.message)
for error in errors]
logger.error(
'Validation failure: /%s/%s\n%s', item_type, uuid, '\n'.join(errortext))
sp.rollback()
error = True
else:
sp.commit()
results.append((item_type, uuid, update, error))
return {'results': results}
示例9: get_font
def get_font(self):
try:
font = traversal.find_resource(traversal.find_root(self.get_model()), self.font)
except:
return None
else:
return font
示例10: user_tagged_content
def user_tagged_content(event):
if ITagAddedEvent.providedBy(event):
request = get_current_request()
context = getattr(request, 'context', None)
if context is None:
return
events = find_events(context)
if not events:
return
site = find_site(context)
catalog = find_catalog(context)
path = catalog.document_map.address_for_docid(event.item)
tagged = find_resource(site, path)
if tagged is None:
return
profile_id = event.user
if profile_id in (None, 'None'):
return
profile = site['profiles'][profile_id]
info = _getInfo(profile, tagged)
if info is None:
return
if info['content_type'] == 'Community':
info['flavor'] = 'tagged_community'
elif info['content_type'] == 'Person':
info['flavor'] = 'tagged_profile'
else:
info['flavor'] = 'tagged_other'
info['operation'] = 'tagged'
info['tagname'] = event.name
events.push(**info)
示例11: main
def main():
parser = argparse.ArgumentParser()
parser.add_argument("config_uri", help="Paster ini file to load settings from")
parser.add_argument("path", help="Which path to extract info from")
args = parser.parse_args()
env = bootstrap(args.config_uri)
root = env['root']
request = env['request']
print "Reading poll times from path %r" % args.path
#Just to make sure path exists
find_resource(root, args.path)
query = "path == '%s'" % args.path
query += " and type_name == 'Poll'"
docids = root.catalog.query(query)[1]
for poll in request.resolve_docids(docids, perm=None):
print_voting_timestamps(poll, request)
示例12: _fetch_organisation_by_name
def _fetch_organisation_by_name(root, organisation_path):
organisation = find_resource(root, organisation_path)
if organisation is None:
print('could not find organisation %s' % (organisation))
sys.exit()
else:
return organisation
示例13: main
def main(argv=sys.argv):
def usage(msg):
print msg
sys.exit(2)
description = "Postprocess new recordings as they are made."
usage = "usage: %prog config_uri"
parser = optparse.OptionParser(usage, description=description)
opts, args = parser.parse_args(argv[1:])
try:
config_uri = args[0]
except KeyError:
usage("Requires a config_uri as an argument")
setup_logging(config_uri)
env = bootstrap(config_uri)
root = env["root"]
redis = get_redis(env["request"])
while True:
path = redis.blpop("yss.new-recordings", 0)[1]
time.sleep(1)
transaction.abort()
recording = find_resource(root, path)
try:
postprocess(recording)
except:
redis.rpush("yss.new-recorings", path)
raise
示例14: url_to_resource
def url_to_resource(self, url):
"""
Returns the resource that is addressed by the given URL.
:param str url: URL to convert
:return: member or collection resource
:note: If the query string in the URL has multiple values for a
query parameter, the last definition in the query string wins.
"""
parsed = urlparse.urlparse(url)
parsed_path = parsed.path # namedtupble problem pylint: disable=E1101
rc = find_resource(self.__request.root, traversal_path(parsed_path))
if ICollectionResource in provided_by(rc):
# In case we found a collection, we have to filter, order, slice.
parsed_query = parsed.query # namedtuple problem pylint: disable=E1101
params = dict(parse_qsl(parsed_query))
filter_string = params.get('q')
if not filter_string is None:
rc.filter = \
UrlPartsConverter.make_filter_specification(filter_string)
order_string = params.get('sort')
if not order_string is None:
rc.order = \
UrlPartsConverter.make_order_specification(order_string)
start_string = params.get('start')
size_string = params.get('size')
if not (start_string is None or size_string is None):
rc.slice = \
UrlPartsConverter.make_slice_key(start_string, size_string)
elif not IMemberResource in provided_by(rc):
raise ValueError('Traversal found non-resource object "%s".' % rc)
return rc
示例15: _set_workflow_state
def _set_workflow_state(
root: IResource, registry: Registry, resource_path: str, states: [str], absolute=False, reset=False
):
resource = find_resource(root, resource_path)
states_to_transition = _get_states_to_transition(resource, registry, states, absolute, reset)
transition_to_states(resource, states_to_transition, registry, reset=reset)
transaction.commit()