当前位置: 首页>>代码示例>>Python>>正文


Python http.http_date函数代码示例

本文整理汇总了Python中werkzeug.http.http_date函数的典型用法代码示例。如果您正苦于以下问题:Python http_date函数的具体用法?Python http_date怎么用?Python http_date使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了http_date函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_send_file_range_request

    def test_send_file_range_request(self, app, client):
        @app.route("/")
        def index():
            return flask.send_file("static/index.html", conditional=True)

        rv = client.get("/", headers={"Range": "bytes=4-15"})
        assert rv.status_code == 206
        with app.open_resource("static/index.html") as f:
            assert rv.data == f.read()[4:16]
        rv.close()

        rv = client.get("/", headers={"Range": "bytes=4-"})
        assert rv.status_code == 206
        with app.open_resource("static/index.html") as f:
            assert rv.data == f.read()[4:]
        rv.close()

        rv = client.get("/", headers={"Range": "bytes=4-1000"})
        assert rv.status_code == 206
        with app.open_resource("static/index.html") as f:
            assert rv.data == f.read()[4:]
        rv.close()

        rv = client.get("/", headers={"Range": "bytes=-10"})
        assert rv.status_code == 206
        with app.open_resource("static/index.html") as f:
            assert rv.data == f.read()[-10:]
        rv.close()

        rv = client.get("/", headers={"Range": "bytes=1000-"})
        assert rv.status_code == 416
        rv.close()

        rv = client.get("/", headers={"Range": "bytes=-"})
        assert rv.status_code == 416
        rv.close()

        rv = client.get("/", headers={"Range": "somethingsomething"})
        assert rv.status_code == 416
        rv.close()

        last_modified = datetime.datetime.utcfromtimestamp(
            os.path.getmtime(os.path.join(app.root_path, "static/index.html"))
        ).replace(microsecond=0)

        rv = client.get(
            "/", headers={"Range": "bytes=4-15", "If-Range": http_date(last_modified)}
        )
        assert rv.status_code == 206
        rv.close()

        rv = client.get(
            "/",
            headers={
                "Range": "bytes=4-15",
                "If-Range": http_date(datetime.datetime(1999, 1, 1)),
            },
        )
        assert rv.status_code == 200
        rv.close()
开发者ID:Warkanlock,项目名称:flask,代码行数:60,代码来源:test_helpers.py

示例2: test_is_resource_modified_for_range_requests

    def test_is_resource_modified_for_range_requests(self):
        env = create_environ()

        env["HTTP_IF_MODIFIED_SINCE"] = http.http_date(datetime(2008, 1, 1, 12, 30))
        env["HTTP_IF_RANGE"] = http.generate_etag(b"awesome_if_range")
        # Range header not present, so If-Range should be ignored
        assert not http.is_resource_modified(
            env,
            data=b"not_the_same",
            ignore_if_range=False,
            last_modified=datetime(2008, 1, 1, 12, 30),
        )

        env["HTTP_RANGE"] = ""
        assert not http.is_resource_modified(
            env, data=b"awesome_if_range", ignore_if_range=False
        )
        assert http.is_resource_modified(
            env, data=b"not_the_same", ignore_if_range=False
        )

        env["HTTP_IF_RANGE"] = http.http_date(datetime(2008, 1, 1, 13, 30))
        assert http.is_resource_modified(
            env, last_modified=datetime(2008, 1, 1, 14, 00), ignore_if_range=False
        )
        assert not http.is_resource_modified(
            env, last_modified=datetime(2008, 1, 1, 13, 30), ignore_if_range=False
        )
        assert http.is_resource_modified(
            env, last_modified=datetime(2008, 1, 1, 13, 30), ignore_if_range=True
        )
开发者ID:pallets,项目名称:werkzeug,代码行数:31,代码来源:test_http.py

示例3: response_formated_records

