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