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


Python Headers.add_header方法代码示例

本文整理汇总了Python中wsgiref.headers.Headers.add_header方法的典型用法代码示例。如果您正苦于以下问题:Python Headers.add_header方法的具体用法?Python Headers.add_header怎么用?Python Headers.add_header使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在wsgiref.headers.Headers的用法示例。


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

示例1: parse_http_headers

# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import add_header [as 别名]
def parse_http_headers(environ):
    h = Headers([])
    for k, v in environ.items():
        if k.startswith('HTTP_'):
            name = k[5:]
            h.add_header(name, v)
    return h
开发者ID:minineko,项目名称:test1,代码行数:9,代码来源:utils.py

示例2: testExtras

# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import add_header [as 别名]
    def testExtras(self):
        h = Headers([])
        self.assertEqual(str(h), "\r\n")

        h.add_header("foo", "bar", baz="spam")
        self.assertEqual(h["foo"], 'bar; baz="spam"')
        self.assertEqual(str(h), 'foo: bar; baz="spam"\r\n\r\n')

        h.add_header("Foo", "bar", cheese=None)
        self.assertEqual(h.get_all("foo"), ['bar; baz="spam"', "bar; cheese"])

        self.assertEqual(str(h), 'foo: bar; baz="spam"\r\n' "Foo: bar; cheese\r\n" "\r\n")
开发者ID:van7hu,项目名称:fanca,代码行数:14,代码来源:test_wsgiref.py

示例3: Response

# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import add_header [as 别名]
class Response(threading.local):
    """ Represents a single response using thread-local namespace. """

    def bind(self, app):
        """ Clears old data and creates a brand new Response object """
        self._COOKIES = None
        self.status = 200
        self.header_list = []
        self.header = HeaderWrapper(self.header_list)
        self.charset = 'UTF-8'
        self.content_type = 'text/html; charset=UTF-8'
        self.error = None
        self.app = app

    def add_header(self, key, value):
        self.header.add_header(key.title(), str(value))

    def wsgiheaders(self):
        ''' Returns a wsgi conform list of header/value pairs '''
        for c in self.COOKIES.values():
            self.add_header('Set-Cookie', c.OutputString())
        return self.header_list

    @property
    def COOKIES(self):
        if not self._COOKIES:
            self._COOKIES = SimpleCookie()
        return self._COOKIES

    def set_cookie(self, key, value, **kargs):
        """
        Sets a Cookie. Optional settings:
        expires, path, comment, domain, max-age, secure, version, httponly
        """
        if not isinstance(value, basestring):
            sec = self.app.config['securecookie.key']
            value = cookie_encode(value, sec)
        self.COOKIES[key] = value
        for k, v in kargs.iteritems():
            self.COOKIES[key][k] = v

    def get_content_type(self):
        """ Get the current 'Content-Type' header. """
        return self.header['Content-Type']
        
    def set_content_type(self, value):
        if 'charset=' in value:
            self.charset = value.split('charset=')[-1].split(';')[0].strip()
        self.header['Content-Type'] = value

    content_type = property(get_content_type, set_content_type, None,
                            get_content_type.__doc__)
开发者ID:RedBeard0531,项目名称:bottle,代码行数:54,代码来源:bottle.py

示例4: __call__

# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import add_header [as 别名]
    def __call__(self, environ, start_response):
        key_morsel = Cookie(environ.get("HTTP_COOKIE", "")).get(self.toggle_key)
        # useful vars
        query = query_str2dict(environ.get("QUERY_STRING"))
        enable_by_cookie = key_morsel.value == self.enable_value if key_morsel else False
        enable_by_query = query.get(self.toggle_key) == self.enable_value
        # pop toggle_key from query dic to avoid case: '?_profile=on&_profile='
        disable = query.pop(self.toggle_key, None) == ""  # only can be disabled by query
        enable = not disable and (enable_by_query or enable_by_cookie)

        run_app, resp_body, saved_ss_args = self._intercept_call()

        # processing cookies and queries
        so = query.pop(self.SIMPLE_OUTPUT_TOGGLE_KEY, None)
        if so is not None:
            self.simple_output = so == "True"
        cookie_to_set = None
        if enable_by_query and not enable_by_cookie:
            cookie_to_set = "%s=%s; Path=/; HttpOnly" % (self.toggle_key, self.enable_value)
        elif disable:
            cookie_to_set = "%s=; Path=/; Max-Age=1; HttpOnly" % self.toggle_key

        if enable:
            start = time.time()
            profile = Profile()
            profile.runcall(run_app, environ)  # here we call the WSGI app
            elapsed = time.time() - start
        else:
            profile = elapsed = None  # for annoying IDE
            run_app(environ)

        status, headers = saved_ss_args[:2]
        headers_dic = Headers(headers)
        if cookie_to_set:
            headers_dic.add_header("Set-Cookie", cookie_to_set)

        # insert result into response
        content_type = headers_dic.get("Content-Type", "")
        if enable and status.startswith("200") and content_type.startswith("text/html"):
            environ["QUERY_STRING"] = dict2query_str(query)

            matched = _find_charset.match(content_type)
            encoding = matched.group(1) if matched else "ascii"
            rendered = self.render_result(profile, elapsed, environ).encode(encoding, "replace")
            resp_body = [insert_into_body(rendered, b"".join(resp_body))]
            headers_dic["Content-Length"] = str(len(resp_body[0]))
        start_response(status, headers, saved_ss_args[2] if len(saved_ss_args) == 3 else None)
        return resp_body
开发者ID:krrr,项目名称:nano-wsgi-profiler,代码行数:50,代码来源:__init__.py

示例5: _parse_headers

# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import add_header [as 别名]
def _parse_headers(environ):
    """
    Parse the environmental variables, looking for HTTP request headers.
    :param environ: environmental variables
    :type environ: dict
    :return: request headers
    :rtype: dict
    """
    headers = Headers([])
    for key, value in environ.items():
        match = _HTTP_HEADER_REGEX.match(key)
        if match is None:
            continue
        name = _normalize_header_name(match.group(0))
        headers.add_header(name, value)
    return headers
开发者ID:jlconnor,项目名称:wsgistack,代码行数:18,代码来源:request.py

示例6: testExtras

# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import add_header [as 别名]
    def testExtras(self):
        h = Headers([])
        self.assertEqual(str(h),'\r\n')

        h.add_header('foo','bar',baz="spam")
        self.assertEqual(h['foo'], 'bar; baz="spam"')
        self.assertEqual(str(h),'foo: bar; baz="spam"\r\n\r\n')

        h.add_header('Foo','bar',cheese=None)
        self.assertEqual(h.get_all('foo'),
            ['bar; baz="spam"', 'bar; cheese'])

        self.assertEqual(str(h),
            'foo: bar; baz="spam"\r\n'
            'Foo: bar; cheese\r\n'
            '\r\n'
        )
开发者ID:524777134,项目名称:cpython,代码行数:19,代码来源:test_wsgiref.py

示例7: testBytes

# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import add_header [as 别名]
    def testBytes(self):
        h = Headers([(b"Content-Type", b"text/plain; charset=utf-8")])
        self.assertEqual("text/plain; charset=utf-8", h.get("Content-Type"))

        h[b"Foo"] = bytes(b"bar")
        self.assertEqual("bar", h.get("Foo"))
        self.assertEqual("bar", h.get(b"Foo"))

        h.setdefault(b"Bar", b"foo")
        self.assertEqual("foo", h.get("Bar"))
        self.assertEqual("foo", h.get(b"Bar"))

        h.add_header(b"content-disposition", b"attachment", filename=b"bud.gif")
        self.assertEqual('attachment; filename="bud.gif"', h.get("content-disposition"))

        del h["content-disposition"]
        self.assertTrue(b"content-disposition" not in h)
