How to use Google Place Add in Python - python-2.7

I'm using Google Place API for Web Service, in Python.
And I'm trying to add places like the tutorial here
My code is here:
from googleplaces import GooglePlaces, types, lang, GooglePlacesError, GooglePlacesAttributeError
API_KEY = "[Google Place API KEY]"
google_places = GooglePlaces(API_KEY)
try:
added_place = google_places.add_place(
name='Mom and Pop local store',
lat_lng={'lat': 51.501984, 'lng': -0.141792},
accuracy=100,
types=types.TYPE_HOME_GOODS_STORE,
language=lang.ENGLISH_GREAT_BRITAIN)
except GooglePlacesError as error_detail:
print error_detail
But I kept getting this error:
I tried to change the input into Json format or Python dictionary format, then it gave the error "google_places.add_place() only accept 1 parameter, 2 give"......
Is there any right way to use Google Place API Add Place method in Python?

Oh, finally I found the solution, it's so simple... I am not familiar with Python POST requests, in fact everything is easy.
Just need the code here, and we will be able to add a Place in Google Place API, with Python:
import requests
post_url = "https://maps.googleapis.com/maps/api/place/add/json?key=" + [YOUR_API_KEY]
r = requests.post(post_url, json={
"location": {
"lat": -33.8669710,
"lng": 151.1958750
},
"accuracy": 50,
"name": "Google Shoes!",
"phone_number": "(02) 9374 4000",
"address": "48 Pirrama Road, Pyrmont, NSW 2009, Australia",
"types": ["shoe_store"],
"website": "http://www.google.com.au/",
"language": "en-AU"
})
To check the results:
print r.status_code
print r.json()

Related

I'm not getting the expected response from client.describe_image_scan_findings() using Boto3

