Python geocoding name 'latitude' is not defined - python

I'm a new in django. I want to
bulid a webapp to search map by address.(Geocoding) This is my view.py, I want to response to my html file to show the map for the input address. My code shows it has name error at/map/. I dont know the reason. Thanks for kindly reply.
from django.shortcuts import render
import urllib
from urllib.request import urlopen
import json
def searchMap(request):
if request.method == "POST":
global latitude
global longitude
city_name = request.POST.get('address')
city_name_Url="https://maps.googleapis.com/maps/api/geocode/json?
address"+city_name
city_name_Url_Quote=urllib.parse.quote(city_name_Url,':?=/')
response=urlopen(city_name_Url_Quote).read().decode('utf-8')
response_json = json.loads(response)
latitude = response_json.get('results')[0]['geometry']['location']['lat']
longitude = api_response_dict('results')[0]['geometry']['location']['lng']
return render(request,'WebPage1.html',{'Latitude':latitude,'Longitude':longitude})
The error message:
NameError at /map/
name 'latitude' is not defined Request Method: GET
Request URL: http://127.0.0.1:8000/map/ Django Version: 1.8.13
Exception Type: NameError Exception Value: name 'latitude' is not
defined Exception
Location: C:\Users\alienware\Desktop\DjangoWebProject12\DjangoWebProject12\HelloWorld\views.py
in searchMap, line 26 Python
Executable: C:\Users\alienware\Desktop\DjangoWebProject12\DjangoWebProject12\env_DjangoWebProject2\Scripts\python.exe
Python Version: 3.6.3 Python Path:
['C:\Users\Desktop\DjangoWebProject12\DjangoWebProject12',
'C:\Users\Desktop\DjangoWebProject12\DjangoWebProject12',
'C:\Users\Desktop\DjangoWebProject12\DjangoWebProject12\env_DjangoWebProject2\Scripts\python36.zip',
'C:\Users\AppData\Local\Programs\Python\Python36\DLLs',
'C:\Users\AppData\Local\Programs\Python\Python36\lib',
'C:\Users\AppData\Local\Programs\Python\Python36',
'C:\Users\Desktop\DjangoWebProject12\DjangoWebProject12\env_DjangoWebProject2',
'C:\Users\Desktop\DjangoWebProject12\DjangoWebProject12\env_DjangoWebProject2\lib\site-packages']
Server time: Mon, 5 Feb 2018 21:57:22 +0800

I assume (from the error traceback) that your real code looks like this:
def searchMap(request):
if request.method == "POST":
# XXX totally unrelated but : __NEVER__ use mutable globals
# in a django app.
global latitude
global longitude
city_name = request.POST.get('address')
city_name_Url="https://maps.googleapis.com/maps/api/geocode/json?
address"+city_name
city_name_Url_Quote=urllib.parse.quote(city_name_Url,':?=/')
response=urlopen(city_name_Url_Quote).read().decode('utf-8')
response_json = json.loads(response)
latitude = response_json.get('results')[0]['geometry']['location']['lat']
longitude = api_response_dict('results')[0]['geometry']['location']['lng']
return render(request,'WebPage1.html',{'Latitude':latitude,'Longitude':longitude})
Now ask yourself what happens when the request's method is not POST... Yes, everything in the if block is ignored, and only the last statement (return render(...)) is executed. At this point, neither latitude nor longitude have been defined, hence your error.
The first thing to fix is the use of a POST request for a search. POST is used to update the server's state. A search does not change the server's state (at least it should not, and your's doesn't indeed) so the correct verb here is GET. As an added bonus, it will make your search result page bookmarkable.
So first change your template code to use GET as value for your form's method attribute. Then in your view, don't test on the request method at all and look for querystring args in request.GET. Also, you'll want to handle the case where the user didn't actually send anything:
def searchMap(request):
context = {}
city_name = request.GET.get('address', '').strip()
if city_name:
# hint: use the `python-requests` module instead,
# it will make you life much easier
city_name_Url="https://maps.googleapis.com/maps/api/geocode/json?
address"+city_name
city_name_Url_Quote=urllib.parse.quote(city_name_Url,':?=/')
response=urlopen(city_name_Url_Quote).read().decode('utf-8')
response_json = json.loads(response)
context["Latitude"] = response_json.get('results')[0]['geometry']['location']['lat']
context["Longitude"] = api_response_dict('results')[0]['geometry']['location']['lng']
else:
# here you want to display an error message to
# the user - don't forget to check the case
# in your template. Note that it would be simpler
# using a Django Form...
context["error"] = "Some errorr message here"
return render(request,'WebPage1.html',context)

Related

How can I access Json attribute and check if (key)exist in payload or not using python

This is my UI
End user can able to update Summary or my_story one at a time, This is my endpoint URL http:localhost:3000/api/account/profile, once user update any one of the field, the URL will work
This is Request payload for summary field
If the user update the Summary field the above endpoint URL will work.
This is Request payload for my_story field
If the user update the my_story field the above endpoint URL will work.
My code(Once the user update anyone of the field. I want to check which field is updated, for this how can I check whether the user is updated Summary or my_story,after accessing the field I want to sanitize the field and send it to response below one is my code):
from lxml.html import clean
def account_update():
data = json.loads(request.data)
cleaner = clean.Cleaner()
if data['other_details']['summary']:
clean_overview = (data['other_details']['summary'])
sanitized_html = cleaner.clean_html(clean_overview)
else:
clean_overview = (data['other_details']['my_story'])
sanitized_html = cleaner.clean_html(clean_overview)
return jsonify({"account": data})
Guys , in the above code I am getting the request payload as data, after that I am accessing the summary and my_story fields as data['other_details']['summary'] and data['other_details']['summary'], here I wrote if condition to check if the user update summary field if condition will work suppose user update my_story field it will goes to else part, but in my case if I update my_story field getting error.
Error:
if data['other_details']['summary']:
KeyError: 'summary'
NOTE:
Sanitizing the field is working fine (I mean cleaner = clean.Cleaner() and sanitized_html = cleaner.clean_html(clean_overview), I just want to know which field the user is updating. Please help me guys.
Most likely, the request.data doesn't always have the summary field in data['other_details'].
This means, you have to check for it in you if-else block before trying to access it.
Best to check for other_details as well.
Here is one way of doing this:
from lxml.html import clean
def account_update():
data = json.loads(request.data)
cleaner = clean.Cleaner()
if 'other_details' in data:
other_details = data['other_details']
if 'summary' in other_details:
clean_overview = other_details['summary']
sanitized_html = cleaner.clean_html(clean_overview)
elif 'my_story' in other_details:
clean_overview = other_details['my_story']
sanitized_html = cleaner.clean_html(clean_overview)
return jsonify({"account": data})
What i see your program just can't find summary atribute.
Solution 1
Im not sure this will work but function getattr() can help you.
Change this line
data['other_details']['summary']
To this
getattr(getattr(data,'other_details'),'summary', False)
Here you can learn more about getattr()
What is getattr() exactly and how do I use it?
Solution 2
Just use some try: and except:

Django HTTP request to api

So i been trying to get this to work but at the same time i do not understand some of these code means. I'm sorry for making the question so long but i want to understand how these works.
I am trying to make a HTTP request to another API to do POST and GET method using django. Based on the website code example, which is this url: https://www.twilio.com/blog/2014/11/build-your-own-pokedex-with-django-mms-and-pokeapi.html
As i wanted to use HTTP Request on my API to call other API, therefore i wanted to get a better understanding of how these works and how to use it.
The code is at the bottom of the website. But i will just provide the code here so it is easier for you.
website code
from django_twilio.views import twilio_view
from twilio.twiml import Response
import requests
import json
BASE_URL = 'http://pokeapi.co'
def query_pokeapi(resource_uri):
url = '{0}{1}'.format(BASE_URL, resource_uri)
response = requests.get(url)
if response.status_code == 200:
return json.loads(response.text)
return None
#twilio_view
def incoming_message(request):
twiml = Response()
body = request.POST.get('Body', '')
body = body.lower()
pokemon_url = '/api/v1/pokemon/{0}/'.format(body)
pokemon = query_pokeapi(pokemon_url)
if pokemon:
sprite_uri = pokemon['sprites'][0]['resource_uri']
description_uri = pokemon['descriptions'][0]['resource_uri']
sprite = query_pokeapi(sprite_uri)
description = query_pokeapi(description_uri)
message = '{0}, {1}'.format(pokemon['name'], description['description'])
image = '{0}{1}'.format(BASE_URL, sprite['image'])
frm = request.POST.get('From', '')
if '+44' in frm:
twiml.message('{0} {1}'.format(message, image))
return twiml
twiml.message(message).media(image)
return twiml
twiml.message("Something went wrong! Try 'Pikachu' or 'Rotom'")
return twiml
My question is:
i have read about the request.POST and request.POST.get but i still don't get it. Isn't request.POST = POST method/create function ?
what does body.lower mean ? Cant seems to find anything about it.
I am very confuse about this part
sprite_uri = pokemon['sprites'][0]['resource_uri']
description_uri = pokemon['descriptions'][0]['resource_uri']
sprite = query_pokeapi(sprite_uri)
description = query_pokeapi(description_uri)
is pokemon['sprites'] refers to the sprites field in the api ?
What does this even means ?
frm = request.POST.get('From', '')
if '+44' in frm:
twiml.message('{0} {1}'.format(message, image))
return twiml
twiml.message(message).media(image)
return twiml
request.POST.get('From', '') Isn't POST where user enter data ? Where does 'From' come from? And what does this means ? if '+44' in frm: if +44 is found in frm ?
ALL The questions are based on very basic python concepts, I recommend you go through python docs here Python Docs
Diff in request.POST and request.POST.get()
Ex request.post has following dict {'abc_key': 'abc_value'}
than request.POST['abc_key'] will give 'abc_value'
but request.POST['xyz_key'] will throw error
so we use default value to escape this error
request.POST.get('xyz_key', "default_value")
this will not give error if xyz_key is not found
body.lower
This method returns a copy of the string in which all case-based
characters have been lowercased.
check this link lower()
pokemon['sprites'][0]['resource_uri']
this is serching in pokemon (which have dictionary values)
Ex. pokemon = {'sprites':[{'resource_uri': 'res_value'}, 1, 2, 3 ]}
so pokemon['sprites'][0]['resource_uri'] will give 'res_value'
frm = request.POST.get('From', '') same as i said in 1st point
if '+44' in frm:
this will return True if string '+44' is substring in frm
variable(string)

python self.session doesn't save data correctly

I'm developing a webapp using Google App Engine and Python.
I'm facing a strange problem and i don't know how to solve it and what causes it.
When I fill a form I send the data for checking them. If they aren't complete and some fields are missed the server send the form back with an advice "FILL ALL THE FIELDS!".
That's work pretty well.
What I'm trying to do is sending the form back with the "description" and "title" fields filled with what the user has written before submitting the form, so he must to fill only the unfilled fields (and he doesn't need to rewrite everything from the beginning).
That's the code:
class SaleAnnCheck(BaseHandler):
def post(self):
title = self.request.POST.get('title')
cat = self.request.POST.get('cat')
description = self.request.POST.get('description')
AcqOpt = self.request.POST.get('AcqOpt')
lat = self.request.POST.get('lat')
lng = self.request.POST.get('lng')
image1 = self.request.POST.get("file1", None)
image2 = self.request.POST.get("file2", None)
image3 = self.request.POST.get("file3", None)
logging.info("info sale announcment")
logging.info(title)
logging.info(cat)
logging.info(description)
logging.info(AcqOpt)
logging.info(lat)
logging.info(lng)
logging.info(image1)
logging.info(image2)
logging.info(image3)
self.session["ECommerceUser"]["description"]=description
self.session["ECommerceUser"]["title"]=title
logging.info('session')
logging.info(self.session["ECommerceUser"])
if title == '' or cat == None or description == '' or AcqOpt == None or lat == '' or lng == '':
error = 'empty'
urlR='/CreateSaleAnn?'+urllib.urlencode({'error':'empty'})
self.redirect(urlR)
class Create(BaseHandler):
def get(self):
error = self.request.get('error')
if error == 'empty':
logging.info('sbagliato')
logging.info(self.session["ECommerceUser"])
template = JINJA_ENVIRONMENT.get_template('templates/CreateAnnouncement.html')
w = self.response.write
w(template.render({'error':'FILL ALL THE MANDATORY FIELDS!', 'description': self.session["ECommerceUser"]["description"], 'title': self.session["ECommerceUser"]["title"]}))
else:
logging.info('giusto')
logging.info(self.session["ECommerceUser"])
template = JINJA_ENVIRONMENT.get_template('templates/CreateAnnouncement.html')
w = self.response.write
w(template.render({'description': self.session["ECommerceUser"]["description"], 'title': self.session["ECommerceUser"]["title"]}))
When I submit the form the content is checked by making an HTTP post request to a certain URL, handled by SaleAnnCheck.
Description and Title are saved in the session correctly (i checked it by printing the content of self.session["ECommerceUser"] in the logs). Then, if a field isn't filled, the server redirect again to the form page, by a GET request to a related URL.
The requests to that URL is handled by Create. But when i try to render the HTML template of the form (using jinja2) with the previous typed values of Description and Title the related text areas are not filled with that values.
It happens because self.session["ECommerceUser"]["description"] and self.session["ECommerceUser"]["title"] are empty, but they weren't when i checked them before (in SaleAnnCheck).
Why it happens? Any explanation? It's a weird problem and there aren't any tips or suggestion about on internet
This is because 'self.session' is not a Session, it's just a class variable and will not be readable outside the class. If you really want to use persistent sessions for storing variables, try something like this:
From the docs:
http://docs.python-requests.org/en/master/user/advanced/
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get('http://httpbin.org/cookies')

