# 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 ''


import cgi
import cgitb; cgitb.enable()
import urllib
import sys
import re
from cachedfetch import cachedFetch

def main():
    form = cgi.FieldStorage()
    if (not form.has_key("title")):
      print 'Content-Type: text/plain'
      print ''
      print 'No title specified!'
      return

    title = form["title"].value

    querystring = urllib.urlencode([('titles', title)])
    url = "http://en.wikipedia.org/w/api.php?action=query&format=yaml&prop=info&" + querystring

# 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: wparticleexists.py
import cgi
import cgitb; cgitb.enable()
import urllib
import sys
import re
from cachedfetch import cachedFetch


def main():
    form = cgi.FieldStorage()
    if (not form.has_key("title")):
      print 'Content-Type: text/plain'
      print ''
      print 'No title specified!'
      return

    title = form["title"].value

    querystring = urllib.urlencode([('titles', title)])
    url = "http://en.wikipedia.org/w/api.php?action=query&format=yaml&prop=info&" + querystring

    data = cachedFetch(url, 3600)