• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python models.Location类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中models.Location的典型用法代码示例。如果您正苦于以下问题:Python Location类的具体用法?Python Location怎么用?Python Location使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Location类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:timothyhahn,项目名称:whereatdrexel-backend,代码行数:28,代码来源:views.py


示例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))
开发者ID:e-Luminate,项目名称:eluminate_web,代码行数:35,代码来源:views.py


示例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) 
开发者ID:djtyree,项目名称:adaptPlotter,代码行数:34,代码来源:views.py


示例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")
开发者ID:fresk,项目名称:counties_api,代码行数:29,代码来源:views.py


示例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)
开发者ID:qwertyshan,项目名称:Jedi,代码行数:60,代码来源:main.py


示例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))
开发者ID:garhol,项目名称:clubmates,代码行数:26,代码来源:views.py


示例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
开发者ID:soloture,项目名称:wanderer,代码行数:60,代码来源:bot.py


示例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)
开发者ID:oerb,项目名称:share-tech,代码行数:33,代码来源:views.py


示例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()
开发者ID:vpatel85,项目名称:pullthrough,代码行数:29,代码来源:forms.py


示例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()
开发者ID:Amplifying,项目名称:intensityengine,代码行数:7,代码来源:tests.py


示例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('/')
开发者ID:AlexLoar,项目名称:blablastar,代码行数:9,代码来源:main.py


示例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!"
开发者ID:soloture,项目名称:wanderer,代码行数:10,代码来源:views.py


示例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')
开发者ID:suprit,项目名称:stuff,代码行数:10,代码来源:views.py


示例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()
开发者ID:thebachchaoproject,项目名称:safemaps,代码行数:12,代码来源:db_helper.py


示例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)
开发者ID:jzxyouok,项目名称:DHO,代码行数:51,代码来源:views.py


示例16: admin_api

def admin_api(request):

    if request.POST['method'] == 'add_location':
        try:
            l = Location()
            l.location = request.POST['location']
            l.page = Page.objects.filter(id=request.POST['page']).get()
            l.save()
        except Exception, e:
            print e
        return HttpResponse(json.dumps({
            'location': l.location,
            'id': l.id,
            }))
开发者ID:sbillaudelle,项目名称:holidaylines,代码行数:14,代码来源:views.py


示例17: search

def search():
    if 'query' not in request.args or not request.args['query']:
        return json.dumps({
            'meta': {
                'code': 400,
                'errorType': 'param_error',
                'errorDetail': 'Missing or empty query parameter'
            },
        }), 400

    limit = 10
    if 'limit' in request.args and request.args['limit'] and request.args['limit'].isdigit():
        limit = int(request.args['limit'])

    # Replacing whitespace with .* to offer more flexibility in what schools get
    # returned in the search. ex: If the query is "Belleville High School", we'd
    # still want it to return "Belleville Senior High School" as a result.
    name_regex = request.args['query'];
    name_regex = name_regex.replace(' ', '.*');

    query = {'name':{'$regex': '%s' % name_regex, '$options': 'i'}};

    if 'state' in request.args:
        query['state'] = request.args['state'];

    total_results = Location.objects(__raw__=query).count()
    locations = Location.objects(__raw__=query).limit(limit)
    results = []
    for location in locations:
        results.append(
            {
                'name': location.name,
                'street': location.street,
                'city': location.city,
                'state': location.state,
                'zip': location.zip,
                'lat': location.lat,
                'lon': location.lon,
                'country': location.country,
                'gsid': location.gsid
            }
        )
    return json.dumps({
        'meta': {
            'code': 200,
            'more_results': len(results) < total_results,
            'total_results': total_results
        },
        'results': results
    }), 200
开发者ID:DoSomething,项目名称:lofi-schools-flask,代码行数:50,代码来源:main.py


示例18: render_search

def render_search():
    create_whoosh_dir()
    rest_ix = get_restaurant_index()
    loc_ix = get_location_index()
    cat_ix = get_category_index()

    restSearchableFields = ["name","phonenum"]
    locSearchableFields = ["address","neighborhood", "zipcode"]
    catSearchableFields = ["name"]

    restDataList = []
    locDataList = []
    catDataList = []

    if request.method == 'POST':
        search_query = request.form['search']
        restDataList = search_results(rest_ix, search_query, restSearchableFields)
        locDataList = search_results(loc_ix, search_query, locSearchableFields)
        catDataList = search_results(cat_ix, search_query, catSearchableFields)
        constructRelatedModels(restDataList, locDataList, catDataList)

    return render_template('search_results.html',
        restDataNames=Restaurant.getDataNames() + ["context"],
        restDataList=restDataList,
        locDataNames=Location.getDataNames() + ["context"],
        locDataList=locDataList,
        catDataNames=Category.getDataNames() + ["context"],
        catDataList=catDataList)
开发者ID:brockuniera,项目名称:cs373-idb,代码行数:28,代码来源:app.py


示例19: browse

def browse(request):
    # If a search query was passed in, see if we can find a matching location
    query = request.GET.get('lq', '').strip()
    if query:
        locations = Location.objects.filter(
            site_name__icontains=query,
            accepted=True
        ).values(
            'id',
            'site_name',
        )

        if len(locations) > 0:
            loc = locations[0]
            return redirect(
                'location-view',
                location_id=loc['id'],
                slug=slugify(loc['site_name']),
            )

    fields = Location.get_filter_fields()

    return render(request, 'browse.html', {
        'filters_main': fields[:6],
        'filters_more': fields[6:],
    })
开发者ID:carabader,项目名称:chicago-early-learning,代码行数:26,代码来源:views.py


示例20: index

def index(request):
    fields = Location.get_filter_fields()
    st = ''
    selected = '2'

    if request.POST and 'searchText' in request.POST:
        st = request.POST['searchText']
        selected = request.POST['searchRadius']

    ctx = RequestContext(request, {
        'fields': fields,
        'searchText': st,
        'options': get_opts(selected),
        'mapbarEnabled': True
    })

    response = render_to_response('index.html', context_instance=ctx)

    # cookie for splash screen, defaults to true
    try:
        show_splash = request.COOKIES['show_splash']
        if show_splash == 'true':
            expires = datetime.utcnow() + timedelta(seconds=60 * 60)
            response.set_cookie('show_splash', 'false', expires=expires, httponly=False)
    except:
        response.set_cookie('show_splash', 'true')

    return response
开发者ID:jbranigan,项目名称:chicago-early-learning,代码行数:28,代码来源:views.py



注:本文中的models.Location类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.Log类代码示例发布时间:2022-05-27
下一篇:
Python models.List类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap