def handle_request(self, env, req):
        if req.method not in ('GET', 'HEAD', 'OPTIONS'):
            headers = self._getCacheHeaders(CACHE_BAD_URL)
            return HTTPMethodNotAllowed(request=req, headers=headers)
        if req.method == 'OPTIONS' and \
                req.headers.get('Access-Control-Request-Method') not in \
                ('GET', 'HEAD', 'OPTIONS'):
            headers = self._getCacheHeaders(CACHE_BAD_URL)
            return HTTPUnauthorized(request=req,
                                    headers={'Allow': 'GET, HEAD, OPTIONS'})
        if self.allowed_origin_remote_ips and \
                req.remote_addr not in self.allowed_origin_remote_ips:
            raise OriginRequestNotAllowed(
                'SOS Origin: Remote IP %s not allowed' % req.remote_addr)

        # allow earlier middleware to override hash and obj_name
        hsh = env.get('swift.cdn_hash')
        object_name = env.get('swift.cdn_object_name')
        if hsh is None or object_name is None:
            for regex in self.cdn_regexes:
                match_obj = regex.match(req.url)
                if match_obj:
                    match_dict = match_obj.groupdict()
                    if not hsh:
                        hsh = match_dict.get('hash')
                    if not object_name:
                        object_name = match_dict.get('object_name')
                    break
        if not hsh:
            self.logger.debug('Hash %s not found in %s' % (hsh, req.url))
            headers = self._getCacheHeaders(CACHE_BAD_URL)
            return HTTPNotFound(request=req, headers=headers)
        if hsh.find('-') >= 0:
            hsh = hsh.split('-', 1)[1]
        try:
            cdn_obj_path = self.get_hsh_obj_path(hsh)
        except ValueError, e:
            self.logger.debug('get_hsh_obj_path error: %s' % e)
            headers = self._getCacheHeaders(CACHE_BAD_URL)
            return HTTPBadRequest(request=req, headers=headers)
        hash_data = self.get_cdn_data(env, cdn_obj_path)
        if hash_data and hash_data.cdn_enabled:
            # this is a cdn enabled container, proxy req to swift
            if env.get('swift.cdn_authorize'):
                auth_resp, ttl = env['swift.cdn_authorize'](
                    env, hash_data.account.encode('utf-8'))
                if auth_resp:
                    return auth_resp(
                        request=req, headers=self._getCacheHeaders(ttl))
            swift_path = quote('/v1/%s/%s/' % (
                hash_data.account.encode('utf-8'),
                hash_data.container.encode('utf-8')))
            if object_name:
                swift_path += object_name
            headers = self._getCdnHeaders(req)
            env['swift.source'] = 'SOS'
            env['swift.leave_relative_location'] = True
            if not self.forward_origin:
                env.pop('HTTP_ORIGIN', None)
            resp = make_pre_authed_request(
                env, req.method, swift_path, headers=headers,
                agent='SwiftOrigin', swift_source='SOS').get_response(self.app)
            if resp.status_int == 301 and 'Location' in resp.headers:
                loc_parsed = urlparse(resp.headers['Location'])
                acc_cont_path = '/v1/%s/%s' % (
                    hash_data.account.encode('utf-8'),
                    hash_data.container.encode('utf-8'))
                if loc_parsed.path.startswith(acc_cont_path):
                    sos_loc = loc_parsed.path[len(acc_cont_path):]
                    resp = SosResponse(
                        headers=self._getCacheHeaders(hash_data.ttl))
                    resp.headers['Location'] = sos_loc
                    resp.status = 301
                    return resp
                else:
                    self.logger.exception(
                        'Unexpected Location header '
                        'returned.  %s does not begin with expected '
                        'path: %s' % (loc_parsed.geturl(), acc_cont_path))
                    return HTTPInternalServerError('Unexpected Relocation')
            if resp.status_int == 304:
                return HTTPNotModified(
                    request=req, headers=self._getCacheHeaders(hash_data.ttl))
            if resp.status_int == 416:
                return HTTPRequestedRangeNotSatisfiable(
                    request=req, headers=self._getCacheHeaders(CACHE_404))
            if resp.status_int // 100 == 2 or resp.status_int == 404 or (
                    resp.status_int == 401 and req.method == 'OPTIONS'):
                if resp.content_length > self.max_cdn_file_size:
                    return HTTPBadRequest(
                        request=req, headers=self._getCacheHeaders(CACHE_404))
                cdn_resp = Response(request=req, app_iter=resp.app_iter)
                cdn_resp.status = resp.status_int
                cdn_resp.headers.update(resp.headers)
                for allow_header in ['Access-Control-Allow-Methods', 'Allow']:
                    if allow_header in cdn_resp.headers:
                        cdn_resp.headers[allow_header] = 'GET, HEAD, OPTIONS'
                if resp.status_int in (404, 401):
                    cdn_resp.headers.update(self._getCacheHeaders(CACHE_404))
                else:
                    cdn_resp.headers.update(
                        self._getCacheHeaders(hash_data.ttl))
                return cdn_resp
            self.logger.error(
                'Unexpected response from '
                'Swift: %s, %s: %s' % (resp.status, swift_path,
                                       resp.body[:40]))
        return HTTPNotFound(request=req,
                            headers=self._getCacheHeaders(CACHE_404))
dataset/ETHPy150Open dpgoetz/sos/sos/origin.py/CdnHandler.handle_request/original