示例#1
0
def get_error_response(error):
    details, status_code = get_error_details_and_status(error)
    support_email = config.get("SUPPORT_EMAIL_FOR_ERRORS")
    app_name = config.get("APP_NAME", "Gen3 Data Commons")

    message = details.get("message")

    error_id = _get_error_identifier()
    logger.error("{} HTTP error occured. ID: {}\nDetails: {}".format(
        status_code, error_id, str(details)))

    # don't include internal details in the public error message
    if status_code == 500:
        message = None

    status_code_message = http_responses.get(status_code,
                                             "Unknown error code.")

    return (
        render_template(
            "error.html",
            app_name=app_name,
            status_code=status_code,
            status_code_message=status_code_message,
            support_email=support_email,
            error_id=error_id,
            message=message,
        ),
        status_code,
    )
示例#2
0
文件: http.py 项目: smartree/monocle
        def _handler(tornado_request):
            try:
                headers = HttpHeaders()
                for k, v in tornado_request.headers.get_all():
                    headers.add(k, v)

                body_file = io.BytesIO(tornado_request.body)
                request = HttpRequest(proto=tornado_request.version,
                                      host=tornado_request.host,
                                      method=tornado_request.method,
                                      uri=tornado_request.uri,
                                      args=tornado_request.arguments,
                                      remote_ip=tornado_request.remote_ip,
                                      headers=headers,
                                      body=tornado_request.body,
                                      body_file=body_file)
                request._tornado_request = tornado_request

                value = yield launch(self.handle_request, request)
                code, headers, content = extract_response(value)
            except Exception:
                code, headers, content = 500, {}, "500 Internal Server Error"
            tornado_request.write("HTTP/1.1 %s %s\r\n" %
                                  (code, responses.get(code, 'Unknown')))
            headers.setdefault('Server', 'monocle/%s' % VERSION)
            headers.setdefault('Content-Length', str(len(content)))
            for name, value in headers.iteritems():
                if isinstance(name, unicode):
                    name = name.encode('ascii')
                if isinstance(value, unicode):
                    value = value.encode('ascii')
                tornado_request.write("%s: %s\r\n" % (name, value))
            tornado_request.write("\r\n")
            tornado_request.write(content)
            tornado_request.finish()
示例#3
0
    def _on_request(self,
                    urlopen,
                    path,
                    pool,
                    method,
                    url,
                    body=None,
                    headers=None,
                    **kw):
        # Remove bypass headers
        real_headers = dict(headers or {})
        real_headers.pop(URLLIB3_BYPASS)

        # Create request contract based on incoming params
        req = Request(method)
        req.headers = real_headers
        req.body = body

        # Compose URL
        req.url = '{}://{}:{:d}{}'.format(pool.scheme, pool.host, pool.port
                                          or 80, url)

        # Match the request against the registered mocks in pook
        mock = self.engine.match(req)

        # If cannot match any mock, run real HTTP request since networking
        # or silent model will be enabled, otherwise this statement won't
        # be reached (an exception will be raised before).
        if not mock:
            return urlopen(pool, method, url, body=body, headers=headers, **kw)

        # Shortcut to mock response and response body
        res = mock._response
        body = res._body

        # Aggregate headers as list of tuples for interface compatibility
        headers = []
        for key in res._headers:
            headers.append((key, res._headers[key]))

        if is_chunked_response(headers):
            body_chunks = body if isinstance(body, list) else [body]
            body_chunks = [chunk.encode() for chunk in body_chunks]

            body = ClientHTTPResponse(MockSock)
            body.fp = FakeChunkedResponseBody(body_chunks)
        else:
            # Assume that the body is a bytes-like object
            body = body_io(body)

        # Return mocked HTTP response
        return HTTPResponse(
            path,
            body=body,
            status=res._status,
            headers=headers,
            preload_content=False,
            reason=http_reasons.get(res._status),
            original_response=FakeResponse(method, headers),
        )
