0

Authenticating requests, especially with Google's API's is so incredibly confusing!

I'd like to make authorized HTTP POST requests through python in order to query data from the datastore. I've got a service account and p12 file all ready to go. I've looked at the examples, but it seems no matter which one I try, I'm always unauthorized to make requests.

Everything works fine from the browser, so I know my permissions are all in order. So I suppose my question is, how do I authenticate, and request data securely from the Datastore API through python?

I am so lost...

1 Answer 1

1

You probably should not be using raw POST requests to use Datastore, instead use the gcloud library to do the heavy lifting for you.

I would also recommend the Python getting started page, as it has some good tutorials.

Finally, I recorded a podcast where I go over the basics of using Datastore with Python, check it out!

Here is the code, and here is an example:

#Import libraries
from gcloud import datastore
import os

#The next few lines will set up your environment variables
#Replace "YOUR_RPOEJCT_ID_HERE" with the correct value in code.py
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "key.json"

projectID = "YOUR_RPOEJCT_ID_HERE"

os.environ["GCLOUD_TESTS_PROJECT_ID"] = projectID
os.environ["GCLOUD_TESTS_DATASET_ID"] = projectID
datastore.set_default_dataset_id(projectID)

#Let us build a message board / news website

#First, create a fake email for our fake user
email = "[email protected]"

#Now, create a 'key' for that user using the email
user_key = datastore.Key('User', email)

#Now create a entity using that key
new_user = datastore.Entity( key=user_key )

#Add some fields to the entity

new_user["name"] = unicode("Iam Fake")
new_user["email"] = unicode(email)

#Push entity to the Cloud Datastore
datastore.put( new_user )

#Get the user from datastore and print
print( datastore.get(user_key) )

This code is licensed under Apache v2

Sign up to request clarification or add additional context in comments.

3 Comments

How would I query using this type of approach? I've seen the example but i'm unsure of how to grab entities from say, my Sections table.
This code throws an error: AttributeError: 'module' object has no attribute 'set_default_dataset_id'
Check out the docs: googlecloudplatform.github.io/gcloud-python/stable/… Also, did you pip install gcloud?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.