Created
May 11, 2009 06:43
-
-
Save csytan/109893 to your computer and use it in GitHub Desktop.
freebase.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python imports | |
import urllib | |
import urllib2 | |
# Local imports | |
try: | |
import simplejson | |
except ImportError: | |
from django.utils import simplejson | |
MQLREAD_SERVICE = "http://www.freebase.com/api/service/mqlread" | |
WEB_SERVICE = "http://www.freebase.com/view/guid/" | |
SEARCH_SERVICE = "http://www.freebase.com/api/service/search?prefix=" | |
TRANS_SERVICE = "http://www.freebase.com/api/trans/blurb/guid/" | |
IMAGE_SERVICE = "http://www.freebase.com/api/trans/raw/guid/" | |
THUMBNAIL_SERVICE = "http://www.freebase.com/api/trans/image_thumb/guid/" | |
def mql_read(q): | |
env = {'qname':{'query':q}} | |
args = urllib.urlencode({'queries':simplejson.dumps(env)}) | |
url = MQLREAD_SERVICE + '?' + args | |
response = urllib2.urlopen(url).read() | |
result = simplejson.loads(response) | |
return result['qname']['result'] | |
def suggest(prefix, type, limit=10): | |
if prefix: | |
query = [{ | |
"name" : None, | |
"name~=": "^" + prefix + "*", | |
"type" : type, | |
"limit": limit | |
}] | |
else: | |
query = [{ | |
"name" : None, | |
"type" : type, | |
"limit": limit | |
}] | |
results = mql_read(query) | |
return results | |
def get_url(guid): | |
return WEB_SERVICE + guid.lstrip('#') | |
def get_image_url(guid): | |
return IMAGE_SERVICE + guid.lstrip('#') | |
def get_thumbnail_url(guid, width=50, height=60): | |
return THUMBNAIL_SERVICE + guid.lstrip('#') + \ | |
'?mode=fillcrop&maxheight=' + str(height) + \ | |
'&maxwidth=' + str(width) | |
def get_thumbnail_url(guid, width=50, height=60): | |
return THUMBNAIL_SERVICE + guid.lstrip('#') | |
def get_blurb_url(guid, maxlength=250): | |
return TRANS_SERVICE + guid.lstrip("#") + "?maxlength=" + str(maxlength) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment