Adds Access-Control* HTTP headers to this WbResponse's HTTP headers.

        :param dict env: The WSGI environment dictionary
        :return: The same WbResponse but with the values for the Access-Control* HTTP header added
        :rtype: WbResponse
977330
def add_access_control_headers(self, env=None):
        
        allowed_methods = 'GET, POST, PUT, OPTIONS, DELETE, PATCH, HEAD, TRACE, CONNECT'
        allowed_origin = None
        if env is not None:
            acr_method = env.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
            if acr_method is not None and acr_method not in allowed_methods:
                allowed_methods = allowed_methods + ', ' + acr_method
            r_method = env.get('REQUEST_METHOD')
            if r_method is not None and r_method not in allowed_methods:
                allowed_methods = allowed_methods + ', ' + r_method
            acr_headers = env.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS')
            if acr_headers is not None:
                self.status_headers.add_header('Access-Control-Allow-Headers', acr_headers)
            allowed_origin = env.get('HTTP_ORIGIN', env.get('HTTP_REFERER', allowed_origin))
        if allowed_origin is None:
            allowed_origin = '*'
        self.status_headers.replace_header('Access-Control-Allow-Origin',  allowed_origin)
        self.status_headers.add_header('Access-Control-Allow-Methods', allowed_methods)
        self.status_headers.add_header('Access-Control-Allow-Credentials', 'true')
        self.status_headers.add_header('Access-Control-Max-Age', '1800')
        return self
836259
def _handle_POST(self, env, start_response):
        
        input = env['wsgi.input']
        data = input.read( int(env['CONTENT_LENGTH']) )
        mimeType = "text/xml"
        if self.encoding is not None:
            mimeType = 'text/xml; charset="%s"' % self.encoding

        request = None
        resource = self.delegate or self
        chain = self.factory.newInstance()
        try:
            pyobj = chain.processRequest(data, request=request, resource=resource)
        except Exception, ex:
            start_response("500 ERROR", [('Content-Type',mimeType)])
            return [fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]

        try:
            soap = chain.processResponse(pyobj, request=request, resource=resource)
        except Exception, ex:
            start_response("500 ERROR", [('Content-Type',mimeType)])
            return [fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]
        
        start_response("200 OK", [('Content-Type',mimeType)])
        return [soap]
847626
def build_environ(scope, message, body):
    
    environ = {
        "REQUEST_METHOD": scope["method"],
        "SCRIPT_NAME": "",
        "PATH_INFO": scope["path"],
        "QUERY_STRING": scope["query_string"].decode("ascii"),
        "SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"],
        "wsgi.version": (1, 0),
        "wsgi.url_scheme": scope.get("scheme", "http"),
        "wsgi.input": io.BytesIO(body),
        "wsgi.errors": sys.stdout,
        "wsgi.multithread": True,
        "wsgi.multiprocess": True,
        "wsgi.run_once": False,
    }

    # Get server name and port - required in WSGI, not in ASGI
    server = scope.get("server", ("localhost", 80))
    environ["SERVER_NAME"] = server[0]
    environ["SERVER_PORT"] = server[1]

    # Get client IP address
    if "client" in scope:
        environ["REMOTE_ADDR"] = scope["client"][0]

    # Go through headers and make them into environ entries
    for name, value in scope.get("headers", []):
        name = name.decode("latin1")
        if name == "content-length":
            corrected_name = "CONTENT_LENGTH"
        elif name == "content-type":
            corrected_name = "CONTENT_TYPE"
        else:
            corrected_name = "HTTP_%s" % name.upper().replace("-", "_")
        # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case
        value = value.decode("latin1")
        if corrected_name in environ:
            value = environ[corrected_name] + "," + value
        environ[corrected_name] = value
    return environ
43556
def get_headers(hide_env=True):
    """"""

    headers = dict(request.headers.items())

    if hide_env and ('show_env' not in request.args):
        for key in ENV_HEADERS:
            try:
                del headers[key]
            except KeyError:
                pass

    return CaseInsensitiveDict(headers.items())
1027781
def wsgi(self, environ, start_response):
        
        try:
            out = self._cast(self._handle(environ))
            # rfc2616 section 4.3
            if response._status_code in (100, 101, 204, 304)\
            or environ['REQUEST_METHOD'] == 'HEAD':
                if hasattr(out, 'close'): out.close()
                out = []
            start_response(response._status_line, response.headerlist)
            return out
        except (KeyboardInterrupt, SystemExit, MemoryError):
            raise
        except Exception:
            if not self.catchall: raise
            err = '<h1>Critical error while processing request: %s</h1>' \
                  % html_escape(environ.get('PATH_INFO', '/'))
            if DEBUG:
                err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \
                       '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \
                       % (html_escape(repr(_e())), html_escape(format_exc()))
            environ['wsgi.errors'].write(err)
            headers = [('Content-Type', 'text/html; charset=UTF-8')]
            start_response('500 INTERNAL SERVER ERROR', headers, sys.exc_info())
            return [tob(err)]