def response_formated_records(records, collection, of, **kwargs):
    """Return formatter records.

    Response contains correct Cache and TTL information in HTTP headers.
    """
    response = make_response(format_records(records, collection=collection,
                                            of=of, **kwargs))

    response.mimetype = get_output_format_content_type(of)
    current_time = datetime.datetime.now()
    response.headers['Last-Modified'] = http_date(
        time.mktime(current_time.timetuple())
    )
    expires = current_app.config.get(
        'CFG_WEBSEARCH_SEARCH_CACHE_TIMEOUT', None)

    if expires is None:
        response.headers['Cache-Control'] = (
            'no-store, no-cache, must-revalidate, '
            'post-check=0, pre-check=0, max-age=0'
        )
        response.headers['Expires'] = '-1'
    else:
        expires_time = current_time + datetime.timedelta(seconds=expires)
        response.headers['Vary'] = 'Accept'
        response.headers['Cache-Control'] = (
            'public' if current_user.is_guest else 'private'
        )
        response.headers['Expires'] = http_date(time.mktime(
            expires_time.timetuple()
        ))
    return response
开发者ID:jiangmin9,项目名称:invenio,代码行数:32,代码来源:search.py

示例4: default

    def default(self, o):
        """Implement this method in a subclass such that it returns a
        serializable object for ``o``, or calls the base implementation (to
        raise a :exc:`TypeError`).

        For example, to support arbitrary iterators, you could implement
        default like this::

            def default(self, o):
                try:
                    iterable = iter(o)
                except TypeError:
                    pass
                else:
                    return list(iterable)
                return JSONEncoder.default(self, o)
        """
        if isinstance(o, datetime):
            return http_date(o.utctimetuple())
        if isinstance(o, date):
            return http_date(o.timetuple())
        if isinstance(o, uuid.UUID):
            return str(o)
        if hasattr(o, '__html__'):
            return text_type(o.__html__())
        return _json.JSONEncoder.default(self, o)
开发者ID:ChengZhongShen,项目名称:flask,代码行数:26,代码来源:__init__.py

示例5: timemap_link_response

def timemap_link_response(app, mementos, uri_r):
    """Return a 200 TimeMap response.

    :param mementos: A sorted (ascending by date) list of (uri_str,
    datetime_obj) tuples representing a TimeMap.
    :param uri_r: The URI-R of the original resource.
    :return: The ``Response`` object.
    """
    assert len(mementos) >= 1

    # Adds Original, TimeGate and TimeMap links
    original_link = Link(uri_r, rel='original')
    timegate_link = Link(
        url_for('timegate', dict(uri_r=uri_r), force_external=True),
        rel='timegate',
    )
    link_self = Link(
        url_for('timemap', dict(
            response_type='link', uri_r=uri_r
        ), force_external=True),
        rel='self', type='application/link-format',
    )
    json_self = Link(
        url_for('timemap', dict(
            response_type='json', uri_r=uri_r
        ), force_external=True),
        rel='timemap', type='application/json',
    )

    # Sets up first and last relations
    if len(mementos) == 1:
        mementos_links = [Link(mementos[0][0], rel='first last memento',
                               datetime=http_date(mementos[0][1]))]
    else:
        # Browse through Mementos to generate the TimeMap links list
        mementos_links = [
            Link(mementos[0][0], rel='first memento',
                 datetime=http_date(mementos[0][1]))
        ] + [
            Link(uri, rel='memento', datetime=http_date(date))
            for (uri, date) in mementos[1:-1]
        ] + [
            Link(mementos[-1][0], rel='last memento',
                 datetime=http_date(mementos[-1][1]))
        ]

    # Aggregates all link strings and constructs the TimeMap body
    links = [original_link, timegate_link, link_self, json_self]
    links.extend(mementos_links)
    body = ',\n'.join([str(l) for l in links]) + '\n'

    # Builds HTTP Response and WSGI return
    headers = [
        ('Date', http_date(datetime.utcnow())),
        ('Content-Length', str(len(body))),
        ('Content-Type', 'application/link-format'),
        ('Connection', 'close'),
    ]
    return Response(body, headers=headers)
开发者ID:tiborsimko,项目名称:timegate,代码行数:59,代码来源:application.py

