예제 #1
0
파일: httputil.py 프로젝트: kzinglzy/zest
    def set_cookie(self, key, value, path="/", **params):
        """domain=None, path='/',
           expires=None, max_age=None, secure=None,
           httponly=None, comment=None, version=None
        """
        expires = params.get("expires")
        if expires:
            params["expires"] = utc_time(expires)
        max_age = params.get("max_age")
        if max_age and isinstance(max_age, datetime.timedelta):
            params["max_age"] = timedelta_to_seconds(max_age)

        cookie = SimpleCookie({key: value})
        cookie[key]["path"] = path
        for option, v in params.items():
            cookie[key][option.replace("_", "-")] = v

        self.headers.parse_header_line(cookie.output())
예제 #2
0
파일: web.py 프로젝트: kzinglzy/zest
def static_file(name, path, request):
    """ Make a static file response.

    Parameters:
    - name: file name of static file.
    - path: absolute static directory path.
    - request: a `Request` object.

    ## This cool function is inspired by `bottle.static_file` then add a
    async read and write support
    """
    file_path = abspath(join(path, name.strip('/\\')))
    if not os.path.exists(file_path) or not os.path.isfile(file_path):
        raise HTTPError(404, 'File does not exist.')
    if not os.access(file_path, os.R_OK):
        raise HTTPError(403, 'You do not have permission to access this file.')

    headers = {}
    mimetype, encoding = mimetypes.guess_type(file_path)
    if mimetype:
        headers['Content-Type'] = mimetype
    else:
        headers['Content-Type'] = 'application/octet-stream'
        headers['Content-Disposition'] = 'attachment; filename="%s"' % name
    if encoding:
        headers['Content-Encoding'] = encoding

    stats = os.stat(file_path)
    headers['Content-Length'] = stats.st_size
    headers['Last-Modified'] = utc_time(stats.st_mtime)

    ims = request.if_modify_since
    if ims is not None and ims >= int(stats.st_mtime):
        response = Response(headers=headers, status=304)
    else:
        body = ''
        if request.method != 'HEAD':
            loop = request.event_loop
            with open(file_path, 'rb') as file:
                body = yield from AsyncFile(loop=loop, file=file).read()
        response = Response(body, headers)

    return response