如何使用适用于Python的Google API客户端库(http://wiki.freebase.com/wiki/Google_API_Client_Libraries#Python)重现以下MQL查询
https://api.freebase.com/api/service/mqlread?queries={"q1":[{"name~=":"*doubt*","name": None,"type": "/media_common/quotation","author": [{"name": "William Shakespeare"}]}], "q2":[{"name~=":"*law*","name": None,"type": "/media_common/quotation","author": [{"name": "William Shakespeare"}]}]}
以下单个查询有效:
from apiclient import discovery
from apiclient import model
import json
from pprint import pprint
DEVELOPER_KEY = ''
model.JsonModel.alt_param = ""
freebase = discovery.build('freebase', 'v1', developerKey=DEVELOPER_KEY)
query = [{"name~=":"*doubt*","name": None,"type": "/media_common/quotation","author": [{"name": "William Shakespeare"}]}]
response = json.loads(freebase.mqlread(query=json.dumps(query)).execute())
pprint (response)
我看不出如何将“查询”参数更改为“查询”
答案 0 :(得分:1)
queries
参数在新API中消失了。您可以采用与此类似的方式使用lightly documented RPC接口:
import urllib
import urllib2
import json
url = 'https://www.googleapis.com/rpc'
requests = [{
'method': 'freebase.text.get',
'apiVersion': 'v1',
'params': {
'id': ['en','bob_dylan']
}
},{
'method': 'freebase.text.get',
'apiVersion': 'v1',
'params': {
'id': ['en','blade_runner']
}
}]
headers = { 'Content-Type': 'application/json' }
req = urllib2.Request(url, json.dumps(requests), headers)
response = urllib2.urlopen(req)
print response.read()
[代码片段由Shawn Simister提供,Google dev rel]
答案 1 :(得分:1)
在Google API Python Client的下一个版本(版本1.0 beta 9)中,您可以将多个查询批处理在一起:
from apiclient import discovery, model
from apiclient.http import BatchHttpRequest
import json
DEVELOPER_KEY = open('DEVELOPER_KEY').read()
query1 = [{"name~=":"*doubt*","name":None,"type":"/media_common/quotation","author":[{"name":"William Shakespeare"}]}]
query2 = [{"name~=":"*law*","name":None,"type":"/media_common/quotation","author":[{"name":"William Shakespeare"}]}]
model.JsonModel.alt_param = ""
freebase = discovery.build('freebase', 'v1', developerKey=DEVELOPER_KEY)
def display_results(request_id, response):
for topic in response['result']:
print topic['name']
batch = BatchHttpRequest(callback=display_results)
batch.add(freebase.mqlread(query=json.dumps(query1)))
batch.add(freebase.mqlread(query=json.dumps(query2)))
batch.execute(http)
使用这种技术,您可以将多个查询,甚至MQL查询与搜索查询组合在一起,它只会创建一个HTTP请求。
答案 2 :(得分:0)
假设发现文档包含queries
参数,我相信它将是:
queries = {"q1":[{"name~=":"*doubt*","name": None,"type": "/media_common/quotation","author": [{"name": "William Shakespeare"}]}], "q2":[{"name~=":"*law*","name": None,"type": "/media_common/quotation","author": [{"name": "William Shakespeare"}]}]}
response = json.loads(freebase.mqlread(queries=json.dumps(queries)).execute())
pprint (response)
客户端使用发现文档来确定每个API方法接受的参数。所以只需更改python参数的名称即可。