MythTV master
request.py
Go to the documentation of this file.
1# -*- coding: utf-8 -*-
2# smolt - Fedora hardware profiler
3#
4# Copyright (C) 2011 Raymond Wagner <sebastian@pipping.org>
5#
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
19
20# This sets up a factory for urllib2.Request objects, automatically
21# providing the base url, user agent, and proxy information.
22# The object returned is slightly modified, with a shortcut to urlopen.
23
24from builtins import object
25
26try:
27 import urllib2 as urllib
28except ImportError:
29 import urllib.request as urllib
30
31try:
32 import urlparse as parse
33except ImportError:
34 from urllib import parse
35
36class _Request( urllib.Request ):
37 timeout = None
38 def open(self):
39 if self.timeout:
40 return urllib.urlopen(self, None, self.timeout)
41 return urllib.urlopen(self)
42
43class _RequestFactory( object ):
44 def __init__(self, baseurl, user_agent, timeout, proxy):
45 self.base_url = baseurl
46 self.user_agent = user_agent
47 self.timeout = timeout
48 self.proxy = proxy
49
50 def __call__(self, *args, **kwargs):
51 return self.new_request(*args, **kwargs)
52
53 def new_request(self, url):
54 url = parse.urljoin(self.base_url, url)
55 req = _Request(url)
56 req.timeout = self.timeout
57 if self.proxy:
58 req.set_proxy(self.proxy, 'http')
59 if self.user_agent:
60 req.add_header('User-Agent', self.user_agent)
61 return req
62
63_request = None
64
65def ConnSetup(baseurl, user_agent=None, timeout=120, proxy=None):
66 global _request
67 if _request is None:
68 _request = _RequestFactory(baseurl, user_agent, timeout, proxy)
69
70def Request(url):
71 global _request
72 if _request is None:
73 raise Exception("Request Factory not yet spawned")
74 return _request(url)
def __init__(self, baseurl, user_agent, timeout, proxy)
Definition: request.py:44
def __call__(self, *args, **kwargs)
Definition: request.py:50
def ConnSetup(baseurl, user_agent=None, timeout=120, proxy=None)
Definition: request.py:65