# Path: cachedfetch.py
# def cachedFetch(url, expiretime=3600, maxlength=100000):    # fetch url, with memcache
#     # Enable this to effectively clear memcache on new version deployment
#     #key = os.environ['CURRENT_VERSION_ID'] + '/' + url
#     key = url
#     data = memcache.get(key)
#     if data is not None:
#         #print >> sys.stderr, "From memcache: " + url 
#         return data
#     else:
#         #print >> sys.stderr, "From fetch: " + url
#         try:
#             result = urllib2.urlopen(url)
#             data = result.read(maxlength)
#             result.close()
#             memcache.add(key, data, expiretime)
#             return data
#         except urllib2.URLError, e:
#             return ''
#         except DownloadError:
#             return ''


from cachedfetch import cachedFetch
from django.utils import simplejson as json
import urllib
import sys

def getRedirectTarget(title):
    querystring = urllib.urlencode({'action': 'query',
                                    'format': 'json',
                                    'redirects': '1',
                                    'titles':title})
    url = "http://en.wikipedia.org/w/api.php?" + querystring
    #url = "http://en.wikipedia.org/w/api.php?action=query&prop=info&titles=appspot.com&redirects&format=json"
    #print >> sys.stderr, "url: " + url 

# Path: cachedfetch.py
# def cachedFetch(url, expiretime=3600, maxlength=100000):    # fetch url, with memcache
#     # Enable this to effectively clear memcache on new version deployment
#     #key = os.environ['CURRENT_VERSION_ID'] + '/' + url
#     key = url
#     data = memcache.get(key)
#     if data is not None:
#         #print >> sys.stderr, "From memcache: " + url 
#         return data
#     else:
#         #print >> sys.stderr, "From fetch: " + url
#         try:
#             result = urllib2.urlopen(url)
#             data = result.read(maxlength)
#             result.close()
#             memcache.add(key, data, expiretime)
#             return data
#         except urllib2.URLError, e:
#             return ''
#         except DownloadError:
#             return ''


# Path: RedirectTarget.py
from cachedfetch import cachedFetch
from django.utils import simplejson as json
import urllib
import sys


def getRedirectTarget(title):
    querystring = urllib.urlencode({'action': 'query',
                                    'format': 'json',
                                    'redirects': '1',
                                    'titles':title})
    url = "http://en.wikipedia.org/w/api.php?" + querystring
    #url = "http://en.wikipedia.org/w/api.php?action=query&prop=info&titles=appspot.com&redirects&format=json"
    #print >> sys.stderr, "url: " + url 

    jsonstring = cachedFetch(url, 3600)