Python wsgiref.handlers.format_date_time() Examples

The following are 19 code examples of wsgiref.handlers.format_date_time(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module wsgiref.handlers , or try the search function .
Example #1
Source File: http_location.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def _get_parameters(self, if_modified_since=None, **kwargs):
        if not self.path_prefix and not self.base:
            raise IOError("No base URL specified.")

        subpath = self.expand_path(**kwargs)
        if subpath:
            path = utils.join_path(self.path_prefix, subpath)
        else:
            path = self.path_prefix

        if path:
            base_url = _join_url(self.base, path)
        else:
            base_url = self.base

        headers = {
            "Cache-Control": "private",
        }

        if if_modified_since:
            headers["If-Modified-Since"] = handlers.format_date_time(
                if_modified_since)

        return base_url, {}, headers, path 
Example #2
Source File: cloud.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #3
Source File: config.py    From hypercorn with MIT License 6 votes vote down vote up
def response_headers(self, protocol: str) -> List[Tuple[bytes, bytes]]:
        headers = [(b"date", format_date_time(time()).encode("ascii"))]
        if self.include_server_header:
            headers.append((b"server", f"hypercorn-{protocol}".encode("ascii")))

        for alt_svc_header in self.alt_svc_headers:
            headers.append((b"alt-svc", alt_svc_header.encode()))
        if len(self.alt_svc_headers) == 0 and self._quic_bind:
            from aioquic.h3.connection import H3_ALPN

            for version in H3_ALPN:
                for bind in self._quic_bind:
                    port = int(bind.split(":")[-1])
                    headers.append((b"alt-svc", b'%s=":%d"; ma=3600' % (version.encode(), port)))

        return headers 
Example #4
Source File: tts_ws_python3_demo.py    From Python-Code with MIT License 5 votes vote down vote up
def create_url(self):
        url = 'wss://tts-api.xfyun.cn/v2/tts'
        # 生成RFC1123格式的时间戳
        now = datetime.now()
        date = format_date_time(mktime(now.timetuple()))

        # 拼接字符串
        signature_origin = "host: " + "ws-api.xfyun.cn" + "\n"
        signature_origin += "date: " + date + "\n"
        signature_origin += "GET " + "/v2/tts " + "HTTP/1.1"
        # 进行hmac-sha256进行加密
        signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
                                 digestmod=hashlib.sha256).digest()
        signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')

        authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
            self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
        authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
        # 将请求的鉴权参数组合为字典
        v = {
            "authorization": authorization,
            "date": date,
            "host": "ws-api.xfyun.cn"
        }
        # 拼接鉴权参数,生成url
        url = url + '?' + urlencode(v)
        # print("date: ",date)
        # print("v: ",v)
        # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
        # print('websocket url :', url)
        return url 
Example #5
Source File: trio_utils.py    From trinity with MIT License 5 votes vote down vote up
def basic_headers(self) -> Tuple[Tuple[str, bytes], ...]:
        # HTTP requires these headers in all responses (client would do
        # something different here)
        return (
            ("Date", format_date_time(None).encode("ascii")),
            ("Server", self.ident),
        ) 
Example #6
Source File: _serialization.py    From azure-storage-python with MIT License 5 votes vote down vote up
def _add_date_header(request):
    current_time = format_date_time(time())
    request.headers['x-ms-date'] = current_time 
Example #7
Source File: pack_views.py    From st2 with Apache License 2.0 5 votes vote down vote up
def _is_file_changed(self, file_mtime, if_none_match=None, if_modified_since=None):
        # For if_none_match check against what would be the ETAG value
        if if_none_match:
            return repr(file_mtime) != if_none_match

        # For if_modified_since check against file_mtime
        if if_modified_since:
            return if_modified_since != format_date_time(file_mtime)

        # Neither header is provided therefore assume file is changed.
        return True 
Example #8
Source File: _serialization.py    From azure-cosmos-table-python with Apache License 2.0 5 votes vote down vote up
def _add_date_header(request):
    current_time = format_date_time(time())
    request.headers['x-ms-date'] = current_time 
