| 1 | #!-*- coding:utf-8 -*-
|
|---|
| 2 | import urllib
|
|---|
| 3 | import urllib2
|
|---|
| 4 | from urlparse import urlparse, urlunparse
|
|---|
| 5 | from xml.dom import minidom
|
|---|
| 6 | import xmllib
|
|---|
| 7 |
|
|---|
| 8 | use_google_api = False
|
|---|
| 9 | try:
|
|---|
| 10 | from google.appengine.api import urlfetch
|
|---|
| 11 | use_google_api = True
|
|---|
| 12 | except:
|
|---|
| 13 | pass
|
|---|
| 14 |
|
|---|
| 15 | use_simplexml = False
|
|---|
| 16 | try:
|
|---|
| 17 | import elementtree.SimpleXMLTreeBuilder as xmlbuilder
|
|---|
| 18 | use_simplexml = True
|
|---|
| 19 | except:
|
|---|
| 20 | pass
|
|---|
| 21 |
|
|---|
| 22 | class Response:
|
|---|
| 23 | def __init__(self, content):
|
|---|
| 24 | self.content = content
|
|---|
| 25 |
|
|---|
| 26 | def parse_xml(self):
|
|---|
| 27 | if use_simplexml:
|
|---|
| 28 | parser = xmlbuilder.TreeBuilder()
|
|---|
| 29 | xmllib.XMLParser.__init__(parser, accept_utf8=1)
|
|---|
| 30 | parser.feed(self.content)
|
|---|
| 31 | return parser.close()
|
|---|
| 32 | return minidom.parseString(self.content)
|
|---|
| 33 |
|
|---|
| 34 | def __str__(self):
|
|---|
| 35 | return self.content
|
|---|
| 36 |
|
|---|
| 37 | class Simple:
|
|---|
| 38 | def __init__(self, opt):
|
|---|
| 39 | self.opt = opt
|
|---|
| 40 |
|
|---|
| 41 | def get(self, param = None, opt = None):
|
|---|
| 42 | url_param = urlparse(self.opt['base_url'])
|
|---|
| 43 |
|
|---|
| 44 | query_params = url_param[4]
|
|---|
| 45 | if isinstance(self.opt, dict):
|
|---|
| 46 | if self.opt.has_key('path'):
|
|---|
| 47 | url_param[2] += opt['path']
|
|---|
| 48 | if self.opt.has_key('param'):
|
|---|
| 49 | if len(query_params):
|
|---|
| 50 | query_params += "&"
|
|---|
| 51 | query_params += "%s" % urllib.urlencode(self.opt['param'])
|
|---|
| 52 |
|
|---|
| 53 | if isinstance(param, dict):
|
|---|
| 54 | query_params += "&%s" % urllib.urlencode(param)
|
|---|
| 55 | url = urlunparse(
|
|---|
| 56 | (url_param[0], url_param[1], url_param[2], url_param[3], query_params, url_param[5]))
|
|---|
| 57 |
|
|---|
| 58 | if use_google_api:
|
|---|
| 59 | return Response(urlfetch.fetch(url).content)
|
|---|
| 60 |
|
|---|
| 61 | return Response(urllib2.urlopen(urllib2.Request(url)).read())
|
|---|