开发者ID:Kanma,项目名称:Athena-Dependencies-Python,代码行数:19,代码来源:test_wsgiref.py

示例8: Response

# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import add_header [as 别名]
class Response(threading.local):
    """ Represents a single response using thread-local namespace. """

    def bind(self):
        """ Clears old data and creates a brand new Response object """
        self._COOKIES = None
        self.status = 200
        self.header_list = []
        self.header = HeaderWrapper(self.header_list)
        self.content_type = "text/html"
        self.error = None
        self.charset = "utf8"

    def wsgiheaders(self):
        """ Returns a wsgi conform list of header/value pairs """
        for c in self.COOKIES.itervalues():
            self.header.add_header("Set-Cookie", c.OutputString())
        return [(h.title(), str(v)) for h, v in self.header.items()]

    @property
    def COOKIES(self):
        if not self._COOKIES:
            self._COOKIES = SimpleCookie()
        return self._COOKIES

    def set_cookie(self, key, value, **kargs):
        """
        Sets a Cookie. Optional settings:
        expires, path, comment, domain, max-age, secure, version, httponly
        """
        self.COOKIES[key] = value
        for k, v in kargs.iteritems():
            self.COOKIES[key][k] = v

    def get_content_type(self):
        """ Get the current 'Content-Type' header. """
        return self.header["Content-Type"]

    def set_content_type(self, value):
        if "charset=" in value:
            self.charset = value.split("charset=")[-1].split(";")[0].strip()
        self.header["Content-Type"] = value

    content_type = property(get_content_type, set_content_type, None, get_content_type.__doc__)
开发者ID:pombredanne,项目名称:buses,代码行数:46,代码来源:bottle.py

示例9: Response

# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import add_header [as 别名]
class Response(threading.local):
    """ Represents a single response using thread-local namespace. """

    def bind(self):
        """ Clears old data and creates a brand new Response object """
        self._COOKIES = None
        self.status = 200
        self.header_list = []
        self.header = HeaderWrapper(self.header_list)
        self.content_type = 'text/html'
        self.error = None

    def wsgiheaders(self):
        ''' Returns a wsgi conform list of header/value pairs '''
        for c in self.COOKIES.itervalues():
            self.header.add_header('Set-Cookie', c.OutputString())
        return [(h.title(), str(v)) for h, v in self.header_list]

    @property
    def COOKIES(self):
        if not self._COOKIES:
            self._COOKIES = SimpleCookie()
        return self._COOKIES

    def set_cookie(self, key, value, **kargs):
        """ Sets a Cookie. Optional settings: expires, path, comment, domain, max-age, secure, version, httponly """
        self.COOKIES[key] = value
        for k in kargs:
            self.COOKIES[key][k] = kargs[k]

    def get_content_type(self):
        '''Gives access to the 'Content-Type' header and defaults to 'text/html'.'''
        return self.header['Content-Type']
        
    def set_content_type(self, value):
        self.header['Content-Type'] = value
        
    content_type = property(get_content_type, set_content_type, None, get_content_type.__doc__)
开发者ID:klose,项目名称:mesos,代码行数:40,代码来源:bottle.py

示例10: Response

# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import add_header [as 别名]
class Response(object):
    """
    Wrapper class around the start_response and return iterable of the WSGI
    protocol.

    :ivar status: HTTP status of the response
    :type status: int
    :ivar headers: response headers
    :type headers: dict
    :ivar cookies: cookies to set
    :type cookies: dict
    """

    def __init__(self):
        self.status = None
        self.__header_list = []
        self.headers = Headers(self.__header_list)
        self.headers['date'] = rfc1123_date()
        self.cookies = SimpleCookie()

    def start_response_args(self, body):
        """
        Return a status string and a list of headers for this response,
        appropriate as arguments to the start_response function.
        :param body: response body
        :type body: str
        :return: tuple of status string and list of header tuples
        :rtype: (str, list)
        """
        if self.status is None:
            raise RuntimeError('response status was not set')
        self.headers['content-length'] = str(len(body))
        for cookie in self.cookies:
            self.headers.add_header('set-cookie', cookie.output(header=''))
        status_str = '%d %s' % (self.status, httplib.responses[self.status])
        return (status_str, self.__header_list)