示例6: test_send_file_range_request

    def test_send_file_range_request(self):
        app = flask.Flask(__name__)

        @app.route('/')
        def index():
            return flask.send_file('static/index.html', conditional=True)

        c = app.test_client()

        rv = c.get('/', headers={'Range': 'bytes=4-15'})
        assert rv.status_code == 206
        with app.open_resource('static/index.html') as f:
            assert rv.data == f.read()[4:16]
        rv.close()

        rv = c.get('/', headers={'Range': 'bytes=4-'})
        assert rv.status_code == 206
        with app.open_resource('static/index.html') as f:
            assert rv.data == f.read()[4:]
        rv.close()

        rv = c.get('/', headers={'Range': 'bytes=4-1000'})
        assert rv.status_code == 206
        with app.open_resource('static/index.html') as f:
            assert rv.data == f.read()[4:]
        rv.close()

        rv = c.get('/', headers={'Range': 'bytes=-10'})
        assert rv.status_code == 206
        with app.open_resource('static/index.html') as f:
            assert rv.data == f.read()[-10:]
        rv.close()

        rv = c.get('/', headers={'Range': 'bytes=1000-'})
        assert rv.status_code == 416
        rv.close()

        rv = c.get('/', headers={'Range': 'bytes=-'})
        assert rv.status_code == 416
        rv.close()

        rv = c.get('/', headers={'Range': 'somethingsomething'})
        assert rv.status_code == 416
        rv.close()

        last_modified = datetime.datetime.fromtimestamp(os.path.getmtime(
            os.path.join(app.root_path, 'static/index.html'))).replace(
            microsecond=0)

        rv = c.get('/', headers={'Range': 'bytes=4-15',
                                 'If-Range': http_date(last_modified)})
        assert rv.status_code == 206
        rv.close()

        rv = c.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(
            datetime.datetime(1999, 1, 1))})
        assert rv.status_code == 200
        rv.close()
开发者ID:VishvajitP,项目名称:flask,代码行数:58,代码来源:test_helpers.py

示例7: timemap_json_response

def timemap_json_response(app, mementos, uri_r):
    """Creates and sends a timemap response.

    :param mementos: A sorted list of (uri_str, datetime_obj) tuples
    representing a timemap.
    :param uri_r: The URI-R of the original resource.
    :param start_response: WSGI callback function.
    :return: The ``Response`` object.
    """
    assert len(mementos) >= 1

    # Prepares the JSON response by building a dict
    response_dict = {}

    response_dict['original_uri'] = uri_r
    response_dict['timegate_uri'] = url_for(
        'timegate', dict(uri_r=uri_r), force_external=True
    )

    # Browse through Mementos to generate TimeMap links dict list
    mementos_links = [
        {'uri': urlstr, 'datetime': http_date(date)}
        for (urlstr, date) in mementos
    ]

    # Builds up first and last links dict
    firstlink = {'uri': mementos[0][0], 'datetime': http_date(mementos[0][1])}
    lastlink = {'uri': mementos[-1][0], 'datetime': http_date(mementos[-1][1])}

    response_dict['mementos'] = {
        'last': lastlink,
        'first': firstlink,
        'list': mementos_links,
    }

    # Builds self (TimeMap)links dict
    response_dict['timemap_uri'] = {
        'json_format': url_for('timemap', dict(
            response_type='json', uri_r=uri_r
        ), force_external=True),
        'link_format': url_for('timemap', dict(
            response_type='link', uri_r=uri_r
        ), force_external=True),
    }

    # Creates the JSON str from the dict
    response_json = json.dumps(response_dict)

    # Builds HTTP Response and WSGI return
    headers = [
        ('Date', http_date(datetime.utcnow())),
        ('Content-Length', str(len(response_json))),
        ('Content-Type', 'application/json'),
    ]
    return Response(response_json, headers=headers)
开发者ID:tiborsimko,项目名称:timegate,代码行数:55,代码来源:application.py

