summaryrefslogtreecommitdiff
path: root/jfr_playoff/remote.py
blob: 54031a8f94cee3b804fda76c05ee6701d51e6b68 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import re, urlparse

import requests

from bs4 import BeautifulSoup as bs
from jfr_playoff.logger import PlayoffLogger

class RemoteUrl:

    url_cache = {}

    @classmethod
    def fetch_raw(cls, url, gzip_fallback=False):
        PlayoffLogger.get('remote').info(
            'fetching content for: %s', url)
        if url not in cls.url_cache:
            request = requests.get(url)
            if request.status_code == 404 and gzip_fallback:
                old_url = urlparse.urlparse(url)
                new_url = old_url._replace(path=old_url.path+'.gz')
                new_url = urlparse.urlunparse(new_url)
                PlayoffLogger.get('remote').info(
                    'URL %s not found, trying GZIP variant %s',
                    url, new_url)
                request = requests.get(url)
            encoding_match = re.search(
                'content=".*;( )?charset=(.*?)"',
                request.content, re.IGNORECASE)
            if encoding_match:
                PlayoffLogger.get('remote').debug(
                    'Content encoding: %s',
                    encoding_match.group(2))
                request.encoding = encoding_match.group(2)
            cls.url_cache[url] = request.text
            PlayoffLogger.get('remote').info(
                'fetched %d bytes from remote location',
                len(cls.url_cache[url]))
        return cls.url_cache[url]

    @classmethod
    def fetch(cls, url):
        return bs(RemoteUrl.fetch_raw(url), 'lxml')

    @classmethod
    def clear_cache(cls):
        cls.url_cache = {}