简体   繁体   中英

Google Datastore API Authentication in Python

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...

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 = "me@fake.com"

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM