[英]Authorization headaches for Freebase API (Python)
我正在嘗試獲得一個非常簡單的Python腳本與Freebase對話。
我發現的所有示例都使用簡單的/ api密鑰授權模型。 因此,我創建了一個Google Developer帳戶,創建了一個項目,並嘗試獲取Google所說的密鑰。 它要求我提供一個從中調用的數字IP地址列表。 不可行的,因為我沒有一個固定的IP(我必須設置DynDNS的,但這並不能幫助,因為谷歌不會采取一個域名,僅數字)。
因此,我嘗試了OAuth2,這對於我需要的功能來說是多余的(我不訪問任何非公共用戶數據)。 但是我什至找不到使用OAuth2 for Freebase的在線示例。 我嘗試調整其他示例,但是在Appengine,Decorator,一些過時的Python庫以及其他幾種方法之間跳來跳去之后,我一無所獲。
任何人都可以解釋或指出如何做到這一點的一個很好的例子(在授權上花費的時間比在我嘗試授權的應用程序上花費的時間多10倍)嗎? 使用OAuth2的有效示例,最好沒有多層“簡化” API; 或有關如何解決API密鑰授權的固定IP要求的技巧,將是很棒的。 謝謝!
史蒂夫
我必須對Google雲端硬盤執行此操作,但據我所知,此方法適用於任何Google API。
在開發人員控制台中創建新的客戶ID時,您應該可以選擇創建服務帳戶。 這將創建一個公鑰/私鑰對,您可以使用它來進行身份驗證,而無需任何OAuth廢話。
我將此代碼從我們的GDrive庫中竊取了,因此它可能已損壞,並且是特定於GDrive的,因此您將需要用Freebase所需的內容替換任何顯示“ drive”的內容。
但我希望足以讓您入門。
# Sample code that connects to Google Drive
from apiclient.discovery import build
import httplib2
from oauth2client.client import SignedJwtAssertionCredentials, VerifyJwtTokenError
SERVICE_EMAIL = "you@gmail.com"
PRIVATE_KEY_PATH ="./private_key.p12"
# Load private key
key = open(PRIVATE_KEY_PATH, 'rb').read()
# Build the credentials object
credentials = SignedJwtAssertionCredentials(SERVICE_EMAIL, key, scope='https://www.googleapis.com/auth/drive')
try:
http = httplib2.Http()
http = credentials.authorize(http)
except VerifyJwtTokenError as e:
print(u"Unable to authorize using our private key: VerifyJwtTokenError, {0}".format(e))
raise
connection = build('drive', 'v2', http=http)
# You can now use connection to call anything you need for freebase - see their API docs for more info.
我通過@Rachel的示例代碼進行了一些工作,使我有些困惑,它可以正常工作,並說明了主題,搜索和查詢功能。
必須安裝庫urllib和json,以及來自https://code.google.com/p/google-api-python-client/downloads/list的代碼,必須為特定項目啟用“設置”計費功能自2014年4月起,Python已損壞。已記錄的“ freebase.readonly”范圍無效。
from apiclient.discovery import build
import httplib2
from oauth2client.client import SignedJwtAssertionCredentials, VerifyJwtTokenError
# Set up needed constants
#
SERVICE_EMAIL = args.serviceEmail
PRIVATE_KEY_PATH = args.privateKeyFile
topicID = args.topicID
query = args.query
search_url = 'https://www.googleapis.com/freebase/v1/search'
topic_url = 'https://www.googleapis.com/freebase/v1/topic'
mql_url = "https://www.googleapis.com/freebase/v1/mqlread"
key = open(PRIVATE_KEY_PATH, 'rb').read()
credentials = SignedJwtAssertionCredentials(SERVICE_EMAIL, key,
scope='https://www.googleapis.com/auth/freebase')
try:
http = httplib2.Http()
http = credentials.authorize(http)
except VerifyJwtTokenError as e:
print(u"Unable to authorize via private key: VerifyJwtTokenError, {0}".format(e))
raise
connection = build('freebase', 'v1', http=http)
# Search for a topic by Freebase topic ID
# https://developers.google.com/freebase/v1/topic-overview
#
params = { 'filter': 'suggest' }
url = topic_url + topicID + '?' + urllib.urlencode(params)
if (args.verbose): print("URL: " + url)
resp = urllib.urlopen(url).read()
if (args.verbose): print("Response: " + resp)
respJ = json.loads(resp)
print("Topic property(s) for '%s': " % topicID)
for property in respJ['property']:
print(' ' + property + ':')
for value in respJ['property'][property]['values']:
print(' - ' + value['text'])
print("\n")
# Do a regular search
# https://developers.google.com/freebase/v1/search-overview
#
params = { 'query': query }
url = search_url + '?' + urllib.urlencode(params)
if (args.verbose): print("URL: " + url)
resp = urllib.urlopen(url).read()
if (args.verbose): print("Response: " + resp)
respJ = json.loads(resp)
print("Search result for '%s': " % query)
theKeys = {}
for res in respJ['result']:
print ("%-40s %-15s %10.5f" %
(res['name'], res['mid'], res['score']))
params = '{ "id": "%s", "type": []}' % (res['mid'])
# Run a query on the retrieved ID, to get its types:
url = mql_url + '?query=' + params
resp = urllib.urlopen(url).read()
respJ = json.loads(resp)
print(" Type(s): " + `respJ['result']['type']`)
otherKeys = []
for k in res:
if (k not in ['name', 'mid', 'score']): otherKeys.append(k)
if (len(otherKeys)): print(" Other keys: " + ", ".join(otherKeys))
sys.exit(0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.