本文整理汇总了Python中pyramid.traversal.traverse函数的典型用法代码示例。如果您正苦于以下问题:Python traverse函数的具体用法?Python traverse怎么用?Python traverse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了traverse函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: paths_filtered_by_status
def paths_filtered_by_status(request, paths, exclude=('deleted', 'replaced'), include=None):
if include is not None:
return [
path for path in paths
if traverse(request.root, path)['context'].__json__(request).get('status') in include
]
else:
return [
path for path in paths
if traverse(request.root, path)['context'].__json__(request).get('status') not in exclude
]
开发者ID:ENCODE-DCC,项目名称:snovault,代码行数:11,代码来源:base.py
示例2: paths_filtered_by_status
def paths_filtered_by_status(request, paths, exclude=("deleted", "replaced"), include=None):
if include is not None:
return [
path for path in paths if traverse(request.root, path)["context"].__json__(request).get("status") in include
]
else:
return [
path
for path in paths
if traverse(request.root, path)["context"].__json__(request).get("status") not in exclude
]
开发者ID:philiptzou,项目名称:clincoded,代码行数:11,代码来源:base.py
示例3: fill_slot
def fill_slot(self, index, value):
"""
Fill the `index`th slot of the URL with `value`
"""
fragments = list(reversed(list(lineage(self))))
fillers = self.slot_fillers
assert index < len(fillers)
# Index into the path for filling the `index`th slot and a function
# which fills it
to_fill = self.ordering[index]
filler_index, filler_function = fillers[to_fill]
# Get the (as yet incomplete) resource with the slot filled
filled_traverser = filler_function(fragments[filler_index], value)
assert filled_traverser
# Get the path which needs to be appended to this traverser
remaining_fragments = [f.__name__ for f in fragments[filler_index + 1:]]
remaining_fragments = transpose_fragments_fixup(remaining_fragments, to_fill)
# Traverse any remaining parts of the path, if they exist
remaining_path = "/".join(remaining_fragments)
if remaining_path:
filled_traverser = traverse(filled_traverser, remaining_path)["context"]
return filled_traverser
开发者ID:ableeb,项目名称:WebOOT,代码行数:28,代码来源:multitraverser.py
示例4: main
def main():
parser = OptionParser(description=__doc__)
parser.add_option('-s', '--source', dest='source',
action="store", default='/', metavar='ZODB-PATH',
help="The ZODB source path to dump (e.g. /foo/bar or /)")
parser.add_option('-d', '--dest', dest='dest',
action="store", default='dump', metavar='FILESYSTEM-PATH',
help="The destination filesystem path to dump to.")
options, args = parser.parse_args()
if args:
config_uri = args[0]
else:
parser.error("Requires a config_uri as an argument")
source = options.source
dest = os.path.expanduser(os.path.normpath(options.dest))
setup_logging(config_uri)
env = bootstrap(config_uri)
root = env['root']
source = traverse(root, source)['context']
dump(source, dest)
开发者ID:dhavlik,项目名称:substanced,代码行数:26,代码来源:dump.py
示例5: _get_user_home_path
def _get_user_home_path(context, request):
"""If currently authenticated user has a 'home_path' set, create a response
redirecting user to that path. Otherwise return None.
"""
userid = authenticated_userid(request)
if userid is None:
return None, None
site = find_site(context)
profiles = find_profiles(site)
profile = profiles.get(userid, None)
if profile is None:
return None, None
home_path = getattr(profile, 'home_path', None)
if home_path:
# OSI sets this to a single space to mean None
home_path = home_path.strip()
if not home_path:
return None, None
tdict = traverse(site, home_path)
target = tdict['context']
view_name = tdict['view_name']
subpath = list(tdict['subpath'])
if view_name:
subpath.insert(0, view_name)
return target, subpath
开发者ID:araymund,项目名称:karl,代码行数:30,代码来源:utils.py
示例6: main
def main():
parser = argparse.ArgumentParser()
parser.add_argument("config_uri", help="Paster ini file to load settings from")
parser.add_argument("path", help="from which path to clear likes (meeting or agenda item)")
args = parser.parse_args()
env = bootstrap(args.config_uri)
root = env['root']
request = env['request']
context = traverse(root, args.path).get('context')
if IMeeting.providedBy(context) or IAgendaItem.providedBy(context):
print('Clearing likes on {}'.format(context.title))
path_query = query.Eq('path', args.path)
cleared = False
for type_name in ('Proposal', 'DiscussionPost'):
count, docids = root.catalog.query(path_query & query.Eq('type_name', type_name))
response = input('Found {} {} on {}. Do you want to clear likes on these? (y/N) '.format(
count, type_name, context.title).encode('utf8'))
if response.lower() in ('y', 'yes', 'j', 'ja'):
cleared = True
for obj in request.resolve_docids(docids, perm=None):
like = request.registry.getAdapter(obj, IUserTags, name='like')
like.storage.clear()
like._notify()
if cleared:
transaction.commit()
env['closer']()
else:
print('Path does not match a meeting or agenda item')
开发者ID:VoteIT,项目名称:mp_buildout,代码行数:32,代码来源:clear_likes.py
示例7: get_filtered_rev_links
def get_filtered_rev_links(self, request, name):
"""
Run get_rev_links, but only return items that do not have a status
in self.filtered_rev_statuses (a tuple defined on the Item)
If we are indexing, add rev_link info to _rev_linked_uuids_by_item.
Args:
request: current Request
name (str): name of the rev (must be in self.rev)
Returns:
list of str uuids of the given rev_link, filtered by status
"""
# Consider caching rev links on the request? Would save DB requests
# May not be worth it because they are quite fast
rev_uuids = self.get_rev_links(request, name)
filtered_uuids = [
str(rev_id) for rev_id in rev_uuids
if traverse(request.root, str(rev_id))['context'].__json__(request).get('status')
not in self.filtered_rev_statuses
]
if getattr(request, '_indexing_view', False) is True:
to_update = {name: filtered_uuids}
if str(self.uuid) in request._rev_linked_uuids_by_item:
request._rev_linked_uuids_by_item[str(self.uuid)].update(to_update)
else:
request._rev_linked_uuids_by_item[str(self.uuid)] = to_update
return filtered_uuids
开发者ID:j1z0,项目名称:snovault,代码行数:28,代码来源:resources.py
示例8: analysis_step_version
def analysis_step_version(self, request, root, step_run=None):
if step_run is None:
return
step_run_obj = traverse(root, step_run)['context']
step_version_uuid = step_run_obj.__json__(request).get('analysis_step_version')
if step_version_uuid is not None:
return request.resource_path(root[step_version_uuid])
开发者ID:kidaa,项目名称:encoded,代码行数:7,代码来源:file.py
示例9: __getitem__
def __getitem__(self, key):
if not isinstance(key, int) and not key.isdigit():
return
if not isinstance(key, int) and "*" in key:
things = self.items
raise
# Pattern
pattern = re.compile(fnmatch.translate(subpath))
contexts = [(f, traverse(self, f)["context"])
for f in listdir(self.path) if pattern.match(f)]
return MultipleTraverser.from_parent(self, subpath, contexts)
b = self.basket[int(key)]
return traverse(HomeResource(self.request), b['path'])["context"]
开发者ID:pwaller,项目名称:WebOOT,代码行数:16,代码来源:baskets.py
示例10: paths_filtered_by_status
def paths_filtered_by_status(request, paths, exclude=('deleted', 'replaced'), include=None):
"""
This function has been deprecated in Fourfront, but is still used by
access_keys calc property in types/user.py (only for snowflakes)
filter out status that shouldn't be visible.
Also convert path to str as functions like rev_links return uuids
"""
if include is not None:
return [
path for path in paths
if traverse(request.root, str(path))['context'].__json__(request).get('status') in include
]
else:
return [
path for path in paths
if traverse(request.root, str(path))['context'].__json__(request).get('status') not in exclude
]
开发者ID:j1z0,项目名称:snovault,代码行数:17,代码来源:base.py
示例11: pipeline
def pipeline(self, root, request, step_run=None):
if step_run is None:
return
workflow_uuid = traverse(root, step_run)['context'].__json__(request).get('workflow_run')
if workflow_uuid is None:
return
pipeline_uuid = root[workflow_uuid].__json__(request).get('pipeline')
if pipeline_uuid is None:
return
return request.resource_path(root[pipeline_uuid])
开发者ID:jclong,项目名称:encoded,代码行数:10,代码来源:file.py
示例12: test_resource_form_traversal
def test_resource_form_traversal():
result = traverse(_root, "/rest/schools/%s/@view" % SCHOOL_ID)
context = result['context']
request = DummyRequest(params={})
request.context = context
from webapp.views.rest import json_rest_get_f
result = json_rest_get_f(context, request)
assert(result['id'] == SCHOOL_ID)
开发者ID:sergeyv,项目名称:webapp,代码行数:10,代码来源:test_traversal.py
示例13: traverse
def traverse(self, path):
if path.startswith('/'):
context = self.root
path = path[1:]
else:
context = self
result = traverse(context, path)
if result['view_name']:
raise KeyError(result['view_name'])
return result['context']
开发者ID:encukou,项目名称:ptcg-editor,代码行数:10,代码来源:__init__.py
示例14: test_traversal__path_type_view_name
def test_traversal__path_type_view_name(path, resource_type, view_name):
"""
Ensure that traversing the ``path`` results in a resource of type
``resource_type`` with view name ``view_name``.
"""
from pyramid.traversal import traverse
root_resource = root_resource_factory()
t = traverse(root_resource, path)
assert isinstance(t['context'], resource_type)
assert t['view_name'] == view_name
开发者ID:cdunklau,项目名称:paildocket,代码行数:10,代码来源:test_traversal.py
示例15: test_traversal__path_resource_attribute
def test_traversal__path_resource_attribute(path, attribute_name, value):
"""
Ensure that traversing the ``path`` results in a resource having
the attribute ``attribute_name`` set to ``value``.
"""
from pyramid.traversal import traverse
root_resource = root_resource_factory()
t = traverse(root_resource, path)
context = t['context']
assert getattr(context, attribute_name) == value
开发者ID:cdunklau,项目名称:paildocket,代码行数:11,代码来源:test_traversal.py
示例16: resolve_uri
def resolve_uri(self, uri, exact=False):
url = urlparse(uri)
url_loc = url.netloc
if not url.port:
url_loc += ':80'
if url_loc != self.req.host:
raise ValueError('Alien URL supplied.')
path = url.path.strip('/').split('/')[1:]
path = [unquote(n) for n in path]
tr = traverse(self, path)
if exact and (tr['view_name'] or (len(tr['subpath']) > 0)):
raise ValueError('Object not found.')
return tr
开发者ID:baloon11,项目名称:npui,代码行数:13,代码来源:nodes.py
示例17: get_paths
def get_paths(self):
paths = set()
root = self.registry['root']
request = _make_request('/', registry=self.registry)
if root:
excludes = self.siteconfig['site'].get('excludes', '').split('\n')
excludes.extend([
'.*',
'/config.py*',
'/site.cfg',
'/%s' % self.siteconfig['site']['outpath']])
relpaths = dirtools.Dir(
root.abspath,
excludes=excludes).files()
for relpath in relpaths:
traverse(root, relpath)
if root:
paths.add('/%s' % relpath)
visited_routes = set()
info = self.registry.queryUtility(IStaticURLInfo)
if info:
for (url, spec, route_name) in info._get_registrations(self.registry):
visited_routes.add(route_name)
path = abspath_from_resource_spec(spec)
relpaths = dirtools.Dir(path).files()
for relpath in relpaths:
paths.add(
request.route_path(route_name, subpath=relpath))
routelist = self.site.config.config.get_routes_mapper().routelist
for route in routelist:
if route.factory is not None:
matches = route.factory.matches(self.registry)
paths = paths.union(route.generate(x) for x in matches)
elif route.name not in visited_routes:
paths.add(route.generate({}))
visited_routes.add(route.name)
return list(sorted(paths))
开发者ID:fschulze,项目名称:stasis,代码行数:37,代码来源:core.py
示例18: main
def main():
parser = OptionParser(description=__doc__)
parser.add_option('-d', '--dry-run', dest='dry_run',
action="store_true", default=False,
help="Don't commit the transactions")
parser.add_option('-i', '--interval', dest='commit_interval',
action="store", default=200,
help="Commit every N transactions")
parser.add_option('-p', '--path', dest='path',
action="store", default=None, metavar='EXPR',
help="Reindex only objects whose path matches a regular expression")
parser.add_option('-n', '--index', dest='indexes',
action="append", help="Reindex only the given index (can be repeated)")
parser.add_option('-s', '--site', dest='site',
action="store", default=None, metavar='PATH')
options, args = parser.parse_args()
if args:
config_uri = args[0]
else:
parser.error("Requires a config_uri as an argument")
commit_interval = int(options.commit_interval)
if options.path:
path_re = re.compile(options.path)
else:
path_re = None
kw = {}
if options.indexes:
kw['indexes'] = options.indexes
setup_logging(config_uri)
env = bootstrap(config_uri)
site = env['root']
if options.site:
site = traverse(site, options.site)
catalog = find_service(site, 'catalog')
if catalog is None:
raise KeyError('No catalog service found at ' % resource_path(site))
catalog.reindex(path_re=path_re, commit_interval=commit_interval,
dry_run=options.dry_run, **kw)
开发者ID:dextermilo,项目名称:substanced,代码行数:46,代码来源:reindex.py
示例19: biological_replicates
def biological_replicates(self, request, registry, root, replicate=None):
if replicate is not None:
replicate_obj = traverse(root, replicate)['context']
replicate_biorep = replicate_obj.__json__(request)['biological_replicate_number']
return [replicate_biorep]
conn = registry[CONNECTION]
derived_from_closure = property_closure(request, 'derived_from', self.uuid)
dataset_uuid = self.__json__(request)['dataset']
obj_props = (conn.get_by_uuid(uuid).__json__(request) for uuid in derived_from_closure)
replicates = {
props['replicate']
for props in obj_props
if props['dataset'] == dataset_uuid and 'replicate' in props
}
bioreps = {
conn.get_by_uuid(uuid).__json__(request)['biological_replicate_number']
for uuid in replicates
}
return sorted(bioreps)
开发者ID:kidaa,项目名称:encoded,代码行数:20,代码来源:file.py
示例20: __getitem__
def __getitem__(self, key):
if self.selection:
if "*" in key:
keys = sorted([k.GetName() for k in self.rootfile.GetListOfKeys()
if k.GetClassName() == self.selection])
pattern = re.compile(fnmatch.translate(key))
contexts = [(f, traverse(self, f)["context"])
for f in keys if pattern.match(f)]
return MultipleTraverser.from_parent(self, key, contexts)
try:
(k for k in self.keys
if k.GetName() == key and
k.GetClassName() == self.selection
).next()
except StopIteration:
return
else:
return super(SelectClass, self).__getitem__(key)
else:
return self.from_parent(self, key, self.rootfile, key)
开发者ID:JohannesEbke,项目名称:WebOOT,代码行数:20,代码来源:file.py
注:本文中的pyramid.traversal.traverse函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论