热门标签:
Q:

Freebase python

我从freebase尝试了这个python示例,并在我的windows和ubuntu机器中运行它。

http://mql.freebaseapps.com/ch04.html

import sys            # Command-line arguments, etc.
import simplejson     # JSON encoding.
import urllib         # URI encoding.
import urllib2        # High-level URL content fetching.

# These are some constants we'll use.
SERVER = 'api.freebase.com'              # Metaweb server
SERVICE = '/api/service/mqlread'         # Metaweb service

# Compose our MQL query as a Python data structure.
# The query is an array in case multiple bands share the same name.
band = sys.argv[1]                       # The desired band, from command line.
query = [{'type': '/music/artist',       # Our MQL query in Python.
          'name': band,                  # Place the band in the query.
          'album': [{ 'name': None,      # None is Python's null.
                      'release_date': None,
                      'sort': 'release_date' }]}]

# Put the query in an envelope
envelope = {
    'query': query,              # The query property specifies the query.
    'escape': False              # Turns off HTML escaping.
    }

# These five lines are the key code for using mqlread
encoded = simplejson.dumps(envelope)            # JSON encode the envelope.
params = urllib.urlencode({'query':encoded})    # Escape request parameters.
url ='http://%s%s?%s' % (SERVER,SERVICE,params) # The URL to request.
f = urllib2.urlopen(url)                        # Open the URL as a file.
response = simplejson.load(f)                   # Read and JSON parse response.

# Check for errors and exit with a message if the query failed.
if response['code'] != '/api/status/ok':                   # If not okay...
    error = response['messages'][0]                        # First msg object.
    sys.exit('%s: %s' % (error['code'], error['message'])) # Display code,msg.

# No errors, so handle the result
result = response['result']           # Open the response envelope, get result.

# Check the number of matching bands
if len(result) == 0:
    sys.exit('Unknown band')
elif len(result) > 1:
    print "Warning: multiple bands named " + band + ". Listing first only."

result = result[0]                    # Get first band from array of matches.
if not result['album']:               # Exit if band has no albums
    sys.exit(band + ' has no known albums.')

for album in result['album']:         # Loop through the result albums.
    name = album['name']              # Album name.
    date = album['release_date']      # Release date timestamp or null.
    if not date: date = ''            
    else: date = ' [%s]' % date[0:4]  # Just the 4-digit year in brackets.
    print "%s%s" % (name, date)       # Print name and date.

但是,它没有工作。 有人可以解释为什么我得到这个错误吗?

Traceback (most recent call last):
  File "mql.py", line 29, in <module>
    f = urllib2.urlopen(url)                        # Open the URL as a file.
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 394, in open
    response = self._open(req, data)
  File "C:\Python27\lib\urllib2.py", line 412, in _open
    '_open', req)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 1199, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "C:\Python27\lib\urllib2.py", line 1168, in do_open
    h.request(req.get_method(), req.get_selector(), req.data, headers)
  File "C:\Python27\lib\httplib.py", line 955, in request
    self._send_request(method, url, body, headers)
  File "C:\Python27\lib\httplib.py", line 989, in _send_request
    self.endheaders(body)
  File "C:\Python27\lib\httplib.py", line 951, in endheaders
    self._send_output(message_body)
  File "C:\Python27\lib\httplib.py", line 811, in _send_output
    self.send(msg)
  File "C:\Python27\lib\httplib.py", line 773, in send
    self.connect()
  File "C:\Python27\lib\httplib.py", line 754, in connect
    self.timeout, self.source_address)
  File "C:\Python27\lib\socket.py", line 562, in create_connection
    sock.connect(sa)

还有一件事,我正在使用python2.7,我没有任何互联网设置的特殊代理配置。

原网址
A:

api.freebase.com已停用,Python客户端库从未更新以与新端点一起使用。

所有回答

共 1 条

author avatar

如果您可以将代码包含在try-except块中,则会更好,如下所示:

try:
   #all the logic to create a URL and store in a variable say url for MQLReader service 
   invoke urllib2.urlopen(url)
   #perform other processing.
except urllib2.URLError, e:
    print str(e)

这会给你一个关于出了什么问题的想法。 我试过你的代码示例,我得到一个错误说: 连接尝试失败,因为连接方在一段时间后未正确响应,或建立连接失败,因为连接的主机未能响应

因此,捕获异常并检查它将为您提供问题的根本原因。

相似问题