Django Query doesn't match

I have the following Django Model:
class State(models.Model):
name = models.CharField(max_length=80,null=False)
latitude = models.CharField(max_length=80,null=False)
longitude = models.CharField(max_length=80,null=False)
def __unicode__(self):
return self.name
In my views.py file I've created the following method:
def getCoords(request):
if request.is_ajax():
if request.method == 'POST':
try:
state = request.POST['state'] #receives the state from JS
stateInstance = State.objects.get(name=state)
stateLat = stateInstance.latitude
stateLong = stateInstance.longitude
data = {"lat" : stateLat, "long" : stateLong}
except State.DoesNotExist:
return HttpResponse("No record")
return HttpResponse(simplejson.dumps(data)) #returns json
So I'm sending this method a param through ajax, let's say "California". The state variable gets the value (I have proved that) but the query doesn't get executed, it returns the query doesn't match message. I've tried with the following as well:
state = request.POST['state']
if state == 'California':
return HttpResponse("Yes!")
else:
return HttpResponse(state)
When this snippet returns the state it displays California which means state's value is correct but the query is not executed properly. I don't know what's going on. Any thoughts?
Make sure you're connecting to the correct database in your settings.py. Make sure the record actually does exist with plain old SQL.
SELECT * FROM [app_name]_state WHERE name = 'California';
Also, try it from the Django shell. python manage.py shell
>>> from [app_name].models import State
>>> s = State.objects.get(name='California')
>>> s
<State: California>
Make sure that what is actually being sent is sent as POST, and not accidentally a GET variable in the URL. Also, make sure that the post variable has no extra characters and that it is actually valid. A decent way to do that is to just print it to the console, or if AJAX, with Firebug.
# Single quotes added so you can see any extra spaces in the console
print "'%s'" % state