开发者ID:jlconnor,项目名称:wsgistack,代码行数:38,代码来源:response.py

示例11: StaticFile

# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import add_header [as 别名]
class StaticFile(object):
    ACCEPT_GZIP_RE = re.compile(r'\bgzip\b')
    BLOCK_SIZE = 16 * 4096
    # All mimetypes starting 'text/' take a charset parameter, plus the
    # additions in this set
    MIMETYPES_WITH_CHARSET = {'application/javascript', 'application/xml'}
    CHARSET = 'utf-8'
    # Ten years is what nginx sets a max age if you use 'expires max;'
    # so we'll follow its lead
    FOREVER = 10*365*24*60*60

    GZIP_SUFFIX = '.gz'

    def __init__(self, path, is_immutable, guess_type=mimetypes.guess_type, **config):
        self.path = path
        stat = os.stat(path)
        self.mtime_tuple = gmtime(stat.st_mtime)
        mimetype, encoding = guess_type(path)
        mimetype = mimetype or 'application/octet-stream'
        charset = self.get_charset(mimetype)
        params = {'charset': charset} if charset else {}
        self.headers = Headers([
            ('Last-Modified', formatdate(stat.st_mtime, usegmt=True)),
            ('Content-Length', str(stat.st_size)),
        ])
        self.headers.add_header('Content-Type', str(mimetype), **params)
        if encoding:
            self.headers['Content-Encoding'] = encoding

        max_age = self.FOREVER if is_immutable else config['max_age']
        if max_age is not None:
            self.headers['Cache-Control'] = 'public, max-age=%s' % max_age

        if config['allow_all_origins']:
            self.headers['Access-Control-Allow-Origin'] = '*'

        gzip_path = path + self.GZIP_SUFFIX
        if os.path.isfile(gzip_path):
            self.gzip_path = gzip_path
            self.headers['Vary'] = 'Accept-Encoding'
            # Copy the headers and add the appropriate encoding and length
            self.gzip_headers = Headers(self.headers.items())
            self.gzip_headers['Content-Encoding'] = 'gzip'
            self.gzip_headers['Content-Length'] = str(os.stat(gzip_path).st_size)
        else:
            self.gzip_path = self.gzip_headers = None

    def get_charset(self, mimetype):
        if mimetype.startswith('text/') or mimetype in self.MIMETYPES_WITH_CHARSET:
            return self.CHARSET

    def serve(self, environ, start_response):
        method = environ['REQUEST_METHOD']
        if method != 'GET' and method != 'HEAD':
            start_response('405 Method Not Allowed', [('Allow', 'GET, HEAD')])
            return []
        if self.file_not_modified(environ):
            start_response('304 Not Modified', [])
            return []
        path, headers = self.get_path_and_headers(environ)
        start_response('200 OK', headers.items())
        if method == 'HEAD':
            return []
        file_wrapper = environ.get('wsgi.file_wrapper', self.yield_file)
        fileobj = open(path, 'rb')
        return file_wrapper(fileobj)

    def file_not_modified(self, environ):
        try:
            last_requested = environ['HTTP_IF_MODIFIED_SINCE']
        except KeyError:
            return False
        # Exact match, no need to parse
        if last_requested == self.headers['Last-Modified']:
            return True
        return parsedate(last_requested) >= self.mtime_tuple

    def get_path_and_headers(self, environ):
        if self.gzip_path:
            if self.ACCEPT_GZIP_RE.search(environ.get('HTTP_ACCEPT_ENCODING', '')):
                return self.gzip_path, self.gzip_headers
        return self.path, self.headers

    def yield_file(self, fileobj):
        # Only used as a fallback in case environ doesn't supply a
        # wsgi.file_wrapper
        try:
            while True:
                block = fileobj.read(self.BLOCK_SIZE)
                if block:
                    yield block
                else:
                    break
        finally:
            fileobj.close()
