Missing geocoding parametr - geocoding

This is my dataframe view
from cartoframes.data.services import Geocoding
gc = Geocoding()
london_stations_gdf, london_stations_metadata = gc.geocode(
df,
street='Borough',
city={'value': 'London'},
country={'value': 'United Kingdom'}
)
ValueError: Credentials attribute is required. Please pass a Credentials instance or use the set_default_credentials function.
Error relate with Geocoding parametrs. however use gc = Geocoding(credentials=None), return me same error.

Assuming you have creds (username and api_key)
If you need to create the creds.json file, run the following
from cartoframes.auth import Credentials
Credentials('my_username', 'my_api_key').save('creds.json')
then modify your code to set your default credentials
from cartoframes.auth import set_default_credentials
from cartoframes.data.services import Geocoding
# set your default creds
set_default_credentials('path/to/your/creds.json')
gc = Geocoding()
london_stations_gdf, london_stations_metadata = gc.geocode(
df,
street='Borough',
city={'value': 'London'},
country={'value': 'United Kingdom'}
)

Related

Using hvac login on GCP Cloud Function

first question ever on StackOverflow.
I am trying to write a Cloud Function on gcp to login to vault via hvac.
https://hvac.readthedocs.io/en/stable/usage/auth_methods/gcp.html#login
It says here that a path to a SA json but I am writing this on Cloud Function.
Does anyone have an example on how to do this properly? The default cloud identity SA associated with the function has permission already to the vault address.
Thanks
In Cloud Functions you don't need the path to the Service Account key because the Cloud Identity SA is already loaded as the Application Default Credentials (ADC).
The code from the link you share it's okay for environments where you don't have configured the ADC or simply you prefer to use another account.
For Functions, the code can be simpler:
import time
import json
import googleapiclient.discovery
import google.auth
import hvac
credentials, project = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
now = int(time.time())
expires = now + 900
payload = {
'iat': now,
'exp': expires,
'sub': credentials.service_account_email,
'aud': 'vault/my-role'
}
body = {'payload': json.dumps(payload)}
name = f'projects/{project}/serviceAccounts/{credentials.service_account_email}'
iam = googleapiclient.discovery.build('iam', 'v1', credentials=credentials)
request = iam.projects().serviceAccounts().signJwt(name=name, body=body)
resp = request.execute()
jwt = resp['signedJwt']
client.auth.gcp.login(
role='my-role',
jwt=jwt,
)

Invoking a Google Cloud Function from a Django View

I have created a Google Cloud function that can be invoked through HTTP. The access to the function is limited to the Service account only.
If I had a Django View which should invoke this function and expect a response?
Here is what I have tried
1) Before starting Django I set the environment variable
export GOOGLE_APPLICATION_CREDENTIALS
2) I tried invoking the function using a standalone code, but soon realised this was going nowhere, because I could not figure out the next step after this.
from google.oauth2 import service_account
from apiclient.http import call
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
SERVICE_ACCOUNT_FILE = 'credentials/credentials.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
Google's documentation does give you documentation around the API, but there is no sample code on how to invoke the methods or what to import within your Python code and what are the ways to invoke those methods.
How do you send a POST request with JSON data to an Cloud Function, with authorization through a service account?
**Edit
A couple hours later I did some more digging and figured this out partially
from google.oauth2 import service_account
import googleapiclient.discovery
import json
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
SERVICE_ACCOUNT_FILE = 'credentials/credentials.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
cloudfunction = googleapiclient.discovery.build('cloudfunctions', 'v1', credentials=credentials)
#projects/{project_id}/locations/{location_id}/functions/{function_id}.
path='some project path'
data='some data in json that works when invoked through the console'
data=json.dumps(data)
a=cloudfunction.projects().locations().functions().call(name=path, body=data).execute()
I get another error now.
Details: "[{'#type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'description': 'Invalid JSON payload received. Unknown name "": Root element must be a message.'}]}]">
I cant find any documentation on this. How should the JSON be formed?
making the json like {"message":{my actual payload}} doesn't work.
The requested documentation can be found here.
The request body argument should be an object with the following form:
{ # Request for the `CallFunction` method.
"data": "A String", # Input to be passed to the function.
}
The following modification on your code should work correctly:
from google.oauth2 import service_account
import googleapiclient.discovery
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
SERVICE_ACCOUNT_FILE = 'credentials/credentials.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
cloudfunction = googleapiclient.discovery.build('cloudfunctions', 'v1', credentials=credentials)
path ="projects/your-project-name/locations/cloud-function-location/functions/name-of-cloud-function"
data = {"data": "A String"}
a=cloudfunction.projects().locations().functions().call(name=path, body=data).execute()
Notice that very limited traffic is allowed since there are limits to the API calls.

Launch GCP instance from my PC using python