Pingdom get_actions_alerts method returns empty list

I am new learner to use pingdom-api in django-project to check the status of website.
I have imported pingdom library to access methods directly in my views.py
my views.py
import datetime
import pingdomlib
api = pingdomlib.Pingdom( username = "anilxxxx#gmail.com", password = "xxxxxx", apikey = "xf8xyxxxxxxxxxxxxxxxxxxxxxxx")
def get_actions_alerts(request):
pingdomactions=api.actions()
print "pingdomactions=", pingdomactions
for alert in api.alerts(limit=10):
time = datetime.datetime.fromtimestamp(alert['time'])
timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
print timestamp
print "[%s] %s is %s" % (time, alert['name'], alert['status'])
return render_to_response("base_audit_template.html") #need to render data to this page
def get_checks(request):
pingdomchecks = api.getChecks()
print "pingdomchecks" , pingdomchecks
for check in pingdomchecks:
# See pingdomlib.check documentation for information on PingdomCheck class
if check.status != 'up':
print check
else :
print "status up:" , check
return render_to_response("base_audit_template.html")
But pingdomactions list is empty on hiting url, also not reading alerts
Terminal putput :
pingdomactions= {u'alerts': []}
[21/Jul/2013 05:19:08] "GET /data/actions/ HTTP/1.1" 200 2075
Questions:
What are the possible problems for getting empty action list ? . Do you have any solutions for this error.
Am i using this pingdomlib correctly? or there is another-way to use it.
The api.action() will pass up the alerts returned by the pingdom api, it'll be empty if pingdom has taken no actions in response to alerts. Typically what I've seen from actions is a list of the email alerts pingdom has sent out as a response to downs, so if you haven't had any downs or any email/sms/other alerts sent out from pingdom that's most likely why it is empty.
Overall it looks like you are using my lib as intended, please let me know if it's still giving you any struggles!

Categories

Resources