开发者ID:ionelmc,项目名称:whitenoise,代码行数:97,代码来源:base.py

示例12: Response

# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import add_header [as 别名]
class Response(threading.local):
    def setup(self):
        self.status = http_status['200']
        self.headers = Headers([('Content-type','text/html; charset=UTF-8')])
        self.out = b''

    def download(self, dir, args, cd=False):
        ims = request.env.get('HTTP_IF_MODIFIED_SINCE', '')
        file = os.path.join(dir, *args)
        if not os.access(file, os.R_OK):
            self.error(mesg='File not found',raise_exc=True)
        mimetype, encoding = mimetypes.guess_type(file)
        if mimetype: self.headers.add_header('Content-Type',mimetype)
        if encoding: self.headers.add_header('Content-Encoding',encoding)
        if cd:
            self.headers.add_header('Content-Disposition','attachment',filename=args[-1])
        stats = os.stat(file)
        self.headers.add_header('Content-Length', str(stats.st_size))
        time_fmt = "%a, %d %b %Y %H:%M:%S GMT"
        last_modified = strftime(time_fmt, gmtime(stats.st_mtime))
        self.headers.add_header('Last-Modified', last_modified)

        if ims: ims = strptime(ims.split(";")[0].strip(), time_fmt)
        else: ims = None
        if ims is not None and ims >= gmtime(stats.st_mtime-2):
            date = strftime(time_fmt, gmtime())
            self.headers.add_header('Date', date)
            self.status = http_status['304']
        elif request.method == 'HEAD': self.out = ''
        else: self.out = open(file,'rb').read()

    def error(self, mesg='', status='404', raise_exc=True):
        self.status = http_status[status]
        self.out = mesg
        self.headers = Headers([('Content-type','text/plain')])
        if raise_exc: raise Exception('ResponseError NotFound')

    def output(self):
        self.headers.add_header('Content-Length', str(len(self.out)))
        if type(self.out)==str: return self.out.encode('utf-8')
        return self.out
开发者ID:vtphan,项目名称:neo,代码行数:43,代码来源:neo.py

示例13: BeanServer

# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import add_header [as 别名]
class BeanServer(object):
    "A really, really simple application server."

    default_headers = [('Content-Type', 'text/html')]

    def __init__(self, ledger, opts):
        self.ledger = ledger

        self.data = []
        self.load()

        # Map of session to dict.
        self.cookiejar = {}

        # Prototype for context object.
        ctx = self.ctx = Context()
        self.opts = ctx.opts = opts
        ctx.debug = opts.debug

    def setHeader(self, name, value):
        self.headers[name] = value

    def write(self, data):
        assert isinstance(data, str), data
        self.data.append(data)

    def load(self):
        "Load the application pages."
        import app
        reload(app)
        self.mapper = app.mapper

    def __call__(self, environ, start_response):
        if self.ctx.debug:
            self.load()

        self.environ = environ
        self.response = start_response
        del self.data[:]
        self.headers = Headers(self.default_headers)

        ctx = copy(self.ctx) # shallow
        ctx.ledger = self.ledger

        path = environ['PATH_INFO']

        ishtml = '.' not in basename(path) or path.endswith('.html')
        if ishtml:
            # Load cookie (session is only in memory).
            cookie = Cookie.SimpleCookie(environ.get('HTTP_COOKIE', ''))
            has_cookie = (bool(cookie) and
                          'session' in cookie and
                          cookie["session"].value in self.cookiejar)
            if has_cookie:
                session_id = cookie["session"].value
                session = self.cookiejar[session_id]
            else:
                session_id = '%x' % randint(0, 16**16)
                cookie["session"] = session_id
                session = self.cookiejar[session_id] = {}
            ctx.session = session

        try:
            # Linear search in the regexp to match the request path.
            page, vardict = self.mapper.match(path)
            if page is None:
                raise HttpNotFound(path)
            else:
                # Update the context object with components of the request and
                # with the query parameters.
                ctx.environ = environ

                form = cgi.parse(environ=environ)
