Returns an HTTP request handler configured with the given ca_file.
762513
def handler(ca_file=None):
    """"""

    def request(url, message, **kwargs):
        scheme, host, port, path = spliturl(url)

        if scheme != "https": 
            ValueError("unsupported scheme: %s" % scheme)

        connection = HTTPSConnection(host, port, ca_file)
        try:
            body = message.get('body', "")
            headers = dict(message.get('headers', []))
            connection.request(message['method'], path, body, headers)
            response = connection.getresponse()
        finally:
            connection.close()

        return {
            'status': response.status,
            'reason': response.reason,
            'headers': response.getheaders(),
            'body': BytesIO(response.read())
        }

    return request
71072
function getServerHandler(basePath, adapter) {
    basePath = basePath || '/';
    if (basePath.length > 0 && basePath[basePath.length - 1] === '/') {
        basePath = basePath.substring(0, basePath.length - 2);
    }
    return function(req, res, next) {
        return teleport.Promise.resolve().then(function() {
            var params = req.params = req.params || {};
            var path = params.path || params['0'] || '';
            if (path[0] !== '/') {
                path = '/' + path;
            }
            path = basePath + path;
            var query = req.query || {};
            var headers = req.headers || {};
            var data = req.data || req.body || {};
            var overrideKey = 'X-HTTP-Method-Override';
            var method = //
            headers[overrideKey] || query[overrideKey] || //
            req.method || 'get';
            delete query[overrideKey];
            method = method.toLowerCase();
            var options = {
                path : path,
                method : method,
                params : params,
                query : query,
                headers : headers,
                data : data
            };
            return adapter.handle(options);
        }).then(function(result) {
            result = result || {};
            var headers = result.headers || {};
            res.set(headers);
            res.send(result.data || {});
        }, function(err) {
            res.status(500).send({
                error : err.stack,
                params : req.params
            });
        });
    }
}
1211839
def file_handler(name, logname, filename, mode='a', encoding=None,
                 delay=False):
    

    return wrap_log_handler(logging.FileHandler(
        filename, mode=mode, encoding=encoding, delay=delay))
1246313
def request(self, host, handler, request_body, verbose):
        ''''''
        #We get a traceback if we don't have this attribute:
        self.verbose = verbose
        url = 'http://' + host + handler
        request = urllib2.Request(url)
        request.add_data(request_body)
        # Note: 'Host' and 'Content-Length' are added automatically
        request.add_header('User-Agent', self.user_agent)
        request.add_header('Content-Type', 'text/xml')
        proxy_handler = urllib2.ProxyHandler()
        opener = urllib2.build_opener(proxy_handler)
        fhandle = opener.open(request)
        return(self.parse_response(fhandle))
1240410
def _request_helper(self, url, request_body):
        
        response = None
        # pylint: disable=try-except-raise
        try:
            response = self.session.post(
                url, data=request_body, **self.request_defaults)

            # We expect utf-8 from the server
            response.encoding = 'UTF-8'

            # update/set any cookies
            if self._cookiejar is not None:
                for cookie in response.cookies:
                    self._cookiejar.set_cookie(cookie)

                if self._cookiejar.filename is not None:
                    # Save is required only if we have a filename
                    self._cookiejar.save()

            response.raise_for_status()
            return self.parse_response(response)
        except requests.RequestException as e:
            if not response:
                raise
            raise ProtocolError(
                url, response.status_code, str(e), response.headers)
        except Fault:
            raise
        except Exception:
            e = BugzillaError(str(sys.exc_info()[1]))
            # pylint: disable=attribute-defined-outside-init
            e.__traceback__ = sys.exc_info()[2]
            # pylint: enable=attribute-defined-outside-init
            raise e
431962
def get_request(self):
        
        # Accept the client
        client_socket, client_address = self.socket.accept()

        if ssl is not None and self.cert_file:
            # Setup an SSL context to accept clients with a certificate
            # signed by a known chain of authority.
            # Other clients will be rejected during handshake.
            context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
            try:
                # Force a valid/signed client-side certificate
                context.verify_mode = ssl.CERT_REQUIRED

                # Load the server certificate
                context.load_cert_chain(
                    certfile=self.cert_file,
                    keyfile=self.key_file,
                    password=self.key_password,
                )

                if self.ca_file:
                    # Load the given authority chain
                    context.load_verify_locations(self.ca_file)
                else:
                    # Load the default chain if none given
                    context.load_default_certs(ssl.Purpose.CLIENT_AUTH)
            except Exception as ex:
                # Explicitly log the error as the default behaviour hides it
                _logger.error("Error setting up the SSL context: %s", ex)
                raise

            try:
                # SSL handshake
                client_stream = context.wrap_socket(
                    client_socket, server_side=True
                )
            except ssl.SSLError as ex:
                # Explicitly log the exception before re-raising it
                _logger.warning(
                    "Error during SSL handshake with %s: %s", client_address, ex
                )
                raise
        else:
            # Nothing to do, use the raw socket
            client_stream = client_socket

        return client_stream, client_address