示例#4
0
文件: http.py 项目: steenzout/monocle
        def _handler(tornado_request):
            try:
                headers = HttpHeaders()
                for k, v in tornado_request.headers.get_all():
                    headers.add(k, v)

                body_file = io.BytesIO(tornado_request.body)
                request = HttpRequest(proto=tornado_request.version,
                                      host=tornado_request.host,
                                      method=tornado_request.method,
                                      uri=tornado_request.uri,
                                      args=tornado_request.arguments,
                                      remote_ip=tornado_request.remote_ip,
                                      headers=headers,
                                      body=tornado_request.body,
                                      body_file=body_file)
                request._tornado_request = tornado_request

                value = yield launch(self.handle_request, request)
                code, headers, content = extract_response(value)
            except:
                code, headers, content = 500, {}, "500 Internal Server Error"
            tornado_request.write("HTTP/1.1 %s %s\r\n" %
                                  (code, responses.get(code, 'Unknown')))
            headers.setdefault('Server', 'monocle/%s' % VERSION)
            headers.setdefault('Content-Length', str(len(content)))
            for name, value in headers.iteritems():
                tornado_request.write("%s: %s\r\n" % (name, value))
            tornado_request.write("\r\n")
            tornado_request.write(content)
            tornado_request.finish()
示例#5
0
 def verifyHeader(self):
     """ raise an exceptions on bad headers """
     code = int(self.c.getinfo(pycurl.RESPONSE_CODE))
     if code in bad_headers:
         raise ResponseException(code,
                                 responses.get(code, "Unknown statuscode"))
     return code
示例#6
0
 def __init__(self, code, header="", content=""):
     int_code = int(code)
     Exception.__init__(self, "Bad server response: %s %s" %
                        (code, responses.get(int_code, unofficial_responses.get(int_code, "unknown error code"))))
     self.code = int_code
     self.header = header
     self.content = content
示例#7
0
    def _on_request(self,
                    _request,
                    conn,
                    method,
                    url,
                    body=None,
                    headers=None,
                    **kw):
        # Create request contract based on incoming params
        req = Request(method)
        req.headers = headers or {}
        req.body = body

        # Compose URL
        req.url = 'http://{}:{}{}'.format(conn.host, conn.port, url)

        # Match the request against the registered mocks in pook
        mock = self.engine.match(req)

        # If cannot match any mock, run real HTTP request since networking,
        # otherwise this statement won't be reached
        # (an exception will be raised before).
        if not mock:
            return _request(conn,
                            method,
                            url,
                            body=body,
                            headers=headers,
                            **kw)

        # Shortcut to mock response
        res = mock._response

        # Aggregate headers as list of tuples for interface compatibility
        headers = []
        for key in res._headers:
            headers.append((key, res._headers[key]))

        mockres = HTTPResponse(SocketMock(), method=method, url=url)
        mockres.version = (1, 1)
        mockres.status = res._status
        mockres.reason = http_reasons.get(res._status)
        mockres.headers = res._headers.to_dict()

        def getresponse():
            return mockres

        conn.getresponse = getresponse

        conn.__response = mockres
        conn.__state = _CS_REQ_SENT

        # Path reader
        def read():
            return res._body or ''

        mockres.read = read

        return mockres
示例#8
0
文件: handlers.py 项目: damnever/2L
 def write_error(self, status_code, **kwargs):
     message = ''
     if status_code:
         reason = responses.get(status_code, 'Unkonwn Error')
         message = '{0} {1}.'.format(status_code, reason)
     else:
         message = '500 Internal Server Error.'
     self.render('error.html', message=message)
示例#9
0
 def __str__(self):
     message = "HTTP %d: %s" % (
         self.status_code,
         self.reason or responses.get(self.status_code, 'Unknown'))
     if self.message:
         return message + " (" + (self.message % self.args) + ")"
     else:
         return message
示例#10
0
def envelope(success, code, msg, response):
    d = {"status": {  "success": success,
                      "code": code,
                      "codestr": responses.get(code, 'Unknown. FIXME!'),
                      "message": msg,
                   },
         "response": response,}
    return d
