本文整理汇总了Python中molly.apps.places.get_entity函数的典型用法代码示例。如果您正苦于以下问题:Python get_entity函数的具体用法?Python get_entity怎么用?Python get_entity使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_entity函数的19个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: initial_context
def initial_context(self, request, scheme, value):
context = super(EntityDetailView, self).initial_context(request)
entity = get_entity(scheme, value)
associations = []
if hasattr(self.conf, 'associations'):
for association in self.conf.associations:
id_type, id, associated_entities = association
try:
if id in entity.identifiers[id_type]:
associations += [{'type': type, 'entities': [get_entity(ns, value) for ns, value in es]} for type, es in associated_entities]
except (KeyError, Http404):
pass
for entity_group in entity.groups.all():
group_entities = filter(lambda e: e != entity,
Entity.objects.filter(groups=entity_group))
if len(group_entities) > 0:
associations.append({
'type': entity_group.title,
'entities': group_entities,
})
board = request.GET.get('board', 'departures')
if board != 'departures':
board = 'arrivals'
context.update({
'entity': entity,
'train_station': entity, # This allows the ldb metadata to be portable
'board': board,
'entity_types': entity.all_types.all(),
'associations': associations,
})
return context
开发者ID:chorfa672m,项目名称:mollyproject,代码行数:35,代码来源:views.py
示例2: initial_context
def initial_context(self, request, slug, entities):
context = super(CreateView, self).initial_context(request)
try:
tour_type = self.conf.types[slug]
except KeyError:
raise Http404()
else:
tour_type['slug'] = slug
context.update({
'tour_type': tour_type,
'entities': [],
'attractions': dict(
(et, sorted(et.entities_completion.filter(location__isnull=False),
key=attrgetter('title')))
for et in EntityType.objects.filter(
slug__in=tour_type['attraction_types'])),
'all_pois': sorted(Entity.objects.filter(
all_types_completion__slug__in=tour_type['attraction_types']),
key=attrgetter('title'))
})
for entity in entities.split('/'):
try:
scheme, value = entity.split(':')
except ValueError:
continue
context['entities'].append(get_entity(scheme, value))
return context
开发者ID:ManchesterIO,项目名称:mollyproject,代码行数:31,代码来源:views.py
示例3: _get_entity
def _get_entity(self, stop_code, stop_name, source, entity_type):
"""Finds a bus stop entity or creates one if it cannot be found.
If multiple entities are found we clean them up.
"""
scheme = 'naptan'
try:
entity = get_entity(scheme, stop_code)
except:
try:
entity = Entity.objects.get(_identifiers__scheme=scheme,
_identifiers__value=stop_code)
logger.debug("Found Entity: %s" % entity)
except Entity.DoesNotExist:
logger.debug("Entity does not exist: %s-%s" % (stop_code, stop_name))
entity = Entity()
except Entity.MultipleObjectsReturned:
logger.warning("Multiple Entities found for : %s-%s" % (stop_code, stop_name))
Entity.objects.filter(_identifiers__scheme=scheme,
_identifiers__value=stop_code).delete()
entity = Entity()
entity.primary_type = entity_type
entity.source = source
identifiers = {scheme: stop_code}
set_name_in_language(entity, 'en', title=stop_name)
entity.all_types = (entity_type,)
entity.save(identifiers=identifiers)
return entity
开发者ID:ManchesterIO,项目名称:mollyproject,代码行数:27,代码来源:cloudamber.py
示例4: handle_POST
def handle_POST(self, request, context, scheme, value):
entity = context['entity'] = get_entity(scheme, value)
if entity.source.module_name != 'molly.providers.apps.maps.osm':
raise Http404
form = UpdateOSMForm(request.POST)
if form.is_valid():
new_metadata = copy.deepcopy(entity.metadata['osm'])
for k in ('name', 'operator', 'phone', 'opening_hours', 'url', 'cuisine', 'food', 'food__hours', 'atm', 'collection_times', 'ref', 'capacity'):
tag_name = k.replace('__', ':')
if tag_name in new_metadata and not form.cleaned_data[k]:
del new_metadata['osm']['tags'][tag_name]
elif form.cleaned_data[k]:
new_metadata['tags'][tag_name] = form.cleaned_data[k]
new_metadata['attrs']['version'] = str(int(new_metadata['attrs']['version'])+1)
osm_update = OSMUpdate(
contributor_name = form.cleaned_data['contributor_name'],
contributor_email = form.cleaned_data['contributor_email'],
contributor_attribute = form.cleaned_data['contributor_attribute'],
entity = entity,
old = simplejson.dumps(entity.metadata),
new = simplejson.dumps(new_metadata),
notes = form.cleaned_data['notes'],
)
osm_update.save()
return self.redirect(
reverse('places:entity-update', args=[scheme, value]) + '?submitted=true',
request)
else:
context['form'] = form
return self.render(request, context, 'places/update_osm')
开发者ID:chorfa672m,项目名称:mollyproject,代码行数:34,代码来源:views.py
示例5: initial_context
def initial_context(self, request, scheme, value, year, month, day):
context = super(TimetableView, self).initial_context(request)
context['entity'] = get_entity(scheme, value)
if year and month and day:
try:
context['date'] = date(int(year), int(month), int(day))
except ValueError:
raise Http404()
else:
context['date'] = date.today()
if context['entity'].scheduledstop_set.all().count() == 0:
# 404 on entities which don't have timetables
raise Http404()
services = context['entity'].scheduledstop_set.filter(
journey__runs_from__lte=context['date'],
journey__runs_until__gte=context['date']
).exclude(activity__in=('D','N','F')).order_by('std')
context['timetable'] = filter(lambda s: s.journey.runs_on(context['date']),
services)
context['title'] = _('Timetable for %(title)s on %(date)s') % {
'title': context['entity'].title,
'date': djangodate(context['date'])
}
return context
开发者ID:MechanisM,项目名称:mollyproject,代码行数:32,代码来源:views.py
示例6: breadcrumb
def breadcrumb(self, request, context, scheme, value):
entity = get_entity(scheme, value)
return Breadcrumb(
'places',
lazy_parent('entity', scheme=scheme, value=value),
_('Directions to %s') % context['entity'].title,
lazy_reverse('entity-directions', args=[scheme, value]),
)
开发者ID:MechanisM,项目名称:mollyproject,代码行数:8,代码来源:views.py
示例7: arrival_point_location
def arrival_point_location(self, first_stop, arrival_point):
"""
Given an arrival point (which may be a park and ride, in which case
directions using public transport are given), figure out directions to
the first location
"""
sv, p_and_r, routes = self.conf.arrival_points[int(arrival_point)]
entity = get_entity(*sv.split(':'))
if p_and_r:
# Get closest bus stop to first stop on route
closest_stops = Entity.objects.filter(
stoponroute__route__service_id__in=routes,
).distance(first_stop.location).order_by('distance')
# Now, check that this stop comes *after* where we get on
closest_stop = None
# Go through all of our stops until we find the closest
# one which matches our criteria
for stop in closest_stops:
# Now, check for each route that goes through this
# stop that are the ones we're considering
for route in stop.route_set.filter(service_id__in=routes):
stoponroute = StopOnRoute.objects.get(entity=stop,
route=route)
# Get the closest stop to the origin that serves
# this route
closest_origin = Entity.objects.filter(
stoponroute__route=route,
).distance(entity.location).order_by('distance')[0]
origin_stop = StopOnRoute.objects.get(route=route,
entity=closest_origin)
if stoponroute.order > origin_stop.order:
# now check that this stop comes after our
# first stop...
closest_stop = stop
break
if closest_stop:
break
p_and_r_context = {
'start': entity,
'routes': set(routes) & set(sor.route.service_id for sor in closest_stop.stoponroute_set.all()),
'origin_stop': origin_stop,
'closest_stop': closest_stop
}
start_location = closest_stop
else:
# Directions from that point to first stop
start_location, p_and_r_context = entity, {}
return start_location, p_and_r_context
开发者ID:ManchesterIO,项目名称:mollyproject,代码行数:58,代码来源:views.py
示例8: _scrape
def _scrape(self, route, url, output):
self._output.write(route)
url += '&showall=1'
service = etree.parse(urlopen(url), parser = etree.HTMLParser())
route.stops.clear()
for i, tr in enumerate(service.find('.//table').findall('tr')[1:]):
try:
stop_code = tr[1][0].text
except IndexError:
# Stops on ACIS Live that don't have codes, e.g., out of county
# stops
stop_name = tr[3][0].text
try:
entity = Entity.objects.get(source=self._get_source(),
_identifiers__scheme='acisroute',
_identifiers__value=stop_name)
except Entity.DoesNotExist:
entity = Entity(source=self._get_source())
entity_type = self._get_entity_type()
entity.primary_type = entity_type
identifiers = { 'acisroute': stop_name }
entity.save(identifiers=identifiers)
set_name_in_language(entity, 'en', title=stop_name)
entity.all_types = (entity_type,)
entity.update_all_types_completion()
else:
# TODO: Change identifier lookup based on ACIS region
try:
entity = get_entity('naptan', stop_code)
if entity.source == self._get_source():
# Raise Http404 if this is a bus stop we came up with,
# so any name changes, etc, get processed
raise Http404()
except Http404:
# Out of zone bus stops with NaPTAN codes - alternatively,
# the fake bus stops Oxontime made up for the TUBE route
try:
entity = Entity.objects.get(source=self._get_source(),
_identifiers__scheme='naptan',
_identifiers__value=stop_code)
except Entity.DoesNotExist:
entity = Entity(source=self._get_source())
identifiers = { 'naptan': stop_code }
entity_type = self._get_entity_type()
entity.primary_type = entity_type
entity.save(identifiers=identifiers)
set_name_in_language(entity, 'en', title=tr[3][0].text)
entity.all_types = (entity_type,)
entity.update_all_types_completion()
entity.save()
StopOnRoute.objects.create(route=route, entity=entity, order=i)
开发者ID:SamFoster,项目名称:mollyproject,代码行数:56,代码来源:acislive.py
示例9: get_metadata
def get_metadata(self, request, scheme, value):
entity = get_entity(scheme, value)
user_location = request.session.get('geolocation:location')
distance, bearing = entity.get_distance_and_bearing_from(user_location)
additional = '<strong>%s</strong>' % capfirst(entity.primary_type.verbose_name)
if distance:
additional += ', approximately %.3fkm %s' % (distance/1000, bearing)
return {
'title': entity.title,
'additional': additional,
'entity': entity,
}
开发者ID:bloomonkey,项目名称:mollyproject,代码行数:12,代码来源:views.py
示例10: breadcrumb
def breadcrumb(self, request, context, scheme, value):
if request.session.get("geolocation:location"):
parent_view = "nearby-detail"
else:
parent_view = "category-detail"
entity = get_entity(scheme, value)
return Breadcrumb(
"places",
lazy_parent(parent_view, ptypes=entity.primary_type.slug),
context["entity"].title,
lazy_reverse("entity", args=[scheme, value]),
)
开发者ID:SamFoster,项目名称:mollyproject,代码行数:12,代码来源:views.py
示例11: get_entity
def get_entity(self):
"""
Gets the entity for this library. This look up is done using the
identifier namespace defined in the config. Returns None if no
identifier can be found.
"""
if hasattr(app_by_local_name('library'), 'library_identifier'):
library_identifier = app_by_local_name('library').library_identifier
try:
return get_entity(library_identifier, '/'.join(self.location))
except (Http404, Entity.MultipleObjectsReturned):
return None
else:
return None
开发者ID:ManchesterIO,项目名称:mollyproject,代码行数:14,代码来源:models.py
示例12: initial_context
def initial_context(self, request, scheme, value):
context = super(EntityDetailView, self).initial_context(request)
entity = get_entity(scheme, value)
associations = []
if hasattr(self.conf, "associations"):
for association in self.conf.associations:
id_type, id, associated_entities = association
try:
if id in entity.identifiers[id_type]:
associations += [
{"type": type, "entities": [get_entity(ns, value) for ns, value in es]}
for type, es in associated_entities
]
except (KeyError, Http404):
pass
for entity_group in entity.groups.all():
group_entities = filter(lambda e: e != entity, Entity.objects.filter(groups=entity_group))
if len(group_entities) > 0:
associations.append({"type": entity_group.title, "entities": group_entities})
board = request.GET.get("board", "departures")
if board != "departures":
board = "arrivals"
context.update(
{
"entity": entity,
"train_station": entity, # This allows the ldb metadata to be portable
"board": board,
"entity_types": entity.all_types.all(),
"associations": associations,
}
)
return context
开发者ID:SamFoster,项目名称:mollyproject,代码行数:36,代码来源:views.py
示例13: get_metadata
def get_metadata(self, request, scheme, value):
entity = get_entity(scheme, value)
user_location = request.session.get("geolocation:location")
distance, bearing = entity.get_distance_and_bearing_from(user_location)
additional = "<strong>%s</strong>" % capfirst(entity.primary_type.verbose_name)
if distance:
additional += ", " + _("about %(distance)dm %(bearing)s") % {
"distance": int(math.ceil(distance / 10) * 10),
"bearing": bearing,
}
routes = sorted(set(sor.route.service_id for sor in entity.stoponroute_set.all()))
if routes:
additional += ", " + ungettext(
"service %(services)s stops here", "services %(services)s stop here", len(routes)
) % {"services": " ".join(routes)}
return {"title": entity.title, "additional": additional, "entity": entity}
开发者ID:SamFoster,项目名称:mollyproject,代码行数:16,代码来源:views.py
示例14: handle_POST
def handle_POST(self, request, context, scheme, value):
entity = context["entity"] = get_entity(scheme, value)
if entity.source.module_name != "molly.providers.apps.maps.osm":
raise Http404
form = UpdateOSMForm(request.POST)
if form.is_valid():
new_metadata = copy.deepcopy(entity.metadata["osm"])
for k in (
"name",
"operator",
"phone",
"opening_hours",
"url",
"cuisine",
"food",
"food__hours",
"atm",
"collection_times",
"ref",
"capacity",
):
tag_name = k.replace("__", ":")
if tag_name in new_metadata and not form.cleaned_data[k]:
del new_metadata["osm"]["tags"][tag_name]
elif form.cleaned_data[k]:
new_metadata["tags"][tag_name] = form.cleaned_data[k]
new_metadata["attrs"]["version"] = str(int(new_metadata["attrs"]["version"]) + 1)
osm_update = OSMUpdate(
contributor_name=form.cleaned_data["contributor_name"],
contributor_email=form.cleaned_data["contributor_email"],
contributor_attribute=form.cleaned_data["contributor_attribute"],
entity=entity,
old=simplejson.dumps(entity.metadata),
new=simplejson.dumps(new_metadata),
notes=form.cleaned_data["notes"],
)
osm_update.save()
return self.redirect(reverse("places:entity-update", args=[scheme, value]) + "?submitted=true", request)
else:
context["form"] = form
return self.render(request, context, "places/update_osm")
开发者ID:SamFoster,项目名称:mollyproject,代码行数:45,代码来源:views.py
示例15: get_metadata
def get_metadata(self, request, scheme, value):
entity = get_entity(scheme, value)
user_location = request.session.get('geolocation:location')
distance, bearing = entity.get_distance_and_bearing_from(user_location)
additional = '<strong>%s</strong>' % capfirst(entity.primary_type.verbose_name)
if distance:
additional += ', ' + _('about %(distance)dm %(bearing)s') % {
'distance': int(math.ceil(distance/10)*10),
'bearing': bearing }
routes = sorted(set(sor.route.service_id for sor in entity.stoponroute_set.all()))
if routes:
additional += ', ' + ungettext('service %(services)s stops here',
'services %(services)s stop here',
len(routes)) % {
'services': ' '.join(routes)
}
return {
'title': entity.title,
'additional': additional,
'entity': entity,
}
开发者ID:chorfa672m,项目名称:mollyproject,代码行数:21,代码来源:views.py
示例16: get_entity_filter
def get_entity_filter(value):
return get_entity(*value)
开发者ID:bloomonkey,项目名称:mollyproject,代码行数:2,代码来源:molly_utils.py
示例17: handle_GET
def handle_GET(self, request, context, scheme, value, ptype):
entity = get_entity(scheme, value)
return super(NearbyEntityDetailView, self).handle_GET(request, context, ptype, entity)
开发者ID:chorfa672m,项目名称:mollyproject,代码行数:3,代码来源:views.py
示例18: endElement
def endElement(self, name):
if name in ('node','way') and self.valid:
try:
types = self.find_types(self.tags)
except ValueError:
self.ignore_count += 1
return
# Ignore ways that lay partly outside our bounding box
if name == 'way' and not all(id in self.node_locations for id in self.nodes):
return
# Ignore disused and under-construction entities
if self.tags.get('life_cycle', 'in_use') != 'in_use' or self.tags.get('disused') in ('1', 'yes', 'true'):
return
# Memory management in debug mode
reset_queries()
if self.id in self.identities:
entity = get_entity(*self.identities[self.id].split(':'))
entity.metadata['osm'] = {
'attrs': dict(self.attrs),
'tags': dict(zip((k.replace(':', '_') for k in self.tags.keys()), self.tags.values()))
}
identifiers = entity.identifiers
identifiers.update({
'osm': self.id
})
entity.save(identifiers=identifiers)
entity.all_types = set(entity.all_types.all()) | set(self.entity_types[et] for et in types)
entity.update_all_types_completion()
self.ids.remove(self.id)
else:
try:
entity = Entity.objects.get(source=self.source,
_identifiers__scheme='osm',
_identifiers__value=self.id)
created = False
except Entity.DoesNotExist:
entity = Entity(source=self.source)
created = True
if not 'osm' in entity.metadata or \
entity.metadata['osm'].get('attrs', {}).get('timestamp', '') < self.attrs['timestamp']:
if created:
self.create_count += 1
else:
self.modify_count += 1
if name == 'node':
entity.location = Point(self.node_location, srid=4326)
entity.geometry = entity.location
elif name == 'way':
cls = LinearRing if self.nodes[0] == self.nodes[-1] else LineString
entity.geometry = cls([self.node_locations[n] for n in self.nodes], srid=4326)
min_, max_ = (float('inf'), float('inf')), (float('-inf'), float('-inf'))
for lon, lat in [self.node_locations[n] for n in self.nodes]:
min_ = min(min_[0], lon), min(min_[1], lat)
max_ = max(max_[0], lon), max(max_[1], lat)
entity.location = Point( (min_[0]+max_[0])/2 , (min_[1]+max_[1])/2 , srid=4326)
else:
raise AssertionError("There should be no other types of entity we're to deal with.")
names = dict()
for lang_code, lang_name in settings.LANGUAGES:
with override(lang_code):
if '-' in lang_code:
tags_to_try = ('name:%s' % lang_code, 'name:%s' % lang_code.split('-')[0], 'name', 'operator')
else:
tags_to_try = ('name:%s' % lang_code, 'name', 'operator')
name = None
for tag_to_try in tags_to_try:
if self.tags.get(tag_to_try):
name = self.tags.get(tag_to_try)
break
if name is None:
try:
name = reverse_geocode(*entity.location)[0]['name']
if not name:
raise IndexError
name = u"↝ %s" % name
except IndexError:
name = u"↝ %f, %f" % (self.node_location[1], self.node_location[0])
names[lang_code] = name
entity.metadata['osm'] = {
'attrs': dict(self.attrs),
'tags': dict(zip((k.replace(':', '_') for k in self.tags.keys()), self.tags.values()))
}
entity.primary_type = self.entity_types[types[0]]
#.........这里部分代码省略.........
开发者ID:RCGTDev,项目名称:mollyproject,代码行数:101,代码来源:osm.py
示例19: _scrape
def _scrape(self, route, url, output):
url += '&showall=1'
service = etree.parse(urlopen(url), parser = etree.HTMLParser())
route.stops.clear()
for i, tr in enumerate(service.find('.//table').findall('tr')[1:]):
try:
stop_code = tr[1][0].text
except IndexError:
# Stops on ACIS Live that don't have codes, e.g., out of county
# stops
stop_name = tr[3][0].text
try:
entity = Entity.objects.get(source=self._get_source(),
_identifiers__scheme='acisroute',
_identifiers__value=stop_name)
except Entity.DoesNotExist:
entity = Entity(source=self._get_source())
entity_type = self._get_entity_type()
entity.primary_type = entity_type
identifiers = { 'acisroute': stop_name }
entity.save(identifiers=identifiers)
set_name_in_language(entity, 'en', title=stop_name)
entity.all_types = (entity_type,)
entity.update_all_types_completion()
else:
if stop_code.startswith('693') or stop_code.startswith('272') \
or stop_code.startswith('734') or stop_code.startswith('282'):
# Oxontime uses NaPTAN code
scheme = 'naptan'
elif stop_code.startswith('450'):
# West Yorkshire uses plate code
scheme = 'plate'
else:
# Everyone else uses ATCO
scheme = 'atco'
if stop_code.startswith('370'):
# Except South Yorkshire, which mangles the code
stop_code = '3700%s' % stop_code[3:]
try:
entity = get_entity(scheme, stop_code)
if entity.source == self._get_source():
# Raise Http404 if this is a bus stop we came up with,
# so any name changes, etc, get processed
raise Http404()
except Http404:
# Out of zone bus stops with NaPTAN codes - alternatively,
# the fake bus stops Oxontime made up for the TUBE route
try:
entity = Entity.objects.get(source=self._get_source(),
_identifiers__scheme=scheme,
_identifiers__value=stop_code)
except Entity.DoesNotExist:
entity = Entity(source=self._get_source())
identifiers = {scheme: stop_code}
entity_type = self._get_entity_type()
entity.primary_type = entity_type
entity.save(identifiers=identifiers)
set_name_in_language(entity, 'en', title=tr[3][0].text)
entity.all_types = (entity_type,)
entity.update_all_types_completion()
entity.save()
StopOnRoute.objects.create(route=route, entity=entity, order=i)
开发者ID:puntofisso,项目名称:mollyproject,代码行数:67,代码来源:acislive.py
注:本文中的molly.apps.places.get_entity函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论