getting lat_lng error while using google places api - python

I am using the Google Places API with Python to build a chatbot application to suggest nearby places.
I am referring to the below link:
https://github.com/slimkrazy/python-google-places
I am doing something like this:
from googleplaces import GooglePlaces, types, lang
API_KEY = ''
google_places = GooglePlaces(API_KEY)
query_result = google_places.nearby_search(
location='Mumbai', keyword='Restaurants',
radius=1000, types=[types.TYPE_RESTAURANT])
if query_result.has_attributions:
print query_result.html_attributions
for place in query_result.places:
print place.name
print place.geo_location
print place.place_id
Its given in the link itself. However , I keep getting the following error:
Traceback (most recent call last):
File "run.py", line 9, in <module>
radius=1000, types=[types.TYPE_RESTAURANT])
File "/home/neetu/Desktop/python-google-places/googleplaces/__init__.py", line 281, in nearby_search
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
File "/home/neetu/Desktop/python-google-places/googleplaces/__init__.py", line 593, in _generate_lat_lng_string
'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e))
ValueError: lat_lng must be a dict with the keys, 'lat' and 'lng'. Cause: Request to URL https://maps.googleapis.com/maps/api/geocode/json?sensor=false&key=AIzaSyAiFpFd85eMtfbvmVNEYuNds5TEF9FjIPI&address=Mumbai failed with response code: REQUEST_DENIED
Any help is super welcome :)

According to the documentation:
https://github.com/slimkrazy/python-google-places/blob/master/googleplaces/init.py:
You should be able to provide a location instead of a lat_lng pair, but you could try giving a lat_lng instead of a location.
Try removing:
location="Mumbai"
and adding
lat_lng={'lat:19.148320, 'lng':72.888794}
After digging through the code, I understand the error.
The error you got was:
ValueError: lat_lng must be a dict with the keys, 'lat' and 'lng'. Cause: >Request to URL https://maps.googleapis.com/maps/api/geocode/json?>sensor=false&key=AIzaSyAiFpFd85eMtfbvmVNEYuNds5TEF9FjIPI&address=Mumbai failed >with response code: REQUEST_DENIED
what it is saying is that it tried to look to google to get the lat_lng pair for "Mumbai", but the request failed as it was denied. Use a valid API key from Google and it should work.

Related

Amazon Neptune on submitting query: AttributeError: 'str' object has no attribute 'source_instructions'

I have the following code running on AWS lambda, but getting the following error.
Error
[ERROR] AttributeError: 'str' object has no attribute 'source_instructions'
Traceback (most recent call last):
File "/var/task/gremlin_python/driver/driver_remote_connection.py", line 56, in submit
    result_set = self._client.submit(bytecode, request_options=self._extract_request_options(bytecode))
  File "/var/task/gremlin_python/driver/driver_remote_connection.py", line 81, in _extract_request_options
    options_strategy = next((x for x in bytecode.source_instructionsEND RequestId: 4ee8073c-e941-43b3-8014-8717893b3188
Source code
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
def test_neptune(host):
remoteConn = DriverRemoteConnection('wss://{}:8182/gremlin','g'.format(host))
query = "g.V().groupCount().by(label).unfold().project('label','count').by(keys).by(values)"
response = remoteConn.submit(query)
print("response-> {}" .format(response))
# iterate repsonse
# go thru label
for set_item in response:
for item in set_item:
print("item-> item: {}".format(item))
remoteConn.close()
test_neptune()
Your DriverRemoteConnection call is wrong. You have:
remoteConn = DriverRemoteConnection('wss://{}:8182/gremlin','g'.format(host))
So you are sending {} as the hostname, and passing 'g' as a second parameter, which is probably where the error comes from. I don't know what you intended the 'g' for, but you probably want:
remoteConn = DriverRemoteConnection('wss://{}:8182/gremlin'.format(host))
If you send the query as a text string you need to create the Client object differently or write the query as in-line Python. There are two examples at (1) and (2) that show each option. The error you are seeing is because the server is trying to find Gremlin bytecode in the packet sent but only found a string (which does not have a source_instructions method).
Using a DriverRemoteConnection you can use a Python line of code such as:
result = (g.V().groupCount().
by(label).
unfold().
project('label','count').
by(keys).
by(values).
next())
If you actually want/need to send the query as a string instead of bytecode, please see my answer to this question
https://github.com/krlawrence/graph/blob/master/sample-code/basic-client.py
https://github.com/krlawrence/graph/blob/master/sample-code/glv-client.py

How to download datasat from The Humanitarian Data Exchange (hdx api python)

I don't quite understand how I can download data from a dataset. I only download one file, and there are several of them. How can I solve this problem?
I am using hdx api library. There is a small example in the documentation. A list is returned to me and I use the download method. But only the first file from the list is downloaded, not all of them.
My code
from hdx.hdx_configuration import Configuration
from hdx.data.dataset import Dataset
Configuration.create(hdx_site='prod', user_agent='A_Quick_Example', hdx_read_only=True)
dataset = Dataset.read_from_hdx('novel-coronavirus-2019-ncov-cases')
resources = dataset.get_resources()
print(resources)
url, path = resources[0].download()
print('Resource URL %s downloaded to %s' % (url, path))
I tried to use different methods, but only this one turned out to be working, it seems some kind of error in the loop, but I do not understand how to solve it.
Result
Resource URL https://data.humdata.org/hxlproxy/api/data-preview.csv?url=https%3A%2F%2Fraw.githubusercontent.com%2FCSSEGISandData%2FCOVID-19%2Fmaster%2Fcsse_covid_19_data%2Fcsse_covid_19_time_series%2Ftime_series_covid19_confirmed_global.csv&filename=time_series_covid19_confirmed_global.csv downloaded to C:\Users\tred1\AppData\Local\Temp\time_series_covid19_confirmed_global.csv.CSV
Forgot to add that I get a list of strings where there is a download url value. Probably the problem is in the loop
When I use a for-loop I get this:
for res in resources:
print(res)
res[0].download()
Traceback (most recent call last):
File "C:/Users/tred1/PycharmProjects/pythonProject2/HDXapi.py", line 31, in <module>
main()
File "C:/Users/tred1/PycharmProjects/pythonProject2/HDXapi.py", line 21, in main
res[0].download()
File "C:\Users\tred1\AppData\Local\Programs\Python\Python38\lib\collections\__init__.py", line 1010, in __getitem__
raise KeyError(key)
KeyError: 0
Datasets
You can get the download link as follows:
dataset = Dataset.read_from_hdx('acled-conflict-data-for-africa-1997-lastyear')
lita_resources = dataset.get_resources()
dictio=lista_resources[1]
url=dictio['download_url']

How to use get_attachment call upon QueryResult (python cloudant) ?

I've been trying to get attachment image data from documents in Cloudant.
I can successfully do it once a document is selected (direct extract with _id, etc).
Now trying to do it in combination with "query" operation using selector, I run into trouble.
Here is my code.
targetName="chibika33"
targetfile="chibitest.png"
#--------------------------------------------------
# get all the documents with the specific nameField
#--------------------------------------------------
myDatabase.create_query_index(fields = ['nameField'])
selector = {'nameField': {'$eq': targetName}}
docs = myDatabase.get_query_result(selector)
#--------------------------------------------------
# get the attachment files to them, save it locally
#--------------------------------------------------
count = 0
for doc in docs:
count=count+1
result_filename="result%03d.png"%(count)
dataContent = doc.get_attachment(targetfile, attachment_type='binary')
dataContentb =base64.b64decode(dataContent)
with open(result_filename,'wb') as output:
output.write(dataContentb)
Causes error as;
Traceback (most recent call last):
File "view8.py", line 44, in <module>
dataContent = doc.get_attachment(targetfile, attachment_type='binary')
AttributeError: 'dict' object has no attribute 'get_attachment'
So far, I've been unable to find any API for converting dict to document object in the python-cloudant-document...[python-cloudant document]: http://python-cloudant.readthedocs.io/en/latest/index.html
Any advise would be highly appreciated.
The returned structure from get_query_result(...) isn't an array of documents.
Try:
resp = myDatabase.get_query_result(selector)
for doc in resp['docs']:
# your code here
See the docs at:
http://python-cloudant.readthedocs.io/en/latest/database.html#cloudant.database.CloudantDatabase.get_query_result

Can't find SalesForce Object

I'm having some trouble with SalesForce, I've never used it before so I'm not entirely sure what is going wrong here. I am using the simple_salesforce python module. I have successfully pulled data from SalesForce standard objects, but this custom object is giving me trouble. My query is
result = sf.query("Select Name from Call_Records__c")
which produces this error:
Traceback (most recent call last):
File "simple.py", line 15, in <module>
result = sf.query("Select Name from Call_Records__c")
File "/usr/local/lib/python2.7/dist-packages/simple_salesforce/api.py", line 276, in query
_exception_handler(result)
File "/usr/local/lib/python2.7/dist-packages/simple_salesforce/api.py", line 634, in _exception_handler
raise exc_cls(result.url, result.status_code, name, response_content)
simple_salesforce.api.SalesforceMalformedRequest: Malformed request https://sandbox.company.com/services/data/v29.0/query/?q=Select+Name+from+Call_Records__c. Response content: [{u'errorCode': u'INVALID_TYPE', u'message': u"\nSelect Name from Call_Records__c\n ^\nERROR at Row:1:Column:18\nsObject type 'Call_Records__c' is not supported. If you are attempting to use a custom object, be sure to append the '__c' after the entity name.
Please reference your WSDL or the describe call for the appropriate names."}]
I've tried it with and without the __c for both the table name and the field name, still can't figure this out. Anything blatantly wrong?
Make sure your result is Call_Records__c/CallRecords__c
Call_Records__c result = sf.query("Select Name from Call_Records__c")
Or
CallRecords__c result = sf.query("Select Name from CallRecords__c")
Try using -
result = sf.query("Select Name from CallRecords__c")

How to add members to a group using directory api and python?

I am trying to get my head around migrating to google admin sdk. I am trying to add members to a group (mailing list) using python. I have figured out how to create the group, but can't figure out how to add members. I have read this page: https://developers.google.com/admin-sdk/directory/v1/reference/members/insert but cannot figure out how to map it to python (I have little experience with REST or python, I'm trying to learn).
This is how I am trying to do it:
import httplib2
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
keyFile = file(p12File, 'rb')
key = keyFile.read()
keyFile.close()
credentials = SignedJwtAssertionCredentials(serviceAccount,
key,
scope,
prn=superAdmin)
http = httplib2.Http()
httplib2.debuglevel = False #change this to True if you want to see the output
http = credentials.authorize(http=http)
directoryService = build(serviceName='admin', version='directory_v1', http=http)
# THIS DOES NOT WORK
groupinfo = {'email': 'wibble#XXX.co.uk'}
directoryService.groups().insert(groupKey='mygroup#XXX.co.uk', body=groupinfo).execute()
When I run that I get:
Traceback (most recent call last):
File "add-member-to-group.py", line 58, in <module>
directoryService.groups().insert(groupKey='mygroup#XXX.co.uk', body=groupinfo).execute()
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/discovery.py", line 604, in method
raise TypeError('Got an unexpected keyword argument "%s"' % name)
TypeError: Got an unexpected keyword argument "groupKey"
I would be grateful if someone could help me to figure out how to do this.
After further hunting around I worked it out. That last line should have been:
directoryService.members().insert(groupKey='mygroup#XXX.co.uk', body=groupinfo).execute()
i.e. directoryService.members()... not directoryService.groups()...
The examples here helped me to work it out.

Categories

Resources