示例#11
0
文件: http.py 项目: aiex/requestspool
def show_response(status_code, headers, output, start_response):
    if status_code == TIMEOUT_STATUS_CODE:
        return requests_timeout(start_response)
    elif status_code == SERVICE_UNAVAILABLE_STATUS_CODE:
        return requests_service_unavailable(start_response)
    start_response(
        "{0} {1}".format(status_code, responses.get(status_code, 'OK')),
        headers.items())
    return (output,)
示例#12
0
 def handle(self, sock, read_data, path, headers):
     "Sends back a static error page."
     try:
         sock.sendall(
             "HTTP/1.0 %s %s\r\nConnection: close\r\nContent-length: 0\r\n\r\n"
             % (self.code, responses.get(self.code, "Unknown")))
     except socket.error, e:
         if e.errno != errno.EPIPE:
             raise
示例#13
0
def response_scrapy2mechanize(scrapy_response):
    url = scrapy_response.url.encode('utf8')
    code = scrapy_response.status
    msg = responses.get(code, '')
    headers = scrapy_response.headers
    headers = headers_scrapy2mechanize(headers)
    data = scrapy_response.body
    mechanize_response = make_response(data, headers, url, code, msg)
    return mechanize_response
示例#14
0
    def document(self):
        """Render the error document"""
        request = self._py_object.request
        resp = request.environ.get('pylons.original_response')

        code = cgi.escape(request.GET.get('code', str(resp.status_int)))
        message = error_names.get(int(code), '')

        response.headers['Content-Type'] = 'application/json; charset=utf-8'
        return '{"error":"%s","code":%s}' % (message, code)
示例#15
0
文件: http.py 项目: aiex/requestspool
def requests_service_unavailable(start_response):
    from httplib import SERVICE_UNAVAILABLE
    s = "server overload!"

    start_response("{0} {1}".format(SERVICE_UNAVAILABLE, responses.get(SERVICE_UNAVAILABLE, 'OK')), [
        ("Content-Type", "text/plain"),
        ("Content-Length", str(len(s)))
    ])

    return (s,)
示例#16
0
文件: http.py 项目: aiex/requestspool
def requests_timeout(start_response):
    from httplib import GATEWAY_TIMEOUT
    s = "requests timeout!"

    start_response("{0} {1}".format(GATEWAY_TIMEOUT, responses.get(GATEWAY_TIMEOUT, 'OK')), [
        ("Content-Type", "text/plain"),
        ("Content-Length", str(len(s)))
    ])

    return (s,)
示例#17
0
    def document(self):
        """Render the error document"""
        request = self._py_object.request
        resp = request.environ.get("pylons.original_response")

        code = cgi.escape(request.GET.get("code", str(resp.status_int)))
        message = error_names.get(int(code), "")

        response.headers["Content-Type"] = "application/json; charset=utf-8"
        return '{"error":"%s","code":%s}' % (message, code)
示例#18
0
    def _urlopen(self, pool, method, url, body=None, headers=None, **kwargs):
        request = self._request_class(method, url, body, headers, pool.scheme,
                                      pool.host, pool.port)
        match = self._find_match(request)

        if match is None:
            error_msg = 'Connection refused: {0} {1}'.format(
                request.method, request.url)
            response = self._error_class(error_msg)

            self._calls.add(request, response)
            raise response

        headers = [
            ('Content-Type', match['content_type']),
        ]

        if 'callback' in match:  # use callback
            status, r_headers, body = match['callback'](request)
            if isinstance(body, unicode):
                body = body.encode('utf-8')
        else:
            status, r_headers, body = match['return']

        if isinstance(body, Exception):
            self._calls.add(request, body)
            raise body

        if hasattr(status, 'split'):
            status, reason = status.split(None, 1)
            status = int(status)
        else:
            reason = http_reasons.get(status)

        if r_headers:
            if hasattr(r_headers, 'items'):
                r_headers = r_headers.items()
            for key, value in r_headers:
                if key.lower() == 'content-type':
                    if headers[0][0].lower() == 'content-type':
                        del headers[0]  # No duplicate content_type
                headers.append((key, value))

        response = self._response_class(
            status=status,
            reason=reason,
            body=BytesIO(body) if body else BytesIO(),
            headers=headers,
            preload_content=False,
            original_response=_FakeResponse(headers),
        )

        self._calls.add(request, response)
        return response
