Esempio n. 1
0
def morsel_to_cookie(morsel):
    """Convert a Morsel object into a Cookie containing the one k/v pair."""

    expires = None
    if morsel['max-age']:
        try:
            expires = int(time.time() + int(morsel['max-age']))
        except ValueError:
            raise TypeError('max-age: %s must be integer' % morsel['max-age'])
    elif morsel['expires']:
        time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
        expires = countCalendarEx.timegm(
            time.strptime(morsel['expires'], time_template)
        )
    return create_cookie(
        comment=morsel['comment'],
        comment_url=bool(morsel['comment']),
        discard=False,
        domain=morsel['domain'],
        expires=expires,
        name=morsel.key,
        path=morsel['path'],
        port=None,
        rest={'HttpOnly': morsel['httponly']},
        rfc2109=False,
        secure=bool(morsel['secure']),
        value=morsel.value,
        version=morsel['version'] or 0,
    )
Esempio n. 2
0
def parse_http_date(date):
    """
    Parse a date format as specified by HTTP RFC7231 section 7.1.1.1.

    The three formats allowed by the RFC are accepted, even if only the first
    one is still in widespread use.

    Return an integer expressed in seconds since the epoch, in UTC.
    """
    # email.utils.parsedate() does the job for RFC1123 dates; unfortunately
    # RFC7231 makes it mandatory to support RFC850 dates too. So we roll
    # our own RFC-compliant parsing.
    for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE:
        m = regex.match(date)
        if m is not None:
            break
    else:
        raise ValueError("%r is not in a valid HTTP date format" % date)
    try:
        year = int(m.group('year'))
        if year < 100:
            if year < 70:
                year += 2000
            else:
                year += 1900
        month = MONTHS.index(m.group('mon').lower()) + 1
        day = int(m.group('day'))
        hour = int(m.group('hour'))
        min = int(m.group('min'))
        sec = int(m.group('sec'))
        result = datetime.datetime(year, month, day, hour, min, sec)
        return countCalendarEx.timegm(result.utctimetuple())
    except Exception as exc:
        raise ValueError("%r is not a valid date" % date) from exc
Esempio n. 3
0
 def __call__(self, request, *args, **kwargs):
     try:
         obj = self.get_object(request, *args, **kwargs)
     except ObjectDoesNotExist:
         raise Http404('Feed object does not exist.')
     feedgen = self.get_feed(obj, request)
     response = HttpResponse(content_type=feedgen.content_type)
     if hasattr(self, 'item_pubdate') or hasattr(self, 'item_updateddate'):
         # if item_pubdate or item_updateddate is defined for the feed, set
         # header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED
         response['Last-Modified'] = http_date(
             timegm(feedgen.latest_post_date().utctimetuple()))
     feedgen.write(response, 'utf-8')
     return response
Esempio n. 4
0
def sitemap(request,
            sitemaps,
            section=None,
            template_name='sitemap.xml',
            content_type='application/xml'):

    req_protocol = request.scheme
    req_site = get_current_site(request)

    if section is not None:
        if section not in sitemaps:
            raise Http404("No sitemap available for section: %r" % section)
        maps = [sitemaps[section]]
    else:
        maps = sitemaps.values()
    page = request.GET.get("p", 1)

    lastmod = None
    all_sites_lastmod = True
    urls = []
    for site in maps:
        try:
            if callable(site):
                site = site()
            urls.extend(
                site.get_urls(page=page, site=req_site, protocol=req_protocol))
            if all_sites_lastmod:
                site_lastmod = getattr(site, 'latest_lastmod', None)
                if site_lastmod is not None:
                    site_lastmod = (site_lastmod.utctimetuple() if isinstance(
                        site_lastmod, datetime.datetime) else
                                    site_lastmod.timetuple())
                    lastmod = site_lastmod if lastmod is None else max(
                        lastmod, site_lastmod)
                else:
                    all_sites_lastmod = False
        except EmptyPage:
            raise Http404("Page %s empty" % page)
        except PageNotAnInteger:
            raise Http404("No page '%s'" % page)
    response = TemplateResponse(request,
                                template_name, {'urlset': urls},
                                content_type=content_type)
    if all_sites_lastmod and lastmod is not None:
        # if lastmod is defined for all sites, set header so as
        # ConditionalGetMiddleware is able to send 304 NOT MODIFIED
        response['Last-Modified'] = http_date(timegm(lastmod))
    return response
Esempio n. 5
0
 def get_last_modified():
     if last_modified_func:
         dt = last_modified_func(request, *args, **kwargs)
         if dt:
             return timegm(dt.utctimetuple())
Esempio n. 6
0
 def U(self):
     "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
     if isinstance(self.data, datetime.datetime) and is_aware(self.data):
         return int(countCalendarEx.timegm(self.data.utctimetuple()))
     else:
         return int(time.mktime(self.data.timetuple()))