789899
def handle_request(self, request, **resources):
        
        if not request.method in self._meta.callmap.keys():
            raise HttpError(
                'Unknown or unsupported method \'%s\'' % request.method,
                status=status.HTTP_501_NOT_IMPLEMENTED)

        # Get the appropriate create/read/update/delete function
        view = getattr(self, self._meta.callmap[request.method])

        # Get function data
        return view(request, **resources)
1363318
def _serve_file(self, path):
        
        fapp = paste.fileapp.FileApp(path)
        return fapp(request.environ, self.start_response)
172182
def request( self, url, method='get',
			decode=None, encode=None, data=None,
			headers=None, raise_for=dict(), queue_lines=None ):
		''''''
		if self.debug_requests:
			url_debug = _dump_trunc(url)
			log.debug('HTTP request: {} {} (h: {}, enc: {}, dec: {}, data: {!r})'.format(
				method, url_debug, headers, encode, decode, _dump_trunc(data) ))

		timeout = HTTPTimeout(**self.request_io_timeouts)
		req_headers = {'User-Agent': 'txU1'}

		if data is not None:
			if encode == 'files':
				boundary = os.urandom(16).encode('hex')
				req_headers['Content-Type'] = 'multipart/form-data; boundary={}'.format(boundary)
				data = MultipartDataSender(data, boundary)
				if not callable(headers): yield data.calculate_length()
				else:
					body = io.BytesIO()
					yield data.calculate_length(body)
					headers = headers(url, method, body.getvalue(), 'multipart/form-data')
			else:
				if encode is None:
					if isinstance(data, types.StringTypes): data = io.BytesIO(data)
				elif encode == 'form':
					req_headers['Content-Type'] = 'application/x-www-form-urlencoded'
					data = io.BytesIO(urllib.urlencode(data))
				elif encode == 'json':
					req_headers['Content-Type'] = 'application/json'
					data = io.BytesIO(json.dumps(data))
				else: raise ValueError('Unknown request encoding: {}'.format(encode))
				if callable(headers):
					data.seek(0)
					headers = headers(url, method, data.read(), req_headers.get('Content-Type'))
				data = FileBodyProducer(data)
		elif callable(headers): headers = headers(url, method, '', None)

		# Passed "headers" should be allowed to be modified by body_hash()
		for k, v in (headers or dict()).viewitems():
			req_headers[force_bytes(k)] = force_bytes(v)
		url, method = it.imap(force_bytes, [url, method.lower()])

		if decode == 'json': req_headers.setdefault('Accept', 'application/json')
		elif decode is not None:
			raise ValueError('Unknown response decoding method: {}'.format(decode))

		res_deferred = first_result( timeout,
			self.request_agent.request( method.upper(), url,
				Headers(dict((k,[v]) for k,v in req_headers.viewitems())), data ) )
		code = res_body = None
		try:
			res = yield res_deferred
			code = res.code
			if code == http.NO_CONTENT: defer.returnValue(None)
			if code not in [http.OK, http.CREATED]:
				if self.debug_requests:
					res_body = defer.Deferred()
					res.deliverBody(DataReceiver(res_body, timer=timeout, allow_loss=True))
					res_body = yield first_result(timeout, res_body)
					log.debug('HTTP error response body: {!r}'.format(res_body))
				raise ProtocolError(code, res.phrase)

			res_body = defer.Deferred()
			res.deliverBody(DataReceiver(res_body, timer=timeout))
			res_body = yield first_result(timeout, res_body)

			if self.debug_requests:
				log.debug( 'HTTP request done ({} {}): {} {} {}, body_len: {}'\
					.format(method, url_debug, code, res.phrase, res.version, len(res_body)) )
			defer.returnValue(json.loads(res_body) if decode is not None else res_body)

		except ( timeout.ActivityTimeout, TimeoutError,
				ResponseFailed, RequestNotSent, RequestTransmissionFailed ) as err:
			if isinstance(err, timeout.ActivityTimeout):
				if not res_deferred.called: res_deferred.cancel()
				if res_body and not res_body.called: res_body.cancel()
			if self.debug_requests:
				log.debug(
					'HTTP transport (underlying protocol) error ({} {}): {}'\
					.format(method, url_debug, err.message or repr(err.args)) )
			raise UnderlyingProtocolError(err)

		except ProtocolError as err:
			if self.debug_requests:
				log.debug(
					'HTTP request handling error ({} {}, code: {}): {}'\
					.format(method, url_debug, code, err.message) )
			raise raise_for.get(code, ProtocolError)(code, err.message)

		except RequestGenerationFailed as err:
			err[0][0].raiseException()

		finally: timeout.state_finished()