示例#19
0
文件: http.py 项目: ChrisWren/monocle
 def _handler(request):
     try:
         value = yield launch(self.handle_request, request)
         code, headers, content = extract_response(value)
     except:
         code, headers, content = 500, {}, "500 Internal Server Error"
     request.write("HTTP/1.1 %s %s\r\n" %
                   (code, responses.get(code, 'Unknown')))
     headers.setdefault('Server', 'monocle/%s' % VERSION)
     headers.setdefault('Content-Length', str(len(content)))
     for name, value in headers.iteritems():
         request.write("%s: %s\r\n" % (name, value))
     request.write("\r\n")
     request.write(content)
     request.finish()
示例#20
0
 def _handler(request):
     try:
         value = yield launch(self.handle_request, request)
         code, headers, content = extract_response(value)
     except:
         code, headers, content = 500, {}, "500 Internal Server Error"
     request.write("HTTP/1.1 %s %s\r\n" %
                   (code, responses.get(code, 'Unknown')))
     headers.setdefault('Server', 'monocle/%s' % VERSION)
     headers.setdefault('Content-Length', str(len(content)))
     for name, value in headers.iteritems():
         request.write("%s: %s\r\n" % (name, value))
     request.write("\r\n")
     request.write(content)
     request.finish()
示例#21
0
文件: error.py 项目: kurikintoki/ero
def http_error(environ, start_response, status_code, log_message=None, *args, **kwargs):
    reason = kwargs.get('reason', None)
    data = 'HTTP %d: %s' % (
        status_code,
        reason or responses.get(status_code, 'Unknown')
    )
    
    if log_message:
        data = data + " (" + (log_message % args) + ")"
        
    response_headers = [
        ('Content-Type', 'text/html charset=UTF-8')
    ]
        
    start_response(status_code, response_headers)
    return iter([data])
示例#22
0
    def request(self, host, handler, request_body, verbose=False):
        parser, unmarshaller = getparser()

        response = self.client.post(handler, request_body, 'text/xml')

        if response.status_code != 200:
            raise ProtocolError(
                '%s%s' % (host, handler),
                response.status_code,
                responses.get(response.status_code, ''),
                dict(response.items()),
            )

        parser.feed(response.content)

        return unmarshaller.close()
    def request(self, host, handler, request_body, verbose = False):
        parser, unmarshaller = getparser()

        response = self.client.post(handler, request_body, 'text/xml')

        if response.status_code != 200:
            raise ProtocolError(
              '%s%s' % (host, handler),
              response.status_code,
              responses.get(response.status_code, ''),
              dict(response.items()),
            )

        parser.feed(response.content)

        return unmarshaller.close()
示例#24
0
 def connectionLost(self, reason=connectionDone):
     """
     Overrides :meth:`.Protocol.connectionLost` and sets the ``_done``
     when complete.  When called with :class:`.ResponseDone` for ``reason``
     this method will call the callback on ``_deferred``
     """
     if reason.type is ResponseDone:
         self._done = True
         url = build_url(self.request.url, self.request.kwargs.get("params"))
         code_text = responses.get(self.code, "UNKNOWN")
         logger.debug(
             "%s %s %s %s, body: %s",
             self.code, code_text, self.request.method, url, self._body)
         self._deferred.callback(self)
     else:
         self._deferred.errback(reason)
