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
25import urllib.request, urllib.error, urllib.parse
26import urllib.parse
27
28class _Request( urllib.request.Request ):
29 timeout = None
30 def open(self):
31 if self.timeout:
32 return urllib.request.urlopen(self, None, self.timeout)
33 return urllib.request.urlopen(self)
34
35class _RequestFactory( object ):
36 def __init__(self, baseurl, user_agent, timeout, proxy):
37 self.base_url = baseurl
38 self.user_agent = user_agent
39 self.timeout = timeout
40 self.proxy = proxy
41
42 def __call__(self, *args, **kwargs):
43 return self.new_request(*args, **kwargs)
44
45 def new_request(self, url):
46 url = urllib.parse.urljoin(self.base_url, url)
47 req = _Request(url)
48 req.timeout = self.timeout
49 if self.proxy:
50 req.set_proxy(self.proxy, 'http')
51 if self.user_agent:
52 req.add_header('User-Agent', self.user_agent)
53 return req
54
55_request = None
56
57def ConnSetup(baseurl, user_agent=None, timeout=120, proxy=None):
58 global _request
59 if _request is None:
60 _request = _RequestFactory(baseurl, user_agent, timeout, proxy)
61
62def Request(url=None):
63 global _request
64 if _request is None:
65 raise Exception("Request Factory not yet spawned")
66 if url:
67 return _request(url)
68 return _request.base_url
def __init__(self, baseurl, user_agent, timeout, proxy)
Definition: request.py:36
def ConnSetup(baseurl, user_agent=None, timeout=120, proxy=None)
Definition: request.py:57