root/lang/python/webSimple/webSimple.py

Revision 10135, 1.9 kB (checked in by mattn, 5 months ago)

lang/python/webSimple/webSimple.py:

  • ヘッダに対応(Basic認証等に使用)
Line 
1#!-*- coding:utf-8 -*-
2import urllib
3import urllib2
4from urlparse import urlparse, urlunparse
5from xml.dom import minidom
6import xmllib
7#import logging
8
9use_google_api = False
10try:
11  from google.appengine.api import urlfetch
12  use_google_api = True
13except:
14  pass
15
16use_simplexml = False
17try:
18  import elementtree.SimpleXMLTreeBuilder as xmlbuilder
19  use_simplexml = True
20except:
21  pass
22
23class 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
38class 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())
Note: See TracBrowser for help on using the browser.