示例#25
0
文件: app.py 项目: imbolc/httphq
    def get(self, status_code):
        status_code = int(status_code)
        if status_code not in responses.keys():
            raise HTTPError(404)

        self.set_status(status_code)

        if status_code in STATUSES_WITHOUT_BODY:
            self.finish()
        elif status_code in STATUSES_WITH_LOCATION:
            self.set_header("Location", self.request.host)
        elif status_code in STATUSES_WITH_AUHT:
            self.set_header("WWW-Authenticate", 'Basic realm="Fake Realm"')
        elif status_code in STATUSES_WITH_PROXY_AUTH:
            self.set_header("Proxy-Authenticate", 'Basic realm="Fake Realm"')
        else:
            self.json_response({"tagline": str(choice(taglines)),
                            "code": status_code,
                            "description": responses.get(status_code)})
示例#26
0
    def response(response, uid=None):
        """Logs the return code of a request that treq completed"""
        assert isinstance(response, TQResponse)
        assert isinstance(uid, UUID)

        message = "%s %s %s %s (uid: %s)"
        args = (
            response.code, responses.get(response.code, "UNKNOWN"),
            response.request.method, response.request.absoluteURI,
            uid.hex[20:]
        )

        if (response.code >= INTERNAL_SERVER_ERROR
                or response.code >= BAD_REQUEST):
            logger.error(message, *args)

        else:
            logger.info(message, *args)

        # Return so response can be handled by another callback
        return response
示例#27
0
 def _value_for_code(code):
     msg = STATUS_CODE_TEXT.get(code, "UNKNOWN STATUS CODE")
     return "HTTP/1.1 %d %s" % (code, msg)
示例#28
0
 def __init__(self, code, message=None):
     self.code = code
     message = message or responses.get(code, "Unknown")
     Exception.__init__(self, "%d: %s" % (self.code, message))
示例#29
0
文件: exceptions.py 项目: damnever/2L
 def __init__(self, code, **kwargs):
     super(HTTPError, self).__init__(code, **kwargs)
     if self.reason is None:
         self.reason = responses.get(code, 'Unkonwn')
示例#30
0
def all_req(environ, start_response):
    path_url = environ['PATH_INFO']
    assert path_url.startswith("/")
    path_url = path_url[1:]
    method = environ.get('REQUEST_METHOD').upper()

    if not (path_url.startswith(u"http://")
            or path_url.startswith(u"https://")):
        path_url = u"http://" + unicode(path_url)
    if path_url != u'http://favicon.ico':
        setattr(all_req, LAST_REQ_BASE_URL, get_base_url(path_url))
    else:
        path_url = getattr(all_req, LAST_REQ_BASE_URL, "") + "/favicon.ico"

    req_query_string = environ.get("QUERY_STRING", "")
    try:
        # 获取data
        req_data = environ['wsgi.input'].read(
            int(environ.get('CONTENT_LENGTH', '0')))
    except:
        req_data = None

    requestpool_headers = {}
    req_headers = {}
    for key, val in environ.iteritems():
        if key.startswith('HTTP_'):
            # 生成req_headers 暂无需求
            header_name = key[5:].replace('_', '-')
            if header_name == 'host'.upper():
                continue
            # 禁用缓存
            if "CACHE-CONTROL" in header_name:
                continue
            elif "IF-MODIFIED-SINCE" in header_name:
                continue
            # 禁用复用
            if "CONNECTION" in header_name:
                continue
            if "CACHE-CONTROL" in header_name:
                continue
            if 'REQUESTSPOOL.' in header_name:
                requestpool_headers[header_name] = val
            else:
                req_headers[header_name] = val

    status_code, headers, output = get_http_result(
        url=path_url,
        method=method,
        req_query_string=req_query_string,
        req_data=req_data,
        req_headers=req_headers)

    if "content-type" in headers and u'text/html' in headers.get(
            "content-type"):
        html = lxml.html.fromstring(output)

        html.rewrite_links(RewriteLink(get_base_url(path_url)))
        output = lxml.html.tostring(html)

    start_response(
        "{0} {1}".format(status_code, responses.get(status_code, 'OK')),
        headers.items())
    return (output, )
