本文整理汇总了Python中molly.apps.places.get_entity函数的典型用法代码示例。如果您正苦于以下问题:Python get_entity函数的具体用法?Python get_entity怎么用?Python get_entity使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_entity函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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
示例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')
示例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
示例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]),
)
示例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
示例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)
示例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,
}
示例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]),
)
示例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
示例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
示例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}
示例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")
示例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,
}