715900
def get_handler(self, request):
        
        try:
            f = self._json_rpc_methods[request.method]

        except (AttributeError, KeyError):  # pragma no coverage
            raise RPCMethodError("Received invalid method '{}'".format(request.method))

        return f
1027264
def crl(request, pk):
    
    authenticated = request.user.is_authenticated
    authenticated = authenticated() if callable(authenticated) else authenticated
    if app_settings.CRL_PROTECTED and not authenticated:
        return HttpResponse(_('Forbidden'),
                            status=403,
                            content_type='text/plain')
    ca = crl.ca_model.objects.get(pk=pk)
    return HttpResponse(ca.crl,
                        status=200,
                        content_type='application/x-pem-file')
34289
def handle_one_request(self):
        """Copy of WSGIRequestHandler, but with different ServerHandler"""

        self.raw_requestline = self.rfile.readline(65537)
        if len(self.raw_requestline) > 65536:
            self.requestline = ''
            self.request_version = ''
            self.command = ''
            self.send_error(414)
            return

        if not self.parse_request():  # An error code has been sent, just exit
            return

        handler = ServerHandler(
            self.rfile, self.wfile, self.get_stderr(), self.get_environ()
        )
        handler.request_handler = self      # backpointer for logging
        handler.run(self.server.get_app())
393998
def _get_file_handlers(self, dsid):
        """"""
        ds_info = self.ids[dsid]

        filetype = self._preferred_filetype(ds_info['file_type'])
        if filetype is None:
            logger.warning("Required file type '%s' not found or loaded for "
                           "'%s'", ds_info['file_type'], dsid.name)
        else:
            return self.file_handlers[filetype]
18010
def _http_request(self, method, url, request_kwargs=None):
        

        kwargs = request_kwargs if request_kwargs is not None else {}

        headers = self._request_headers()
        headers.update(self.additional_headers)
        if 'headers' in kwargs:
            headers.update(kwargs['headers'])
        kwargs['headers'] = headers

        if self._has_proxy():
            kwargs['proxies'] = self._proxy_parameters()

        request_url = self._url(
            url,
            file_upload=kwargs.pop('file_upload', False)
        )

        request_method = getattr(requests, method)
        response = request_method(request_url, **kwargs)

        if response.status_code == 429:
            raise RateLimitExceededError(response)

        return response
1003604
def get_request_handler(self):
        
        assert self.request_handler is not None, \
            'Please define a request_handler ' \
            ' for Endpoint: %s' % self.__class__.__name__

        return self.request_handler(self, **self.get_request_handler_params())
1238366
def get(self, request, *args, **kwargs):
        
        private_file = self.get_private_file()

        if not self.can_access_file(private_file):
            return HttpResponseForbidden('Private storage access denied')

        if not private_file.exists():
            return self.serve_file_not_found(private_file)
        else:
            return self.serve_file(private_file)
531105
def getFileHandle(self, dataFile, openMethod):
        
        if dataFile in self._memoTable:
            handle = self._memoTable[dataFile]
            self._update(dataFile, handle)
            return handle
        else:
            try:
                handle = openMethod(dataFile)
            except ValueError:
                raise exceptions.FileOpenFailedException(dataFile)

            self._memoTable[dataFile] = handle
            self._add(dataFile, handle)
            if len(self._memoTable) > self._maxCacheSize:
                dataFile = self._removeLru()
                del self._memoTable[dataFile]
            return handle