示例8: __call__

    def __call__(self, environ, start_response):
        cleaned_path = get_path_info(environ)
        if PY2:
            cleaned_path = cleaned_path.encode(sys.getfilesystemencoding())
        # sanitize the path for non unix systems
        cleaned_path = cleaned_path.strip('/')
        for sep in os.sep, os.altsep:
            if sep and sep != '/':
                cleaned_path = cleaned_path.replace(sep, '/')
        path = '/' + '/'.join(x for x in cleaned_path.split('/')
                              if x and x != '..')
        file_loader = None
        for search_path, loader in iteritems(self.exports):
            if search_path == path:
                real_filename, file_loader = loader(None)
                if file_loader is not None:
                    break
            if not search_path.endswith('/'):
                search_path += '/'
            if path.startswith(search_path):
                real_filename, file_loader = loader(path[len(search_path):])
                if file_loader is not None:
                    break
        if file_loader is None or not self.is_allowed(real_filename):
            return self.app(environ, start_response)

        guessed_type = mimetypes.guess_type(real_filename)
        mime_type = guessed_type[0] or self.fallback_mimetype
        f, mtime, file_size = file_loader()

        headers = [('Date', http_date())]
        if self.cache:
            timeout = self.cache_timeout
            etag = self.generate_etag(mtime, file_size, real_filename)
            headers += [
                ('Etag', '"%s"' % etag),
                ('Cache-Control', 'max-age=%d, public' % timeout)
            ]
            if not is_resource_modified(environ, etag, last_modified=mtime):
                f.close()
                start_response('304 Not Modified', headers)
                return []
            headers.append(('Expires', http_date(time() + timeout)))
        else:
            headers.append(('Cache-Control', 'public'))

        headers.extend((
            ('Content-Type', mime_type),
            ('Content-Length', str(file_size)),
            ('Last-Modified', http_date(mtime))
        ))
        start_response('200 OK', headers)
        return wrap_file(environ, f)
开发者ID:0x00xw,项目名称:wooyun,代码行数:53,代码来源:wsgi.py

示例9: _tag

def _tag(value):
    if isinstance(value, tuple):
        return {' t': [_tag(x) for x in value]}
    elif isinstance(value, uuid.UUID):
        return {' u': value.hex}
    elif isinstance(value, bytes):
        return {' b': b64encode(value).decode('ascii')}
    elif callable(getattr(value, '__html__', None)):
        return {' m': text_type(value.__html__())}
    elif isinstance(value, list):
        return [_tag(x) for x in value]
    elif isinstance(value, datetime):
        return {' d': http_date(value)}
    elif isinstance(value, dict):
        return dict((k, _tag(v)) for k, v in iteritems(value))
    elif isinstance(value, str):
        try:
            return text_type(value)
        except UnicodeError:
            from keyes.debughelpers import UnexpectedUnicodeError
            raise UnexpectedUnicodeError(u'A byte string with '
                u'non-ASCII data was passed to the session system '
                u'which can only store unicode strings.  Consider '
                u'base64 encoding your string (String was %r)' % value)
    return value
开发者ID:KinSai1975,项目名称:Keyes.py,代码行数:25,代码来源:signals.py

示例10: home

def home():
    feeds = Feed.query.order_by(Feed.id.desc()).all()
    return jsonify(
        count=len(feeds),
        feeds=[dict(id=f.id, tid=f.tid, text=f.text,
                    created_at=http_date(f.created_at), synced=f.synced)
               for f in feeds])
开发者ID:tualatrix,项目名称:zhejiangair,代码行数:7,代码来源:zhejiangair.py

示例11: default

 def default(self, obj):
     if isinstance(obj, datetime):
         return http_date(obj)
     elif isinstance(obj, ObjectId):
         return str(obj)
     else:
         return json.JSONEncoder.default(self, obj)
开发者ID:Ceasar,项目名称:conmongo,代码行数:7,代码来源:json.py

示例12: fetch_resource