Example #9
Source File: trio-server.py    From h11 with MIT License 5 votes vote down vote up
def basic_headers(self):
        # HTTP requires these headers in all responses (client would do
        # something different here)
        return [
            ("Date", format_date_time(None).encode("ascii")),
            ("Server", self.ident),
        ] 
Example #10
Source File: decorators.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def browser_cache(expires=None):
    """Add Flask cache response headers based on expires in seconds.

    If expires is None, caching will be disabled.
    Otherwise, caching headers are set to expire in now + expires seconds

    Example usage:

    ::

        @app.route('/map')
        @browser_cache(expires=60)
        def index():
            return render_template('index.html')

    """
    from wsgiref.handlers import format_date_time
    from flask import g
    from flask_restx.utils import unpack

    def cache_decorator(view):
        @wraps(view)
        def cache_func(*args, **kwargs):

            resp, code, headers = unpack(view(*args, **kwargs))
            now = datetime.datetime.now()

            headers['Last-Modified'] = format_date_time(time.mktime(now.timetuple()))

            failure = code - 200 >= 100  # this is not a successful answer
            do_not_cache = getattr(g, 'DONOTCACHE', False)

            if expires is None or failure or do_not_cache:
                headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
            else:
                headers['Cache-Control'] = 'private, max-age={}'.format(expires)

            return resp, code, headers
        return cache_func
    return cache_decorator 
Example #11
Source File: decorators.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def browser_cache(expires=None):
    """Add Flask cache response headers based on expires in seconds.

    If expires is None, caching will be disabled.
    Otherwise, caching headers are set to expire in now + expires seconds

    Example usage:

    ::

        @app.route('/map')
        @browser_cache(expires=60)
        def index():
            return render_template('index.html')

    """
    from wsgiref.handlers import format_date_time
    from flask import g
    from flask_restx.utils import unpack

    def cache_decorator(view):
        @wraps(view)
        def cache_func(*args, **kwargs):

            resp, code, headers = unpack(view(*args, **kwargs))
            now = datetime.datetime.now()

            headers['Last-Modified'] = format_date_time(time.mktime(now.timetuple()))

            failure = code - 200 >= 100  # this is not a successful answer
            do_not_cache = getattr(g, 'DONOTCACHE', False)

            if expires is None or failure or do_not_cache:
                headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
            else:
                headers['Cache-Control'] = 'private, max-age={}'.format(expires)

            return resp, code, headers
        return cache_func
    return cache_decorator 
Example #12
Source File: decorators.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def browser_cache(expires=None):
    """Add Flask cache response headers based on expires in seconds.

    If expires is None, caching will be disabled.
    Otherwise, caching headers are set to expire in now + expires seconds

    Example usage:

    ::

        @app.route('/map')
        @browser_cache(expires=60)
        def index():
            return render_template('index.html')

    """
    from wsgiref.handlers import format_date_time
    from flask import g
    from flask_restx.utils import unpack

    def cache_decorator(view):
        @wraps(view)
        def cache_func(*args, **kwargs):

            resp, code, headers = unpack(view(*args, **kwargs))
            now = datetime.datetime.now()

            headers['Last-Modified'] = format_date_time(time.mktime(now.timetuple()))

            failure = code - 200 >= 100  # this is not a successful answer
            do_not_cache = getattr(g, 'DONOTCACHE', False)

            if expires is None or failure or do_not_cache:
                headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
            else:
                headers['Cache-Control'] = 'private, max-age={}'.format(expires)

            return resp, code, headers
        return cache_func
    return cache_decorator 
Example #13
Source File: response.py    From quart with MIT License 5 votes vote down vote up
def date(self, value: datetime) -> None:
        self.headers["Date"] = format_date_time(value.timestamp()) 
