Freebase python

2019-04-17 08:33发布

I tried this python example from freebase and run it in my windows and ubuntu machine.

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.

However, it did not work. Could someone explain it why i got this error?

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)

One more thing, I am using python 2.7 and i don't have any special proxy configuration for the internet setting.

2条回答
ゆ 、 Hurt°
2楼-- · 2019-04-17 09:13

It would be better if you can enclose your code within a try-except block as below:

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)

This will give you an idea about what is going wrong. I tried your code sample and I get an error saying that: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

Hence catching the exception and examining it will give you the root cause of the problem.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-04-17 09:20

api.freebase.com has been retired and the Python client library was never updated to work with the new endpoint.

查看更多
登录 后发表回答