def fetch_resource(resource):
    '''
    Gets the resource using the request library and sets the times of last successful update based on the status code.
    :param resource:
    :return:
    '''
    headers = {}
    if resource.last_succ:
        headers['If-Modified-Since'] = http_date(resource.last_succ)
    if resource.etag:
        headers["If-None-Match"] = resource.etag.encode('ascii')
    resp = requests.get(resource.url, headers=headers)
    resource.last_status_code = resp.status_code
    resource.last_fetch = datetime.datetime.utcnow()
    if resp.status_code == 200:
        resource.document = resp.content
        if "etag" in resp.headers:
            resource.etag = resp.headers.get('etag').decode('ascii')
        else:
            resource.etag = None
        resource.last_succ = datetime.datetime.utcnow()
        resource.last_parsed = None
        resource.last_parse_error = None
    if resp.status_code == 304:
        resource.last_succ = datetime.datetime.utcnow()
    db.session.add(resource)
    return resource
开发者ID:IATI,项目名称:iati-datastore,代码行数:27,代码来源:crawler.py

示例13: _tag

def _tag(value):
    if isinstance(value, tuple):
        return {" t": [_tag(x) for x in value]}
    elif isinstance(value, uuid.UUID):
        return {" u": value.hex}
    elif isinstance(value, bytes):
        return {" b": b64encode(value).decode("ascii")}
    elif callable(getattr(value, "__html__", None)):
        return {" m": text_type(value.__html__())}
    elif isinstance(value, list):
        return [_tag(x) for x in value]
    elif isinstance(value, datetime):
        return {" d": http_date(value)}
    elif isinstance(value, dict):
        return dict((k, _tag(v)) for k, v in iteritems(value))
    elif isinstance(value, str):
        try:
            return text_type(value)
        except UnicodeError:
            raise UnexpectedUnicodeError(
                u"A byte string with "
                u"non-ASCII data was passed to the session system "
                u"which can only store unicode strings.  Consider "
                u"base64 encoding your string (String was %r)" % value
            )
    return value
开发者ID:42only,项目名称:flask,代码行数:26,代码来源:sessions.py

示例14: graphite

def graphite():
    params = {k: request.values.getlist(k) for k in request.values.keys()}
    try:
        response = fetch_remote(
            current_app.config['GRAPHITE_SERVER'],
            method=request.method,
            data=request.data,
            accept=request.headers.get('Accept'),
            params=params,
            timeout=current_app.config['GRAPHITE_TIMEOUT']
        )
        headers = {'Content-Type': response.headers.get('Content-Type')}
        cache_for = int(request.values.get('_cache', 0))
        if cache_for > 0:
            headers['Cache-Control'] = 'private, max-age=' + str(cache_for)
            headers['Expires'] = http_date(datetime.now() + timedelta(seconds=cache_for))
        return make_response((
            response.content,
            response.status_code,
            headers
        ))
    except Exception as e:
        width = request.values.get('width', '400')
        height = request.values.get('height', '200')
        image = IMAGE_TPL.format(
            error=str(e),
            width=width,
            height=height
        )
        return make_response((
            image,
            500,
            {'Content-Type': 'image/svg+xml'}
        ))
开发者ID:TeDomum,项目名称:pdnscontrol,代码行数:34,代码来源:graphite.py

示例15: cache

def cache():
    """Returns a 304 if an If-Modified-Since header or If-None-Match is present. Returns the same as a GET otherwise.
    ---
    tags:
      - Response inspection
    parameters:
      - in: header
        name: If-Modified-Since
      - in: header
        name: If-None-Match
    produces:
      - application/json
    responses:
      200:
        description: Cached response
      304:
        description: Modified

    """
    is_conditional = request.headers.get('If-Modified-Since') or request.headers.get('If-None-Match')

    if is_conditional is None:
        response = view_get()
        response.headers['Last-Modified'] = http_date()
        response.headers['ETag'] = uuid.uuid4().hex
        return response
    else:
        return status_code(304)
开发者ID:Lucretiel,项目名称:httpbin,代码行数:28,代码来源:core.py


注:本文中的werkzeug.http.http_date函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。