]>
git.ipfire.org Git - location/libloc.git/blob - src/python/importer.py
2 ###############################################################################
4 # libloc - A library to determine the location of someone on the Internet #
6 # Copyright (C) 2020 IPFire Development Team <info@ipfire.org> #
8 # This library is free software; you can redistribute it and/or #
9 # modify it under the terms of the GNU Lesser General Public #
10 # License as published by the Free Software Foundation; either #
11 # version 2.1 of the License, or (at your option) any later version. #
13 # This library is distributed in the hope that it will be useful, #
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU #
16 # Lesser General Public License for more details. #
18 ###############################################################################
25 log
= logging
.getLogger("location.importer")
28 class Downloader(object):
32 def set_proxy(self
, url
):
34 Sets a HTTP proxy that is used to perform all requests
36 log
.info("Using proxy %s" % url
)
39 def request(self
, url
, data
=None):
40 req
= urllib
.request
.Request(url
, data
=data
)
44 req
.set_proxy(self
.proxy
, "http")
46 return DownloaderContext(self
, req
)
49 class DownloaderContext(object):
50 def __init__(self
, downloader
, request
):
51 self
.downloader
= downloader
52 self
.request
= request
54 # Save the response object
58 log
.info("Retrieving %s..." % self
.request
.full_url
)
61 self
.response
= urllib
.request
.urlopen(self
.request
)
63 # Log the response headers
64 log
.debug("Response Headers:")
65 for header
in self
.headers
:
66 log
.debug(" %s: %s" % (header
, self
.get_header(header
)))
70 def __exit__(self
, type, value
, traceback
):
75 Makes the object iterable by going through each block
81 line
= body
.readline()
94 return self
.response
.headers
96 def get_header(self
, name
):
98 return self
.headers
.get(name
)
103 Returns a file-like object with the decoded content
106 # Return the response by default