示例#31
0
class _Application:
    headers = {
        'content-type': 'text/html',
        'cache-control': 'no-cache, must-revalidate',
        'expires': 'Thu, 01 Jan 1970 00:00:00 GMT'
    }

    def __init__(self,
                 debug=False,
                 app_dir=None,
                 tmpl_conf={},
                 encoding='utf-8',
                 gzip=False,
                 web_dir=None,
                 cfg=object()):
        self.cfg = cfg
        self.aid = id(self)

        self.encoding = encoding
        self.debug = debug
        self.gzip = gzip
        self.app_dir = app_dir = os.path.abspath(app_dir)
        self.req_dir = os.path.join(self.app_dir, 'request')
        self.web_dir = web_dir or ''

        orig_dir = os.path.normpath(
            os.path.join(app_dir, tmpl_conf.get('orig_dir', 'tmpl/orig')))
        exec_dir = os.path.normpath(
            os.path.join(app_dir, tmpl_conf.get('exec_dir', 'tmpl/exec')))
        self.tmpl = TemplateLookup(orig_dir,
                                   exec_dir,
                                   debug,
                                   input_encoding=encoding,
                                   output_encoding=encoding)

        self.als = {}

        self.__modrefs = {}
        self.__threads = {}

    def cleanup(self):
        for m in self.__modrefs.values():
            m.cleanup()
        self.__modrefs.clear()
        self.__threads.clear()
        self.als.clear()

    def application(self, environ, start_response):
        ts = time.time()
        tid = thread.get_ident()
        tdata = self.__threads.get(tid)
        if tdata == None:
            #current_request, thread_local_storage, thread_module_refs
            tdata = self.__threads[tid] = [None, {}, {}]

        try:
            tdata[0] = req = Request(self, environ, tdata[1])

            #get module name
            pi = environ.get('PATH_INFO') or environ.get('SCRIPT_NAME')
            if pi != None and pi[:len(self.web_dir)] == self.web_dir:
                pi = pi[len(self.web_dir):]
                if pi[:1] != '/' or len(pi) == 1: pi = '/default'
            else:
                pi = '/default'

            #process request
            while pi:
                nz = os.path.normpath(self.req_dir + pi)
                if nz[:len(self.req_dir)] == self.req_dir and os.path.isfile(
                        nz + '.py'):
                    handler = self.load(nz[len(self.app_dir):]).RequestHandler
                else:
                    handler = RequestHandler

                #process request
                hinst = handler(req)
                try:
                    hinst.handle()
                except RequestExitException, ree:
                    pass
                finally:
                    hinst.cleanup()
                    hinst = None

                pi, req._next_req_handler = req._next_req_handler, None

            #build response
            status = req.out_status
            output = ''.join(req.out_res)
            cookie = [c.OutputString() for c in req.out_cookie.values()]
            status = "%s %s" % (status, responses.get(status, 'UNKNOWN'))
            headers = self.headers.copy()
            headers.update(req.out_headers)

            #gzip
            if self.gzip and output and not headers.has_key('content-encoding') \
            and environ.get('HTTP_ACCEPT_ENCODING', '').lower().find('gzip') >= 0:
                headers['content-encoding'] = 'gzip'
                gfp = cStringIO.StringIO()
                gzf = gzip.GzipFile(fileobj=gfp, mode='wb')
                gzf.write(output)
                gzf.close()
                output = gfp.getvalue()
                is_gzip = 1

            headers['content-length'] = len(output)
            headers = [(string.capwords(k, '-'), str(v))
                       for k, v in headers.items()]
            headers.extend([('Set-Cookie', c) for c in cookie])
示例#32
0
         gfp = cStringIO.StringIO()
         gzf = gzip.GzipFile(fileobj=gfp, mode='wb')
         gzf.write(output)
         gzf.close()
         output = gfp.getvalue()
         is_gzip = 1
     
     headers['content-length'] = len(output)
     headers = [ (string.capwords(k, '-'), str(v)) for k,v in headers.items() ]
     headers.extend( [ ('Set-Cookie', c) for c in cookie ] )
     
 except Exception, e:
     status = 200
     output = traceback.format_exc()
     if isinstance(output, unicode): output = output.encode(self.encoding)
     status = "%s %s" % (status, responses.get(status, 'UNKNOWN'))
     headers = self.headers.copy()
     headers['content-length'] = len(output)
     headers = [ (string.capwords(k, '-'), str(v)) for k,v in headers.items() ]
 
 finally:
     if tdata[0]:
         tdata[0].cleanup()
         tdata[0] = None
     if self.debug:
         tdata[1].clear()
         tdata[2].clear()
         self.als.clear()
 
 headers.append( ('SYS', 'TS:%0.3f, TID:%08X, AID:%08X' % (time.time() - ts, tid, self.aid)) )
 start_response(status, headers)
