2014-04-18 52 views
1

我試圖讓一個非常簡單的Python腳本與Freebase交談。Freebase API(Python)的授權令人頭疼

我發現的所有例子都使用simple/api密鑰授權模型。因此,我創建了Google開發者帳戶,製作了一個項目,並試圖按照Google的說法獲得一個關鍵字。它要求我提供一個我將撥打的數字IP地址列表。不可行,因爲我不一個固定的IP(我確實有dyndns設置,但這並沒有幫助,因爲谷歌不會採取域名,只有數字)。

所以我嘗試了OAuth2,這是我需要的東西(我沒有訪問任何非公開用戶數據)的過度殺傷力。但是我甚至找不到在Freebase上使用OAuth2的在線示例。我嘗試過調整其他例子,但是在appengine,Decorator,幾個過時的Python庫以及其他幾種方法之間跳躍之後,我沒有任何地方。

任何人都可以解釋或指出一個很好的例子,如何做到這一點(沒有花費10倍的時間授權,比我試圖授權的應用程序)?一個OAuth2的工作示例,最好沒有多層「簡化」API;或者關於如何避開API密鑰授權的固定IP要求的提示,將會非常棒。謝謝!

史蒂夫

回答

1

我必須爲谷歌驅動器做到這一點,但據我所知,這應該對任何谷歌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 = "[email protected]" 
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. 
+1

謝謝!那讓我感到很開心。我將在下面發佈工作示例(不適合評論)。 – TextGeek

+0

太棒了!我很高興它的工作。 –

0

從@ Rachel的示例代碼工作,帶着幾分擺弄我得到了這一點,它的工作原理,並說明了話題,搜索和查詢功能。

必須安裝庫的urllib和JSON,加上代碼https://code.google.com/p/google-api-python-client/downloads/list 必須從具體的項目「設置」 爲Python的mglread()接口被打破爲2014年4月 的啓用結算的記錄「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)