2014-04-18 53 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)