示例#33
0
 def handle(self, sock, read_data, path, headers):
     "Sends back a static error page."
     try:
         sock.sendall("HTTP/1.0 %s %s\r\nConnection: close\r\nContent-length: 0\r\n\r\n" % (self.code, responses.get(self.code, "Unknown")))
     except socket.error, e:
         if e.errno != errno.EPIPE:
             raise
示例#34
0
    def _on_request(self,
                    _request,
                    session,
                    method,
                    url,
                    data=None,
                    headers=None,
                    **kw):
        # Create request contract based on incoming params
        req = Request(method)
        req.headers = headers or {}
        req.body = data

        # Expose extra variadic arguments
        req.extra = kw

        # Compose URL
        if not kw.get('params'):
            req.url = str(url)
        else:
            req.url = str(url) + '?' + urlencode(
                [(x, y) for x, y in kw['params'].items()])

        # Match the request against the registered mocks in pook
        mock = self.engine.match(req)

        # If cannot match any mock, run real HTTP request if networking
        # or silent model are enabled, otherwise this statement won't
        # be reached (an exception will be raised before).
        if not mock:
            return _request(session,
                            method,
                            url,
                            data=data,
                            headers=headers,
                            **kw)

        # Simulate network delay
        if mock._delay:
            yield from asyncio.sleep(mock._delay / 1000)  # noqa

        # Shortcut to mock response
        res = mock._response

        # Aggregate headers as list of tuples for interface compatibility
        headers = []
        for key in res._headers:
            headers.append((key, res._headers[key]))

        # Create mock equivalent HTTP response
        _res = HTTPResponse(req.method, self._url(urlunparse(req.url)))

        # response status
        _res.version = (1, 1)
        _res.status = res._status
        _res.reason = http_reasons.get(res._status)
        _res._should_close = False

        # Add response headers
        _res._raw_headers = tuple(headers)
        _res._headers = multidict.CIMultiDictProxy(
            multidict.CIMultiDict(headers))

        if res._body:
            _res.content = SimpleContent(
                res._body.encode('utf-8', errors='replace'), )
        else:
            # Define `_content` attribute with an empty string to
            # force do not read from stream (which won't exists)
            _res.content = EmptyStreamReader()

        # Return response based on mock definition
        return _res
示例#35
0
def codestr(code):
    return HTTP_CODES.get(code, 'UNKNOWN')
示例#36
0
 def __init__(self, code, content=""):
     Exception.__init__(self, "Bad server response: %s %s" % (code, responses.get(int(code), "Unknown Header")))
     self.code = code
     self.content = content
示例#37
0
 def __init__(self, code, content=""):
     Exception.__init__(
         self, "Bad server response: %s %s" %
         (code, responses.get(int(code), "Unknown Header")))
     self.code = code
     self.content = content
示例#38
0
 def get_status_message(self, code):
     from httplib import responses
     return responses.get(self.code, 'Unknown status')
示例#39
0
 def _value_for_code(code):
     msg = STATUS_CODE_TEXT.get(code,"UNKNOWN STATUS CODE")
     return "HTTP/1.1 %d %s" % (code,msg)
示例#40
0
 def __init__(self, code, message=None, response=None):
     self.code = code
     self.message = message or responses.get(code, "Unknown")
     self.response = response