30339
def wsgi(self, environ, start_response):
        
        try:
            environ['bottle.app'] = self
            request.bind(environ)
            response.bind()
            out = self._cast(self._handle(environ), request, response)
            # rfc2616 section 4.3
            if response._status_code in (100, 101, 204, 304)\
            or request.method == 'HEAD':
                if hasattr(out, 'close'): out.close()
                out = []
            start_response(response._status_line, list(response.iter_headers()))
            return out
        except (KeyboardInterrupt, SystemExit, MemoryError):
            raise
        except Exception, e:
            if not self.catchall: raise
            err = '<h1>Critical error while processing request: %s</h1>' \
                  % html_escape(environ.get('PATH_INFO', '/'))
            if DEBUG:
                err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \
                       '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \
                       % (html_escape(repr(e)), html_escape(format_exc(10)))
            environ['wsgi.errors'].write(err)
            headers = [('Content-Type', 'text/html; charset=UTF-8')]
            start_response('500 INTERNAL SERVER ERROR', headers)
            return [tob(err)]
143057
def call(env)
      request = env['rack-accept_headers.request'] ||= Request.new(env)
      check!(request) unless @checks.empty?
      @app.call(env)
    rescue AcceptError
      response = Response.new
      response.not_acceptable!
      response.finish
    end
1165544
def make_response(status, headers, payload, environ):
    
    return Response(body=payload, status=int(status.split()[0]),
                    headers=headers)
768252
def host(environ):  # pragma: no cover
    

    url = environ['wsgi.url_scheme'] + '://'

    if environ.get('HTTP_HOST'):
        url += environ['HTTP_HOST']
    else:
        url += environ['SERVER_NAME']

        if environ['wsgi.url_scheme'] == 'https':
            if environ['SERVER_PORT'] != '443':
                url += ':' + environ['SERVER_PORT']
        else:
            if environ['SERVER_PORT'] != '80':
                url += ':' + environ['SERVER_PORT']

    return url + quote(environ.get('SCRIPT_NAME', ''))
801460
def add_to_env(self, content):
        
        if not self.rewrite_config:
            raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.")
        if not self.env_file:
            self.env_path, self.env_file = self.__get_env_handle(self.root_dir)
        self.env_file.write(content + '\n')
187256
def setup(self, environ):
        '''
        '''
        request = wsgi_request(environ)
        cfg = request.cache.cfg
        loop = request.cache._loop
        self.store = create_store(cfg.data_store, loop=loop)
        pubsub = self.store.pubsub(protocol=Protocol())
        channel = '%s_webchat' % self.name
        ensure_future(pubsub.subscribe(channel), loop=loop)
        return WsgiHandler([Router('/', get=self.home_page),
                            WebSocket('/message', Chat(pubsub, channel)),
                            Router('/rpc', post=Rpc(pubsub, channel),
                                   response_content_types=JSON_CONTENT_TYPES)],
                           [AsyncResponseMiddleware,
                            GZipMiddleware(min_length=20)])
795521
def handle(self, environ, start_response):
        ""
        # Pass off to the router
        try:
            handler = self.route(
                environ['PATH_INFO'].lower(),
                environ['REQUEST_METHOD'].lower(),
            )
            if handler is None:
                raise HttpNotFound()
        # Handle errors
        except HttpNotFound:
            start_response('404 Not Found', [('Content-Type', 'application/json')])
            return [json.dumps({"error": "not_found"})]
        except HttpMethodNotAllowed:
            start_response('405 Method Not Allowed', [('Content-Type', 'application/json')])
            return [json.dumps({"error": "method_not_allowed"})]
        # Dispatch to the named method
        body = environ['wsgi.input'].read()
        if body:
            body = json.loads(body)
        response = handler(
            environ['PATH_INFO'].lower(),
            body,
        )
        # Send the response
        start_response('200 OK', [('Content-Type', 'application/json')])
        return [json.dumps(response)]
1121264
def header(self):
        ''' 
        '''
        if self._header is None:
            self._header = HeaderDict()
            for key, value in self.environ.iteritems():
                if key.startswith('HTTP_'):
                    key = key[5:].replace('_','-').title()
                    self._header[key] = value
        return self._header
983072
def add_headers(self, app):
        
        @app.after_request
        def after_request(response):  # noqa
            for header, value in self.config.get('headers'):
                response.headers[header] = value
            return response
308598
def enable_cors(self):
        '''
        '''
        def access_control_headers():
            bottle.response.headers['Access-Control-Allow-Origin'] = '*'
            bottle.response.headers['Access-Control-Allow-Methods'] = \
                'GET, POST, PUT, DELETE, OPTIONS'
            bottle.response.headers['Access-Control-Allow-Headers'] = \
                'Origin, X-Requested-With, Content-Type, Accept, Authorization'

        def options_response(res):
            if bottle.request.method == 'OPTIONS':
                new_res = bottle.HTTPResponse()
                new_res.headers['Access-Control-Allow-Origin'] = '*'
                new_res.headers['Access-Control-Allow-Methods'] = \
                    bottle.request.headers.get(
                        'Access-Control-Request-Method', '')
                new_res.headers['Access-Control-Allow-Headers'] = \
                    bottle.request.headers.get(
                        'Access-Control-Request-Headers', '')
                return new_res
            res.headers['Allow'] += ', OPTIONS'
            return bottle.request.app.default_error_handler(res)

        self.app.add_hook('after_request', access_control_headers)
        self.app.error_handler[int(405)] = options_response
        return self
1023366
def get_authorization_header():
    
    header = request.environ.get('HTTP_AUTHORIZATION')

    if not header:
        return None

    header = wsgi_to_bytes(header)

    try:
        auth_type, auth_info = header.split(None, 1)
        auth_type = auth_type.lower()
    except ValueError:
        return None

    return auth_type, auth_info
926147
def AddHeader(self, header, value):
        '''
        '''
        self.user_headers.append((header, value))
        return self