Beispiel #1
0
def read(url):
    try:
        headers = {'User-Agent': 'Hacker News Reader (' + settings.DOMAIN_URL + ')'}
        cookies = None
        request = get_request()
        if request and 'usercookie' in request.session:
            cookies = {'user': request.session['usercookie']}
        try:
            r = requests.get('https://news.ycombinator.com/' + url, headers=headers, cookies=cookies, timeout=5)
        except (requests.exceptions.Timeout, requests.exceptions.SSLError) as e:
            raise utils.ShowAlert('Connection to news.ycombinator.com timed out')
        if re.match(r'^We\'ve limited requests for old items', r.text):
            raise utils.ShowAlert('Requests have been limited for old items. It might take a while before you can access this.')
        elif re.match(r'^We\'ve limited requests for this url', r.text):
            raise utils.ShowAlert('Requests have been limited for this page. It might take a while before you can access this.')
        elif re.match(r'^No such user.$', r.text):
            raise utils.ShowAlert('No such user.')
        elif re.match(r'^No such item.$', r.text):
            raise utils.ShowAlert('Item not found')
        elif re.match(r'^((?!<body>).)*$', r.text):
            raise utils.ShowAlert('Hacker News is either not working or parsing failed')
        elif re.match(r'<title>Error</title>', r.text):
            raise utils.ShowAlert('Hacker News is down')
    except requests.HTTPError:
        raise utils.ShowAlert('Could not connect to news.ycombinator.com, try again later.<br>\
            If this error persists please contact the developer.')
    return BeautifulSoup(r.text, from_encoding='utf-8')
Beispiel #2
0
    def get(self, *args, **kwargs):
        """
            This is a very limited version of the Manager.get(). It only retrieves
            a single record.
        """
        # only two options supported record_id= or carenet_id=
        record_id = kwargs.get('record_id')
        carenet_id = kwargs.get('carenet_id')
        assert record_id or carenet_id

        request = get_request()

        sessionkey = _sessionkey(record_id, carenet_id)
        session = request.session.get(sessionkey)
        client = get_indivo_client(request,
                                   with_session_token=False,
                                   token=session['access_token'])

        # I am using JSON to get the data from the server. I could also use XML.
        # The content of the GET document is totally different from the content of the PUT document.
        # Therefore there is no possibility of streamlineing the PUT and the GET stages.

        if record_id:
            resp, content = client.read_demographics(
                record_id=record_id,
                body={"response_format": "application/json"})
            if resp['status'] != '200':
                raise Exception("Error fetching demographics from record: %s" %
                                record_id)
        else:
            resp, content = client.read_demographics_carenet(
                carenet_id=carenet_id,
                body={"response_format": "application/json"})
            if resp['status'] != '200':
                raise Exception(
                    "Error fetching demographics from carenet: %s" %
                    carenet_id)

        data = json.loads(content)[0]
        o = self.model()
        o.carenet_id = carenet_id
        o.record_id = record_id
        if record_id:
            o._is_record = True
            o._is_carenet = False
        else:
            o._is_record = False
            o._is_carenet = True
        for k, v in data.items():
            if k != '__documentid__':
                setattr(o, k, v)
        return o
Beispiel #3
0
    def award_to(self, user, ignore_message=False):
        request = get_request()
        if request is None or request.user != user:
            return False
        has_badge = user.badges.filter(id=self.id).exists()
        if self.meta_badge.one_time_only and has_badge:
            return False
        if self.meta_badge.get_progress_percentage(user=user) < 100:
            return False

        BadgeToUser.objects.create(badge=self, user=user)

        badge_awarded.send(sender=self.meta_badge, user=user, badge=self)

        if not ignore_message:
            message_template = _(u"You just got the %s Badge!")
            if request is not None:
                messages.info(request, message_template % self.title)

        return BadgeToUser.objects.filter(badge=self, user=user).count()
Beispiel #4
0
    def award_to(self, user, ignore_message=False):
        request = get_request()
        if request is None or request.user != user:
            return False
        has_badge = user.badges.filter(id=self.id).exists()
        if self.meta_badge.one_time_only and has_badge:
            return False
        if self.meta_badge.get_progress_percentage(user=user) < 100:
            return False

        BadgeToUser.objects.create(badge=self, user=user)

        badge_awarded.send(sender=self.meta_badge, user=user, badge=self)

        if not ignore_message:
            message_template = _(u"You just got the %s Badge!")
            if request is not None:
                messages.info(request, message_template % self.title)

        return BadgeToUser.objects.filter(badge=self, user=user).count()
Beispiel #5
0
def read(url):
    try:
        headers = {
            'User-Agent': 'Hacker News Reader (' + settings.DOMAIN_URL + ')'
        }
        cookies = None
        request = get_request()
        if request and 'usercookie' in request.session:
            cookies = {'user': request.session['usercookie']}
        try:
            r = requests.get('https://news.ycombinator.com/' + url,
                             headers=headers,
                             cookies=cookies,
                             timeout=5)
        except (requests.exceptions.Timeout,
                requests.exceptions.SSLError) as e:
            raise utils.ShowAlert(
                'Connection to news.ycombinator.com timed out')
        if re.match(r'^We\'ve limited requests for old items', r.text):
            raise utils.ShowAlert(
                'Requests have been limited for old items. It might take a while before you can access this.'
            )
        elif re.match(r'^We\'ve limited requests for this url', r.text):
            raise utils.ShowAlert(
                'Requests have been limited for this page. It might take a while before you can access this.'
            )
        elif re.match(r'^No such user.$', r.text):
            raise utils.ShowAlert('No such user.')
        elif re.match(r'^No such item.$', r.text):
            raise utils.ShowAlert('Item not found')
        elif re.match(r'^((?!<body>).)*$', r.text):
            raise utils.ShowAlert(
                'Hacker News is either not working or parsing failed')
        elif re.match(r'<title>Error</title>', r.text):
            raise utils.ShowAlert('Hacker News is down')
    except requests.HTTPError:
        raise utils.ShowAlert(
            'Could not connect to news.ycombinator.com, try again later.<br>\
            If this error persists please contact the developer.')
    return BeautifulSoup(r.text, from_encoding='utf-8')
Beispiel #6
0
    def save(self):
        carenet_id = self.carenet_id
        record_id = self.record_id
        assert record_id != None
        # Problem - XML format required
        d = self.to_xml()
        sessionkey = _sessionkey(record_id, carenet_id)
        request = get_request()
        session = request.session.get(sessionkey)
        client = get_indivo_client(request,
                                   with_session_token=False,
                                   token=session['access_token'])

        if record_id:
            resp, content = client.set_demographics(record_id=record_id,
                                                    body=d)
            if resp['status'] != '200':
                logger.error(
                    "Error %s updating demographics from record (%s): %s\n%s" %
                    (resp['status'], record_id, content, d.replace(
                        "><", ">\n<")))
                raise Exception(
                    "Error %s updating demographics from record (%s): %s" %
                    (resp['status'], record_id, content))
Beispiel #7
0
def test_request_available(request):
    thread_request = middleware.get_request()
    if thread_request == request:
        return HttpResponse('OK')
    return HttpResponseNotFound()