How to use the wsgiref.handlers.format_date_time function in wsgiref

To help you get started, we’ve selected a few wsgiref examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github tylerlong / everblog / everblog / blueprints / blog_entry.py View on Github external
def lang_feed(lang):
    """generate atom feed for blog entries in the specific language"""
    blog_entries = db.session.query(BlogEntry).filter_by(lang = lang).order_by(BlogEntry.created.desc()).limit(PAGE_SIZE)
    updated = blog_entries.first().created if blog_entries.count() > 0 else ''

    etag = '"{0}"'.format(hashlib.sha256(str(updated)).hexdigest())
    if request.headers.get('If-None-Match', '') == etag:
        return '', 304
    last_modified = format_date_time(mktime(updated.timetuple()))
    if request.headers.get('If-Modified-Since', '') == last_modified:
        return '', 304

    title = app.config['BLOG_OWNER'] + "'s Thoughts and Writings"
    if lang == 'cn':
        title = app.config['BLOG_OWNER'] + u'的博客'
    feed = AtomFeed(title = title, 
                    url = request.url_root, 
                    feed_url = request.url, 
                    author = app.config['BLOG_OWNER'])
    if updated:
        feed.updated = updated
    for blog_entry in blog_entries:
        feed.add(title = blog_entry.title, 
                 content = unicode(blog_entry.content),
                 content_type = 'html',
github CyanogenMod / android_external_webkit / Tools / Scripts / webkitpy / tool / commands / rebaselineserver.py View on Github external
def _serve_file(self, file_path, cacheable_seconds=0):
        if not os.path.exists(file_path):
            self.send_error(404, "File not found")
            return
        with codecs.open(file_path, "rb") as static_file:
            self.send_response(200)
            self.send_header("Content-Length", os.path.getsize(file_path))
            mime_type, encoding = mimetypes.guess_type(file_path)
            if mime_type:
                self.send_header("Content-type", mime_type)

            if cacheable_seconds:
                expires_time = (datetime.datetime.now() +
                    datetime.timedelta(0, cacheable_seconds))
                expires_formatted = format_date_time(
                    time.mktime(expires_time.timetuple()))
                self.send_header("Expires", expires_formatted)
            self.end_headers()

            shutil.copyfileobj(static_file, self.wfile)
github newsapps / p2p-python / p2p / __init__.py View on Github external
def get_multi_content_items(self, ids, query=None, force_update=False):
        """
        Get a bunch of content items at once. We need to use the content items
        ids to use this API call.

        The API only allows 25 items to be requested at once, so this function
        breaks the list of ids into groups of 25 and makes multiple API calls.

        Takes an optional `query` parameter which is dictionary containing
        parameters to pass along in the API call. See the P2P API docs
        for details on parameters.
        """
        ret = list()
        ids_query = list()
        if_modified_since = format_date_time(
            mktime(datetime(2000, 1, 1).utctimetuple()))

        if not query:
            query = self.default_content_item_query

        # Pull as many items out of cache as possible
        ret = [
            self.cache.get_content_item(
                id=i, query=query) for i in ids
        ]
        assert len(ids) == len(ret)

        # Go through what we had in cache and see if we need to
        # retrieve anything
        for i in range(len(ret)):
            if ret[i] is None:
github CyanogenMod / android_external_webkit / WebKitTools / Scripts / webkitpy / tool / commands / rebaselineserver.py View on Github external
def _serve_file(self, file_path, cacheable_seconds=0):
        if not os.path.exists(file_path):
            self.send_error(404, "File not found")
            return
        with codecs.open(file_path, "rb") as static_file:
            self.send_response(200)
            self.send_header("Content-Length", os.path.getsize(file_path))
            mime_type, encoding = mimetypes.guess_type(file_path)
            if mime_type:
                self.send_header("Content-type", mime_type)

            if cacheable_seconds:
                expires_time = (datetime.datetime.now() +
                    datetime.timedelta(0, cacheable_seconds))
                expires_formatted = format_date_time(
                    time.mktime(expires_time.timetuple()))
                self.send_header("Expires", expires_formatted)
            self.end_headers()

            shutil.copyfileobj(static_file, self.wfile)
github google / rekall / rekall-agent / rekall_agent / locations / cloud.py View on Github external
def _get_parameters(self, if_modified_since=None, generation=None, **_):
        """Calculates the params for the request."""
        base_url = self.to_path()

        url_endpoint = ('https://storage.googleapis.com/%s' % base_url)

        headers = self.headers.to_primitive(False)
        headers["Authorization"] = (
            "Bearer " + self._config.server.service_account.oauth_token)
        headers["Cache-Control"] = "private"
        if if_modified_since:
            headers["If-Modified-Since"] = handlers.format_date_time(
                if_modified_since)

        params = {}
        generation = generation or self.generation
        if generation:
            params["generation"] = generation

        return url_endpoint, params, headers, base_url
github newsapps / p2p-python / p2p / __init__.py View on Github external
def http_headers(self, content_type=None, if_modified_since=None):
        h = {'Authorization': 'Bearer %(P2P_API_KEY)s' % self.config}

        if content_type is not None:
            h['content-type'] = content_type

        if type(if_modified_since) == datetime:
            h['If-Modified-Since'] = format_date_time(
                mktime(if_modified_since.utctimetuple()))
        elif if_modified_since is not None:
            h['If-Modified-Since'] = if_modified_since

        return h
github django-tastypie / django-tastypie / tastypie / resources.py View on Github external
``Resource._meta``.
        """
        identifier = self._meta.authentication.get_identifier(request)

        # Check to see if they should be throttled.
        throttle = self._meta.throttle.should_be_throttled(identifier)

        if throttle:
            # Throttle limit exceeded.

            response = http.HttpTooManyRequests()

            if isinstance(throttle, int) and not isinstance(throttle, bool):
                response['Retry-After'] = throttle
            elif isinstance(throttle, datetime):
                response['Retry-After'] = format_date_time(mktime(throttle.timetuple()))

            raise ImmediateHttpResponse(response=response)
github evilhero / mylar / mylar / search.py View on Github external
#logger.fdebug('dateconv of : ' + str(dateconv))
                        # convert it to a numeric time, then subtract the timezone difference (+/- GMT)
                        if dateconv[-1] is not None:
                            postdate_int = time.mktime(dateconv[:len(dateconv)-1]) - dateconv[-1]
                        else:
                            postdate_int = time.mktime(dateconv[:len(dateconv)-1])
                        #logger.fdebug('postdate_int of : ' + str(postdate_int))
                        #logger.fdebug('Issue date of : ' + str(stdate))
                        #convert it to a Thu, 06 Feb 2014 00:00:00 format
                        issue_convert = datetime.datetime.strptime(stdate.rstrip(), '%Y-%m-%d')
                        #logger.fdebug('issue_convert:' + str(issue_convert))
                        #issconv = issue_convert.strftime('%a, %d %b %Y %H:%M:%S')
                        # to get past different locale's os-dependent dates, let's convert it to a generic datetime format
                        stamp = time.mktime(issue_convert.timetuple())
                        #logger.fdebug('stamp: ' + str(stamp))
                        issconv = format_date_time(stamp)
                        #logger.fdebug('issue date is :' + str(issconv))
                        #convert it to a tuple
                        econv = email.utils.parsedate_tz(issconv)
                        #logger.fdebug('econv:' + str(econv))
                        #convert it to a numeric and drop the GMT/Timezone
                        issuedate_int = time.mktime(econv[:len(econv)-1])
                        #logger.fdebug('issuedate_int:' + str(issuedate_int))
                        if postdate_int < issuedate_int:
                            logger.fdebug(str(pubdate) + ' is before store date of ' + str(stdate) + '. Ignoring search result as this is not the right issue.')
                            continue
                        else:
                            logger.fdebug(str(pubdate) + ' is after store date of ' + str(stdate))

# -- end size constaints.
github kura / blackhole / blackhole / http / response.py View on Github external
def date(self):
        now = datetime.datetime.now()
        stamp = time.mktime(now.timetuple())
        return format_date_time(stamp)