uploading content to Metaweb

[ permalink ] [ download ]
import urllib2       # Higher-level URL content fetching
import simplejson    # JSON serialization and parsing

host = 'sandbox.freebase.com'           # The Metaweb host
uploadservice = '/api/service/upload'   # Path to upload service

# Upload the specified content (and give it the specified type).
# Return the guid of the /type/content object that represents it.
# The returned guid can be used to retrieve the content with /api/trans/raw.
def upload(content, type, credentials):
    # This is the URL we POST content to 
    url = 'http://%s%s'%(host,uploadservice)
    # Build the HTTP request
    req = urllib2.Request(url, content)         # URL and content to POST
    req.add_header('Content-Type', type)        # Content type header
    req.add_header('Cookie', credentials)       # Authentication header
    req.add_header('X-Metaweb-Request', 'True') # Guard against XSS attacks
    try:
        f = urllib2.urlopen(req)                # POST the request
        response = simplejson.load(f)           # Parse the response
        return response['result']['id']         # Extract and return content id
    except urllib2.HTTPError, e:
        if e.code == 400:                               # For code 400:
            body = simplejson.load(e)                   # parse the response
            raise MQLError(body['messages'][0]['text']) # to get error message
        else:  # For any other error,  report code and response body
            raise MQLError('HTTP Error %d:\n%s' % (e.code, e.read()))
hits counter