Which python library should i use to control or launch or delete an instance on my Google cloud platform from my private PC ?
I think the simplest way is to use the Google Compute Engine Python API Client Library. You can see a sample with examples here.
You can see the complete list of functions regarding instances in REST Resource: instances
As you can see, you might do:
import googleapiclient.discovery
compute = googleapiclient.discovery.build('compute', 'v1')
listInstance = compute.instances().list(project=project, zone=zone).execute()
stopInstance = compute.instances().stop(project=project, zone=zone, instance=instance_id).execute()
startInstance = compute.instances().start(project=project, zone=zone, instance=instance_id).execute()
deleteInstance = compute.instances().delete(project=project, zone=zone, instance=instance_id).execute()
Don't confuse the param name "instance" with the chosen name for the path parameter "resourceId". You can see on the right side or at the bottom of the page examples with the real parameter's name.
You also could directly call the the REST API (see example) with in Python if you prefer to using POST/PUT methods.
You also might want to use OAuth. As you can see in the examples of the links provided, it would be something like:
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
service = discovery.build('compute', 'v1', credentials=credentials)
# Project ID for this request.
project = 'my-project' # TODO: Update placeholder value.
# The name of the zone for this request.
zone = 'my-zone' # TODO: Update placeholder value.
# Name of the instance resource to start.
instance = 'my-instance' # TODO: Update placeholder value.
request = service.instances().start(project=project, zone=zone, instance=instance)
response = request.execute()
You may also want to check out libcloud.

Error Pulling Facebook Ad Campaign

I am trying to automate a task for my company. They want me to pull the insights from their ad campaigns and put it in a CSV file. From here I will create a excel sheet that grabs this data and automates the plots that we send to our clients.
I have referenced the example code from the library and I believe where my confusion exists is in who I define 'me' to be in line 14.
token = 'temporary token from facebook API'
VOCO_id = 'AppID'
AppSecret = 'AppSecret'
me = 'facebookuserID'
AppTokensDoNotExpire = 'AppToken'
from facebook_business import FacebookSession
from facebook_business import FacebookAdsApi
from facebook_business.adobjects.campaign import Campaign as AdCampaign
from facebook_business.adobjects.adaccountuser import AdAccountUser as AdUser
session = FacebookSession(VOCO_id,AppSecret,AppTokensDoNotExpire)
api = FacebookAdsApi(session)
FacebookAdsApi.set_default_api(api)
me = AdUser(fbid=VOCO_id)
####my_account = me.get_ad_account()
When I run the following with the hashtag on my_account, I get a return stating that the status is "live" for these but the value of my permissions is not compatible.

Pydrive authentication using

I was using gdata module to access, upload, download files from google doc. I have the oauth key and secret with me. Now I want to switch to google drive api. Learning and studying a bit on google drive api , it looks like a bit different in the authentication. I also have downloaded pydrive module so as I can start things up. But I am not able to authorize my server side python code to authorize/authenticate the user using my oauth keys and access my drive. Do any one has any spare know how on how I can use pydrive to access my drive with my previous auth keys. I just need a simple way to authenticate.
For using the gdata module we use either of these credentials-
1> username & password or
2> consumer oauth key and secret key.
Since you are trying to use oauth credentials, I think you want a Domain Wide Delegated Access for Google Drive, which will help you to achieve uploading/downloading files into any user's google drive through out the domain.
For this you need to generate a new Client ID of a Service Account Type from
Developer's Console
*.p12 file will get downloaded. Note the path where you save it.
Also note the email address of your Service account. These will be use while coding.
Below is the python code where u have to carefully edit-
PATH TO SERIVE ACCOUNT PRIVATE KEY, something#developer.gserviceaccount.com, EMAIL_ID#YOURDOMAIN.COM in order to run it properly and test it.
Hope this will help!
Resource- Google Drive API
import httplib2
import pprint
import sys
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
"""Email of the Service Account"""
SERVICE_ACCOUNT_EMAIL = 'something#developer.gserviceaccount.com'
"""Path to the Service Account's Private Key file"""
SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'PATH TO SERIVE ACCOUNT PRIVATE KEY'
def createDriveService(user_email):
"""Build and returns a Drive service object authorized with the service accounts
that act on behalf of the given user.
Args:
user_email: The email of the user.
Returns:
Drive service object.
"""
f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
scope='https://www.googleapis.com/auth/drive', sub=user_email)
http = httplib2.Http()
http = credentials.authorize(http)
return build('drive', 'v2', http=http)
drive_service=createDriveService('EMAIL_ID#YOURDOMAIN.COM')
result = []
page_token = None
while True:
try:
param = {}
if page_token:
param['pageToken'] = page_token
files = drive_service.files().list().execute()
#print files
result.extend(files['items'])
page_token = files.get('nextPageToken')
if not page_token:
break
except errors.HttpError, error:
print 'An error occurred: %s' % error
break
for f in result:
print '\n\nFile: ',f.get('title')
print "\n"