I'm trying to use Boto3 to get the number of vulnerabilities from my images in my repositories. I have a list of repository names and image IDs that are getting passed into this function. Based off their documentation
I'm expecting a response like this when I filter for ['imageScanFindings']
'imageScanFindings': {
'imageScanCompletedAt': datetime(2015, 1, 1),
'vulnerabilitySourceUpdatedAt': datetime(2015, 1, 1),
'findingSeverityCounts': {
'string': 123
},
'findings': [
{
'name': 'string',
'description': 'string',
'uri': 'string',
'severity': 'INFORMATIONAL'|'LOW'|'MEDIUM'|'HIGH'|'CRITICAL'|'UNDEFINED',
'attributes': [
{
'key': 'string',
'value': 'string'
},
]
},
],
What I really need is the
'findingSeverityCounts' number, however, it's not showing up in my response. Here's my code and the response I get:
main.py
repo_names = ['cftest/repo1', 'your-repo-name', 'cftest/repo2']
image_ids = ['1.1.1', 'latest', '2.2.2']
def get_vuln_count(repo_names, image_ids):
container_inventory = []
client = boto3.client('ecr')
for n, i in zip(repo_names, image_ids):
response = client.describe_image_scan_findings(
repositoryName=n,
imageId={'imageTag': i}
)
findings = response['imageScanFindings']
print(findings)
Output
{'findings': []}
The only thing that shows up is findings and I was expecting findingSeverityCounts in the response along with the others, but nothing else is showing up.
THEORY
I have 3 repositories and an image in each repository that I uploaded. One of my theories is that I'm not getting the other responses, such as findingSeverityCounts because my images don't have vulnerabilities? I have inspector set-up to scan on push, but they don't have vulnerabilities so nothing shows up in the inspector dashboard. Could that be causing the issue? If so, how would I be able to generate a vulnerability in one of my images to test this out?
My theory was correct and when there are no vulnerabilities, the response completely omits certain values, including the 'findingSeverityCounts' value that I needed.
I created a docker image using python 2.7 to generate vulnerabilities in my scan to test out my script properly. My work around was to implement this if statement- if there's vulnerabilities it will return them, if there aren't any vulnerabilities, that means 'findingSeverityCounts' is omitted from the response, so I'll have it return 0 instead of giving me a key error.
Example Solution:
response = client.describe_image_scan_findings(
repositoryName=n,
imageId={'imageTag': i}
)
if 'findingSeverityCounts' in response['imageScanFindings']:
print(response['imageScanFindings']['findingSeverityCounts'])
else:
print(0)

Tests and Environments

i'm newbie here and newbie also using postman.
I'm trying to use environments to store values from responses and use them to the next request. I found some examples on the web and i use them.
I managed to store the first value in a environment but not the 2nd, 3rd, in the same request. I tried many different ways to write the tests but without success
My tests' code is this:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("clientID", jsonData.LoginClientID);
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("COMPANY", jsonData.objs.data[0].LoginCompan
Response was this:
{
"success": true,
"clientID": "abcd",
"objs": [
{
"COMPANY": "1",
"BRANCH": "1",
"MODULE": "0",
}
],
"ver": "5.00.518.11143"
}
Running the POST request the value of clientID is stored in enviroment's value but not COMPANY
Any advice ?
Thanks Eddie
Just remove the data part of the code when setting the variable. You're just after the list of items in that objs array, not sure where data comes into it.
For example, from your code:
jsonData.objs[0].LoginCompan
More information about extracting values from a response body can be found here:
https://community.getpostman.com/t/sharing-tips-and-tricks-with-others-in-the-postman-community/5123/5

How to send GET request to API

Summary: I have a job board, a user searches a zip code and all the jobs matching that zip code are displayed, I am trying to add a feature that lets you see jobs within a certain mile radius of that zip code. There is a web API ( www.zipcodeapi.com ) that does these calculations and returns zip codes within the specified radius, I am just unsure how to use it.
Using www.zipcodeapi.com , you enter a zip code and a distance and it returns all zip codes within this distance. The format for API request is as follows: https://www.zipcodeapi.com/rest/<api_key>/radius.<format>/<zip_code>/<distance>/<units>, so if a user enters zip code '10566' and a distance of 5 miles, the format would be https://www.zipcodeapi.com/rest/<api_key>/radius.json/10566/5/miles and this would return:
{
"zip_codes": [
{
"zip_code": "10521",
"distance": 4.998,
"city": "Croton On Hudson",
"state": "NY"
},
{
"zip_code": "10548",
"distance": 3.137,
"city": "Montrose",
"state": "NY"
}
#etc...
]
}
My question is how do I send a GET request to the API using django?
I have the user searched zip code stored in zip = request.GET.get('zip') and the mile radius stored in mile_radius = request.GET['mile_radius']. How can I incorporate those two values in their respective spots in https://www.zipcodeapi.com/rest/<api_key>/radius.<format>/<zip_code>/<distance>/<units> and send the request? Can this be done with Django or do I have this all confused? Does it need to be done with a frontend language? I have tried to search this on google but only find this for RESTful APIS, and I dont think this is what I am looking for. Thanks in advance for any help, if you couldn't tell i've never worked with a web API before.
You can use the requests package, to do exactly what you want. It's pretty straightforward and has good documentation.
Here's an example of how you could perform it for your case:
zip_code = request.GET.get('zip')
mile_radius = request.GET['mile_radius']
api_key = YOUR_API_KEY
fmt = 'json'
units = 'miles'
response = requests.get(
url=f'https://www.zipcodeapi.com/rest/{api_key}/radius.{fmt}/{zip_code}/{mile_radius}/{units}')
zip_codes = response.json().get('zip_codes')
zip_codes should then be an array with those dicts as in your example.

I want to manipulate the file in MarkLogic using Python

declareUpdate();
//get Docs
myDoc = cts.doc("/heal/scripts/Test.json").toObject();
//add Data
myDoc.prescribedPlayer =
[
{
"default": "http://www.youtube.com/watch?vu003dhYB0mn5zh2c"
}
]
//persist
xdmp.documentInsert("/heal/scripts/Test.json",myDoc,null,"scripts")
You're looking to add a new JSON property. You can do that using a REST Client API request, sending a PATCH command. Use an insert instruction in the patch.
See the note in Specifying Position in JSON, which indicates that
You cannot use last-child to insert a property as an immediate child of the root node of a document. Use before or after instead. For details, see Limitations of JSON Path Expressions.
Instead, your patch will look something like:
{
"insert": {
"context": "/topProperty",
"position": "after",
"content":
[
{
"default": "http://www.youtube.com/watch?vu003dhYB0mn5zh2c"
}
],
}
}
where topProperty is a JSON property that is part of the root node of the JavaScript object you want to update.
If that approach is problematic (for instance, if there is no topProperty that's reliably available), you could also do a sequence of operations:
retrieve the document
edit the content in Python
update the document in the database
With this approach, there is the possibility that some other process may update the document while you're working on it. You can either rely on optimistic locking or a multi-statement transaction to work around that, depending on the potential consequences of someone else doing a write.
Hey #Ankur Please check below python method,
def PartialUpdateData(self,filename, content, context):
self.querystring = {"uri": "/" + self.collection + "/" + filename}
url = self.baseUri
self.header = {'Content-Type': "application/json"}
mydata = {
"patch":[{ "insert": {
"context": context,
"position": "before",
"content": content
}}]}
resp = requests.patch(url + "/documents", data=json.dumps(mydata),
headers=self.header, auth=self.auth, params=self.querystring)
return resp.content
I hope this can solve your problem.

How to expose a Django model as a RESTful web service?

I'm trying to create a REST web service that exposes the following Django model:
class Person(models.Model):
uid = models.AutoField(primary_key=True)
name = models.CharField(max_length=40)
latitude = models.CharField(max_length=20)
longitude = models.CharField(max_length=20)
speed = models.CharField(max_length=10)
date = models.DateTimeField(default=datetime.datetime.now)
def __unicode__(self):
return self.name
Here's how I thought about it so far:
Get all Persons
URL: http://localhost/api/persons/
Method: GET
Querystring:
startlat=
endlat=
startlng=
endlng=
Used for getting the Persons that are within the specified coordinate range.
page=
Used for getting the specified page of the response (if the response contains multiple pages).
Returns:
200 OK & JSON
404 Not Found
Example:
Request:
GET http://localhost/api/persons/?startlat=10&endlat=15&startlng=30&endlng=60
Response:
{
"persons":
[
{ "href": "1" },
{ "href": "2" },
{ "href": "3" },
...
{ "href": "100" }
],
"next": "http://localhost/api/persons/?startlat=10&endlat=15&startlng=30&endlng=60&page=2"
}
Get info on a specified Person
URL: http://localhost/api/persons/[id]
Method: GET
Returns:
200 OK & JSON
404 Not Found
Example:
Request:
http://localhost/api/persons/5/
Response:
{
"uid": "5",
"name": "John Smith",
"coordinates": {
"latitude":"14.43432",
"longitude":"56.4322"
},
"speed": "12.6",
"updated": "July 17, 2009, 8:46 a.m."
}
How correct is my attempt so far? Any suggestions are highly appreciated.
{ "href": "1" },
1 is hardly a valid URL. You should use full URLs. Google for HATEOAS.
Also, remember to send a relevant Content-Type header. You may want to make up your own mime-type to describe the format. This gives you the option to later change the content-type (Eg. change the format after publishing). See Versioning REST Web Services
I think query parameters could be simpler and clearer. This would make the URI more readable and would allow more flexibility for future extensions:
GET http://localhost/api/persons/?latitude=10:15&longitude=30:60
You may want to enable these in the future:
GET http://localhost/api/persons/?latitude=10&longitude=60&within=5km
Seems REST-cool. Even i worked on same kind of thing, few days earlier.
The only change, i would love to do in it, is the direct link to the person details. And also some details (like name here) to identify the person, and aid me in decision to navigate further. Like...
{
"persons":
[
{ "name": "John Smith", "href": "http://localhost/api/persons/1/" },
{ "name": "Mark Henry", "href": "http://localhost/api/persons/2/" },
{ "name": "Bruce Wayne", "href": "http://localhost/api/persons/3/" },
...
{ "name": "Karl Lewis", "href": "http://localhost/api/persons/100/" }
],
"next": "http://localhost/api/persons/?startlat=10&endlat=15&startlng=30&endlng=60&page=2"
}
This way, i am giving everything, to present data as,
John
Smith
Mark
Henry
Bruce
Wayne
...
Karl Lewis
Next Page
It's ok to provide shorthand URIs in your JSON responses if you provide some templating system. Like giving a base URI as something like http://whatever.com/persons/{id}/ and then providing IDs. Then with python you can just do a format call on the string. You don't ever want to make the programmer actually look at and understand the meaning of the URIs, which isn't necessary when you use templates.
You might want to take a look at pre-existing REST middleware. I know they saved me a lot of time. I'm using http://code.google.com/p/django-rest-interface/. And a snippet of the urls.py
json_achievement_resource = Collection(
queryset = Achievement.objects.all(),
permitted_methods = ('GET',),
responder = JSONResponder(paginate_by = 10)
)
urlpatterns += patterns('',
url(r'^api/ach(?:ievement)?/(.*?)/json$', json_achievement_resource),
)