示例#41
0
                gzf.write(output)
                gzf.close()
                output = gfp.getvalue()
                is_gzip = 1

            headers['content-length'] = len(output)
            headers = [(string.capwords(k, '-'), str(v))
                       for k, v in headers.items()]
            headers.extend([('Set-Cookie', c) for c in cookie])

        except Exception, e:
            status = 200
            output = traceback.format_exc()
            if isinstance(output, unicode):
                output = output.encode(self.encoding)
            status = "%s %s" % (status, responses.get(status, 'UNKNOWN'))
            headers = self.headers.copy()
            headers['content-length'] = len(output)
            headers = [(string.capwords(k, '-'), str(v))
                       for k, v in headers.items()]

        finally:
            if tdata[0]:
                tdata[0].cleanup()
                tdata[0] = None
            if self.debug:
                tdata[1].clear()
                tdata[2].clear()
                self.als.clear()

        headers.append(('SYS', 'TS:%0.3f, TID:%08X, AID:%08X' %
示例#42
0
def codestr(code):
    return HTTP_CODES.get(code, 'UNKNOWN')
示例#43
0
文件: status.py 项目: dipstef/httpy
 def __init__(self, request, code, *args, **kwargs):
     super(HttpStatusCodeError, self).__init__(request, code, responses.get(code, ''), *args, **kwargs)
     self.code = code
     self.message = '%s on: %s' % (responses.get(code, '%s: %d' % (self.__class__.__name__, code)), str(request))
示例#44
0
def _example_v3(media_type_objects, method=None, endpoint=None, status=None,
                nb_indent=0):
    """
    Format examples in `Media Type Object` openapi v3 to HTTP request or
    HTTP response example.
    If method and endpoint is provided, this fonction prints a request example
    else status should be provided to print a response example.

    Args:
        - media_type_objects (Dict[str, Dict]): Dict containing
            Media Type Objects.
        - method: The HTTP method to use in example.
        - endpoint: The HTTP route to use in example.
        - status: The HTTP status to use in example.
    """
    # TODO: According to the openapi 3.0.0 spec, we should get example in
    # `schema` if the `example` or `examples` key is not provided.
    # https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#media-type-object

    indent = '   '
    extra_indent = indent * nb_indent

    if method is not None:
        method = method.upper()
    else:
        status_text = http_status_codes.get(int(status), '-')

    for content_type, content in media_type_objects.items():
        examples = content.get('examples')
        if examples is None:
            examples = {}
            if 'example' in content:
                if method is None:
                    examples['Example response'] = {
                        'value': content['example']
                    }
                else:
                    examples['Example request'] = {
                        'value': content['example']
                    }

        for example_name, example in examples.items():
            if 'summary' in example:
                example_title = '{example_name} - {example[summary]}'.format(
                    **locals())
            else:
                example_title = example_name

            yield ''
            yield '{extra_indent}**{example_title}:**'.format(**locals())
            yield ''
            yield '{extra_indent}.. sourcecode:: http'.format(**locals())
            yield ''

            # Print http response example
            if method:
                yield '{extra_indent}{indent}{method} {endpoint} HTTP/1.1' \
                    .format(**locals())
                yield '{extra_indent}{indent}Host: example.com' \
                    .format(**locals())
                yield '{extra_indent}{indent}Content-Type: {content_type}' \
                    .format(**locals())

            # Print http request example
            else:
                yield '{extra_indent}{indent}HTTP/1.1 {status} {status_text}' \
                    .format(**locals())
                yield '{extra_indent}{indent}Content-Type: {content_type}' \
                    .format(**locals())

            yield ''
            for example_line in example['value'].splitlines():
                yield '{extra_indent}{indent}{example_line}'.format(**locals())
            yield ''
示例#45
0
def responses(code):
	return _responses.get(code)
示例#46
0
 def verifyHeader(self):
     """ raise an exceptions on bad headers """
     code = int(self.c.getinfo(pycurl.RESPONSE_CODE))
     if code in bad_headers:
         raise ResponseException(code, responses.get(code, "Unknown statuscode"))
     return code
示例#47
0
def abort(status_code):
    raise ApiError(responses.get(status_code, ''), status_code=status_code)