Example #14
Source File: new_use.py    From Python-Code with MIT License 5 votes vote down vote up
def create_url(self):
        url = 'wss://tts-api.xfyun.cn/v2/tts'
        # 生成RFC1123格式的时间戳
        now = datetime.now()
        date = format_date_time(mktime(now.timetuple()))

        # 拼接字符串
        signature_origin = "host: " + "ws-api.xfyun.cn" + "\n"
        signature_origin += "date: " + date + "\n"
        signature_origin += "GET " + "/v2/tts " + "HTTP/1.1"
        # 进行hmac-sha256进行加密
        signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
                                 digestmod=hashlib.sha256).digest()
        signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')

        authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
            self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
        authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
        # 将请求的鉴权参数组合为字典
        v = {
            "authorization": authorization,
            "date": date,
            "host": "ws-api.xfyun.cn"
        }
        # 拼接鉴权参数,生成url
        url = url + '?' + urlencode(v)
        # print("date: ",date)
        # print("v: ",v)
        # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
        # print('websocket url :', url)
        return url 
Example #15
Source File: cloud.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def _get_parameters(self, if_modified_since=None):
        base_url = self.to_path()

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

        headers = {"Cache-Control": "private"}
        if if_modified_since:
            headers["If-Modified-Since"] = handlers.format_date_time(
                if_modified_since)

        return url_endpoint, {}, headers, base_url 
Example #16
Source File: response.py    From quart with MIT License 5 votes vote down vote up
def retry_after(self, value: Union[datetime, int]) -> None:
        if isinstance(value, datetime):
            self.headers["Retry-After"] = format_date_time(value.timestamp())
        else:
            self.headers["Retry-After"] = str(value) 
Example #17
Source File: response.py    From quart with MIT License 5 votes vote down vote up
def last_modified(self, value: datetime) -> None:
        self.headers["Last-Modified"] = format_date_time(value.timestamp()) 
Example #18
Source File: response.py    From quart with MIT License 5 votes vote down vote up
def expires(self, value: datetime) -> None:
        self.headers["Expires"] = format_date_time(value.timestamp()) 
Example #19
Source File: pack_views.py    From st2 with Apache License 2.0 4 votes vote down vote up
def get_one(self, ref_or_id, file_path, requester_user, if_none_match=None,
                if_modified_since=None):
        """
            Outputs the content of a specific file in a pack.

            Handles requests:
                GET /packs/views/file/<pack_ref_or_id>/<file path>
        """
        pack_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)

        if not pack_db:
            msg = 'Pack with ref_or_id "%s" does not exist' % (ref_or_id)
            raise StackStormDBObjectNotFoundError(msg)

        if not file_path:
            raise ValueError('Missing file path')

        pack_ref = pack_db.ref

        # Note: Until list filtering is in place we don't require RBAC check for icon file
        permission_type = PermissionType.PACK_VIEW
        if file_path not in WHITELISTED_FILE_PATHS:
            rbac_utils = get_rbac_backend().get_utils_class()
            rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                              resource_db=pack_db,
                                                              permission_type=permission_type)

        normalized_file_path = get_pack_file_abs_path(pack_ref=pack_ref, file_path=file_path)
        if not normalized_file_path or not os.path.isfile(normalized_file_path):
            # Ignore references to files which don't exist on disk
            raise StackStormDBObjectNotFoundError('File "%s" not found' % (file_path))

        file_size, file_mtime = self._get_file_stats(file_path=normalized_file_path)

        response = Response()

        if not self._is_file_changed(file_mtime,
                                     if_none_match=if_none_match,
                                     if_modified_since=if_modified_since):
            response.status = http_client.NOT_MODIFIED
        else:
            if file_size is not None and file_size > MAX_FILE_SIZE:
                msg = ('File %s exceeds maximum allowed file size (%s bytes)' %
                       (file_path, MAX_FILE_SIZE))
                raise ValueError(msg)

            content_type = mimetypes.guess_type(normalized_file_path)[0] or \
                'application/octet-stream'

            response.headers['Content-Type'] = content_type
            response.body = self._get_file_content(file_path=normalized_file_path)

        response.headers['Last-Modified'] = format_date_time(file_mtime)
        response.headers['ETag'] = repr(file_mtime)

        return response