## FIXME: make this wsgi compatible.
                ## conlen = int(self.environ['CONTENT_LENGTH'])
                ## s = self.environ['wsgi.input'].read(conlen)
                ## form = cgi.parse_qs(s)

                ctx.__dict__.update(form)
                ctx.__dict__.update(vardict)

                page(self, ctx)

                # Add session cookie to headers, if necessary.
                if ishtml and not has_cookie:
                    for k, v in sorted(cookie.items()):
                        self.headers.add_header('Set-Cookie', v.OutputString())

                start_response('200 OK', self.headers.items())
                return self.data

        except HttpRedirect, e:
            location = e.message
            start_response(e.status, [('Location', location)])
            return [str(e)]

        except HttpError, e:
            status = getattr(e, 'status', '500 Internal Server Error')
            start_response(status, [('Content-Type', 'text/html')])
            return [str(e)]
开发者ID:mgax,项目名称:beancount,代码行数:102,代码来源:serve.py

示例14: __call__

# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import add_header [as 别名]
	def __call__(self, environ, start_response):
		'''Main function for handling a single request. Follows the
		WSGI API.

		@param environ: dictionary with environment variables for the
		request and some special variables. See the PEP for expected
		variables.

		@param start_response: a function that can be called to set the
		http response and headers. For example::

			start_response(200, [('Content-Type', 'text/plain')])

		@returns: the html page content as a list of lines
		'''
		headerlist = []
		headers = Headers(headerlist)
		path = environ.get('PATH_INFO', '/')
		try:
			methods = ('GET', 'HEAD')
			if not environ['REQUEST_METHOD'] in methods:
				raise WWWError('405', headers=[('Allow', ', '.join(methods))])

			# cleanup path
			#~ print 'INPUT', path
			path = path.replace('\\', '/') # make it windows save
			isdir = path.endswith('/')
			parts = [p for p in path.split('/') if p and not p == '.']
			if [p for p in parts if p.startswith('.')]:
				# exclude .. and all hidden files from possible paths
				raise PathNotValidError()
			path = '/' + '/'.join(parts)
			if isdir and not path == '/': path += '/'
			#~ print 'PATH', path

			if not path:
				path = '/'
			elif path == '/favicon.ico':
				path = '/+resources/favicon.ico'
			else:
				path = urllib.unquote(path)

			if path == '/':
				headers.add_header('Content-Type', 'text/html', charset='utf-8')
				content = self.render_index()
			elif path.startswith('/+docs/'):
				dir = self.notebook.document_root
				if not dir:
					raise PageNotFoundError(path)
				file = dir.file(path[7:])
				content = [file.raw()]
					# Will raise FileNotFound when file does not exist
				headers['Content-Type'] = file.get_mimetype()
			elif path.startswith('/+file/'):
				file = self.notebook.dir.file(path[7:])
					# TODO: need abstraction for getting file from top level dir ?
				content = [file.raw()]
					# Will raise FileNotFound when file does not exist
				headers['Content-Type'] = file.get_mimetype()
 			elif path.startswith('/+resources/'):
				if self.template.resources_dir:
					file = self.template.resources_dir.file(path[12:])
					if not file.exists():
						file = data_file('pixmaps/%s' % path[12:])
				else:
					file = data_file('pixmaps/%s' % path[12:])

				if file:
					content = [file.raw()]
						# Will raise FileNotFound when file does not exist
					headers['Content-Type'] = file.get_mimetype()
	 			else:
					raise PageNotFoundError(path)
			else:
				# Must be a page or a namespace (html file or directory path)
				headers.add_header('Content-Type', 'text/html', charset='utf-8')
				if path.endswith('.html'):
					pagename = path[:-5].replace('/', ':')
				elif path.endswith('/'):
					pagename = path[:-1].replace('/', ':')
				else:
					raise PageNotFoundError(path)

				path = self.notebook.resolve_path(pagename)
				page = self.notebook.get_page(path)
				if page.hascontent:
					content = self.render_page(page)
				elif page.haschildren:
					content = self.render_index(page)
				else:
					raise PageNotFoundError(page)
		except Exception, error:
			headerlist = []
			headers = Headers(headerlist)
			headers.add_header('Content-Type', 'text/plain', charset='utf-8')
			if isinstance(error, (WWWError, FileNotFoundError)):
				logger.error(error.msg)
				if isinstance(error, FileNotFoundError):
					error = PageNotFoundError(path)
					# show url path instead of file path
