本文整理汇总了Python中models.Location类的典型用法代码示例。如果您正苦于以下问题:Python Location类的具体用法?Python Location怎么用?Python Location使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Location类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: admin_home
def admin_home():
locform = LocationForm()
if locform.validate_on_submit() :
ids = request.form.getlist('id')
name = request.form.getlist('name')
longitude = request.form.getlist('longitude')
latitude = request.form.getlist('latitude')
type = request.form.getlist('types')
for (i, id) in enumerate(ids) :
if id.isdigit() :
loc = Location.query.get(id)
loc.longitude = longitude[i]
loc.latitude = latitude[i]
loc.name = name[i]
loc.type = type[i].lower()
db.session.commit()
else :
if longitude[i] and latitude[i] and name[i] :
loc = Location(float(longitude[i]), float(latitude[i]), name[i], 'N/A', 'N/A')
loc.type = type[i].lower()
db.session.add(loc)
db.session.commit()
locations = Location.query.all()
type_list = list()
for type in location_type._asdict().values():
type_list.append(type.capitalize())
return render_template('admin.html', locations=locations, location_types=type_list, form=locform, username=current_user.username)
示例2: add
def add(request, form_class=AddLocationForm, template='maps/add_location.html'):
center_obj = DEFAULT_CENTER_OBJ
if request.method == 'POST': # If the form has been submitted...
form = form_class(request.user, request.POST)
if form.is_valid():
location = form.save(commit=False)
location.user = request.user
location.save()
msg = _("%(name)s has been saved.") %{'name': location.name}
messages.add_message(request, messages.SUCCESS, msg)
if request.session.has_key('next'):
redirect_url = request.session.get('next')
return HttpResponseRedirect(redirect_url)
return HttpResponseRedirect(reverse('locations_list'))
else:
# We re-pass the default location if the form is not valid
location = Location()
location.marker = Point(DEFAULT_CENTER_OBJ['x'], DEFAULT_CENTER_OBJ['y'])
else:
# A dynamically loaded form
location = Location()
location.marker = Point(DEFAULT_CENTER_OBJ['x'], DEFAULT_CENTER_OBJ['y'])
form = form_class(initial={'user' : request.user,
'marker' : location.marker})
if request.GET.has_key('next'):
request.session['next'] = request.GET['next']
return render_to_response(template,
{ "form": form,
"location": location,
},
context_instance=RequestContext(request))
示例3: addEditObstacle
def addEditObstacle(oid):
obstacle = None
form = ObstacleForm()
if oid is not None:
obstacle = Obstacle.query.get(oid) # @UndefinedVariable
if request.method == 'GET':
if obstacle is None:
form.new.data = True
else:
form.new.data = False
form.id.data = obstacle.id
form.location.lat.data = obstacle.location.lat
form.location.lon.data = obstacle.location.lon
if request.method == 'POST' and form.validate(): # @UndefinedVariable
if obstacle is None:
#new obstacle has passed validation, add to db
location = Location(lat=form.location.lat.data, lon=form.location.lon.data)
db.session.add(location) # @UndefinedVariable
obstacle= Obstacle(location=location)
db.session.add(obstacle) # @UndefinedVariable
db.session.commit() # @UndefinedVariable
flash("Obstacle has been created")
else:
#node has been updated. save updates
location = Location.query.get(obstacle.loc_id) # @UndefinedVariable
location.lat = form.location.lat.data
location.lon = form.location.lon.data
db.session.commit() # @UndefinedVariable
flash("Obstacle has been updated")
# after creating the new state, redirect them back to dce config page
return redirect(url_for("obstaclePage"))
return render_template("obstacleForm.html", form=form)
示例4: location_list
def location_list(request):
if request.method == 'GET':
return get_location_list()
if request.method == 'POST':
if not request.user.is_authenticated(request):
return HttpResponse('Unauthorized', status=401)
data = json.loads(request.body)
l = None
if not data.get('id'):
l = Location(user=request.user, data=json.dumps(data), name=data['name'])
l.save()
data["id"] = l.id
l.data = json.dumps(data)
l.save()
else:
l = Location.objects.get(pk=int(data['id']))
if (request.user.is_staff == False):
if (l.user.pk != request.user.pk):
return HttpResponse(json.dumps({'error': 'not authorized'}), content_type="application/json")
l.data = json.dumps(data)
l.name = data['name']
l.save()
return HttpResponse(json.dumps(l.data), content_type="application/json")
return HttpResponse(json.dumps({'error': 'must be get or post request'}), content_type="application/json")
示例5: post
def post(self):
messageid = self.request.get("messageid")
if messageid == "":
rawCharacter = cgi.escape(self.request.get("character"), quote = True)
rawLocation = cgi.escape(self.request.get("address"), quote = True)
# Validate character
(character, charError) = map.validateCharacter(rawCharacter)
# Validate location
location = map.validateLocation(rawLocation)
error, msgError = "", ""
# Check validation errors and format error message
if character == None:
msgChar = rawCharacter
else:
msgChar = str(character.name)
if charError != "":
error = charError
msgError = error
if location.status != "OK":
error = (error + " " + location.status.encode('utf_8')).decode('utf_8')
msgError = error
if (charError == "") and (location.status == "OK"):
error = ("Move %s to %s. Got it!" % (msgChar, location.address.encode('utf_8'))).decode('utf_8')
msgError = ""
print datetime.datetime.utcnow()
print "error: " + error.encode('utf_8')
print type(error)
print "msgError: " + msgError.encode('utf_8')
print type(msgError)
# Store in Message store
if recordMessage("WebForm", None, self.request.remote_addr, msgChar, location, rawCharacter+" "+rawLocation, msgError):
print "IN APP:"
top_msgs(True)
self.writeHTML(error=error, character=character, location=location)
else:
error = "App Error: Failed to insert message."
self.writeHTML(error=error, character=character, location=location)
else:
# Validate messageid and get message
messagekey = ndb.Key(urlsafe=messageid)
message = Message()
message = messagekey.get()
character = Character.query(Character.name == message.character).get()
location = Location()
location.address = message.address
location.latlng = message.latlng
# If message found
if not message:
error = "App Error: Cannot get message."
self.writeHTML(error=error, character=None, location=None)
# If message not found
else:
# Write
self.writeHTML(error="", character=character, location=location)
示例6: add_location
def add_location(request, loc):
context = {}
my_location = Location.objects.get(id=loc)
context['curr_location'] = my_location
context['parent'] = my_location.parent
context['lat'] = my_location.latitude
context['lon'] = my_location.longitude
context['zoom'] = my_location.density
if request.method == 'POST': # If the form has been submitted...
form = LocationForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
name = form.cleaned_data['name']
latitude = form.cleaned_data['latitude']
longitude = form.cleaned_data['longitude']
density = form.cleaned_data['density']
venue = form.cleaned_data['venue']
parent = form.cleaned_data['parent']
l = Location(name=name, parent=parent, latitude=latitude, longitude=longitude, density=density, venue=venue)
l.save()
return HttpResponseRedirect('/') # Redirect after POST
else:
context['form'] = LocationForm(initial={'parent':my_location.id}) # An unbound form
return render_to_response('www/place/add.html', context, context_instance=RequestContext(request))
示例7: take_suggestions
def take_suggestions():
if os.path.exists(LATESTFILE_SUG):
fp = open(LATESTFILE_SUG)
lastid = fp.read().strip()
fp.close()
if lastid == '':
lastid = 0
else:
lastid = 0
result = api.GetMentions(since_id = lastid)
#No mention, no suggestion
print lastid
if len(result) == 0:
print "No mention received"
return []
else :
fp = open(LATESTFILE_SUG, 'w')
fp.write(str(max([x.id for x in result])))
fp.close()
entry = History.query.descending('mongo_id').first()
for x in result:
print x.text
#Somebody already suggested..
if entry.next_location.name != entry.suggested_location.name :
print "There already is a suggestion. Fitz is currently headed to "+entry.next_location.name
return []
else :
candidates = {}
#Walk through all the mentions we got here..
for x in result :
mention_entry = x.text.split(' ')
s_user = x.user.screen_name
#Locations have to be proposed in a form of "Check out ***"
if mention_entry[1] == 'Check' and mention_entry[2] == 'out':
s_key = s_user + ":" + ' '.join(mention_entry[3:])
s_geo = geocoder(' '.join(mention_entry[3:]))
distance = gcd(entry.next_location.geocode[0], entry.next_location.geocode[1], s_geo[1], s_geo[2])
candidates[s_key] = distance
#Got somethin' but no useful words
if len(candidates) == 0:
print "Got some words, but no suggestions.."
return []
#Got somewhere to go!
else :
next_move = min(candidates, key=candidates.get)
print candidates[candidates.keys()[0]] > candidates[candidates.keys()[1]]
print next_move
l = Location()
l.name = next_move.split(':')[1]
l.geocode = geocoder(next_move.split(':')[1])[1:]
entry.suggested_location = l
entry.suggested_by = next_move.split(':')[0]
entry.save()
user_sug = []
user_sug.append(next_move.split(':')[0])
user_sug.append(next_move.split(':')[1])
return user_sug
示例8: new_location
def new_location(request):
"""
New Location
"""
data = {}
template = 'itembase/simpleform.djhtml'
data['message'] = None
data['headstring'] = 'New Location'
if request.method == "POST":
form = LocationForm(request.POST)
if form.is_valid():
location = Location(lc_name=form.cleaned_data['lc_name'],
lc_geo=form.cleaned_data['lc_geo'],
lc_adr=form.cleaned_data['lc_adr'],
lc_city=form.cleaned_data['lc_city'],
lc_www=form.cleaned_data['lc_www'],
lc_mail=form.cleaned_data['lc_mail'],
lc_info=form.cleaned_data['lc_info'],
)
location.save()
print(location)
membership = Membership(me_user = request.user,
me_location = location,
me_trust1 = request.user,
me_trust2 = request.user,
)
membership.save()
print membership
return redirect('itembase/home')
return redirect('itembase/home')
else:
data['form'] = LocationForm()
return render(request, template, data)
示例9: save
def save(self, eventperson):
eventperson.attended = self.cleaned_data['attended']
try:
person = eventperson.person
except Person.DoesNotExist:
person, created = Person.objects.get_or_create(
first_name = self.cleaned_data['first_name'],
last_name = self.cleaned_data['last_name'],
email = self.cleaned_data['email'],
)
for a in self.people_attrs:
setattr(person,a,self.cleaned_data[a])
if any([self.cleaned_data.get(a,None) for a in self.address_attrs]):
address = person.address
if not address:
address = Location()
for a in self.address_attrs:
setattr(address,a,self.cleaned_data[a])
address.save()
person.address = address
person.save()
eventperson.person = person
eventperson.save()
示例10: test01_setup
def test01_setup(self):
"Setting up for related model tests."
for name, state, lon, lat in cities:
loc = Location(point=Point(lon, lat))
loc.save()
c = City(name=name, state=state, location=loc)
c.save()
示例11: post
def post(self):
""" Create a new location (or override existing) """
try:
Location.save_from_request(self.request)
except Exception as e:
self.error(403)
self.response.out.write(e)
return
self.redirect('/')
示例12: suggest
def suggest():
entry = History.query.descending('mongo_id').first()
suggested_point = app.config['SUGGESTED_POINT']
geocode = geocoder(suggested_point)
location = Location()
location.name = geocode[0]
location.geocode = (geocode[1],geocode[2])
entry.suggested_location = location
entry.save()
return suggested_point + " suggested!"
示例13: home
def home(request):
# create a location for no particular reason
if Location.objects.count() == 0:
loc = Location(name="Microsoft NERD Center",
street="1 Memorial Drive",
city="Cambridge",
state="MA",
country="US")
loc.save()
return render_to_response('home.html')
示例14: add_location
def add_location(name, latitude, longitude):
"""
@summary: Add the location to the database
@param name : Location name
@type name: str
@param latitude: latitude of the location as float
@type latitude: float
@param longitude: longitude of the location as float
@type longitude: float
"""
loc = Location(name=name,latitude=latitude, longitude=longitude)
loc.save()
示例15: post
def post(self, request):
try:
wechat.parse_data(request.body)
except ParseError:
return HttpResponse('Invalid Body Text')
id = wechat.message.id # MsgId
target = wechat.message.target # ToUserName
source = wechat.message.source # FromUserName
time = wechat.message.time # CreateTime
type = wechat.message.type # MsgType
raw = wechat.message.raw # 原始 XML 文本
# get_or_create会得到一个tuple (object, created)
fowler = Fowler.objects.get_or_create(OpenID=source)[0]
if isinstance(wechat.message, TextMessage):
keywords = [func.keyword for func in Function.objects.all()]
content = wechat.message.content # 对应于 XML 中的 Content
if content in keywords:
reply = Function.objects.get(keyword=content).explain
else:
reply = '本公众号支持的回复有: \n' + ' '.join(keywords)
dialog = Dialog(message=content, reply=reply, fowler=fowler)
dialog.save()
response_xml = wechat.response_text(content=reply, escape=True)
return HttpResponse(response_xml)
elif isinstance(wechat.message, LocationMessage):
location = wechat.message.location # Tuple(Location_X, Location_Y)
scale = wechat.message.scale # 地图缩放大小
label = wechat.message.label # 地理位置
loc = Location(fowler=fowler, x=location[0], y=location[1], label=label)
loc.save()
response_xml = wechat.response_text(content='已收到您的地理位置')
return HttpResponse(response_xml)
elif isinstance(wechat.message, EventMessage):
if wechat.message.type == 'subscribe':
fowler.activate = 1
fowler.save()
response_xml = wechat.response_text(content='欢迎关注本公众号 具体功能请回复‘功能’')
return HttpResponse(response_xml)
elif wechat.message.type == 'unsubscribe':
fowler.activate = 0
fowler.save()
else:
response_xml = wechat.response_text(content="回复'功能'了解本公众号提供的查询功能")
return HttpResponse(response_xml)