#.........这里部分代码省略.........
开发者ID:gdw2,项目名称:zim,代码行数:103,代码来源:www.py

示例15: __init__

# 需要导入模块: from wsgiref.headers import Headers [as 别名]
# 或者: from wsgiref.headers.Headers import add_header [as 别名]
class BaseResponse:
    """Base class for Response"""
    default_status = 200
    default_content_type = 'text/plain;'

    def __init__(self, body=b'', status=None, headers=None):
        self.headers = Headers()
        self._body = body
        self._status_code = status or self.default_status
        self._cookies = SimpleCookie()

        if headers:
            for name, value in headers.items():
                self.headers.add_header(name, value)

    @property
    def body(self):
        return [self._body]

    @property
    def status_code(self):
        """ The HTTP status code as an integer (e.g. 404)."""
        return self._status_code

    @property
    def status(self):
        """ The HTTP status line as a string (e.g. ``404 Not Found``)."""
        if not 100 <= self._status_code <= 999:
            raise ValueError('Status code out of range.')
        status = _HTTP_STATUS_LINES.get(self._status_code)
        return str(status or ('{} Unknown'.format(self._status_code)))

    @status.setter
    def status(self, status_code):
        if not 100 <= status_code <= 999:
            raise ValueError('Status code out of range.')
        self._status_code = status_code

    @property
    def headerlist(self):
        """ WSGI conform list of (header, value) tuples. """
        if 'Content-Type' not in self.headers:
            self.headers.add_header('Content-Type', self.default_content_type)
        if self._cookies:
            for c in self._cookies.values():
                self.headers.add_header('Set-Cookie', c.OutputString())
        return self.headers.items()

    def set_cookie(self, key, value, expires=None, max_age=None, path=None,
                   secret=None, digestmod=hashlib.sha256):
        if secret:
            if isinstance(secret, str):
                secret = secret.encode('utf-8')
            encoded = base64.b64encode(pickle.dumps((key, value), pickle.HIGHEST_PROTOCOL))
            sig = base64.b64encode(hmac.new(secret, encoded, digestmod=digestmod).digest())
            value_bytes = b'!' + sig + b'?' + encoded
            value = value_bytes.decode('utf-8')

        self._cookies[key] = value
        if len(key) + len(value) > 3800:
            raise ValueError('Content does not fit into a cookie.')

        if max_age is not None:
            if isinstance(max_age, int):
                max_age_value = max_age
            else:
                max_age_value = max_age.seconds + max_age.days * 24 * 3600
            self._cookies[key]['max-age'] = max_age_value
        if expires is not None:
            if isinstance(expires, int):
                expires_value = expires
            else:
                expires_value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", expires.timetuple())
            self._cookies[key]['expires'] = expires_value
        if path:
            self._cookies[key]['path'] = path

    def delete_cookie(self, key, **kwargs):
        kwargs['max_age'] = -1
        kwargs['expires'] = 0
        self.set_cookie(key, '', **kwargs)
开发者ID:c-bata,项目名称:kobin,代码行数:83,代码来源:environs.py


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