Python http.client.responses() Examples
The following are 26
code examples of http.client.responses().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
http.client
, or try the search function
.
Example #1
Source File: httputil.py From teleport with Apache License 2.0 | 6 votes |
def write_headers(self, start_line, headers, chunk=None, callback=None): """Write an HTTP header block. :arg start_line: a `.RequestStartLine` or `.ResponseStartLine`. :arg headers: a `.HTTPHeaders` instance. :arg chunk: the first (optional) chunk of data. This is an optimization so that small responses can be written in the same call as their headers. :arg callback: a callback to be run when the write is complete. The ``version`` field of ``start_line`` is ignored. Returns a `.Future` if no callback is given. .. deprecated:: 5.1 The ``callback`` argument is deprecated and will be removed in Tornado 6.0. """ raise NotImplementedError()
Example #2
Source File: httputil.py From teleport with Apache License 2.0 | 6 votes |
def write_headers( self, start_line: Union["RequestStartLine", "ResponseStartLine"], headers: HTTPHeaders, chunk: bytes = None, ) -> "Future[None]": """Write an HTTP header block. :arg start_line: a `.RequestStartLine` or `.ResponseStartLine`. :arg headers: a `.HTTPHeaders` instance. :arg chunk: the first (optional) chunk of data. This is an optimization so that small responses can be written in the same call as their headers. The ``version`` field of ``start_line`` is ignored. Returns a future for flow control. .. versionchanged:: 6.0 The ``callback`` argument was removed. """ raise NotImplementedError()
Example #3
Source File: httputil.py From teleport with Apache License 2.0 | 6 votes |
def write_headers( self, start_line: Union["RequestStartLine", "ResponseStartLine"], headers: HTTPHeaders, chunk: bytes = None, ) -> "Future[None]": """Write an HTTP header block. :arg start_line: a `.RequestStartLine` or `.ResponseStartLine`. :arg headers: a `.HTTPHeaders` instance. :arg chunk: the first (optional) chunk of data. This is an optimization so that small responses can be written in the same call as their headers. The ``version`` field of ``start_line`` is ignored. Returns a future for flow control. .. versionchanged:: 6.0 The ``callback`` argument was removed. """ raise NotImplementedError()
Example #4
Source File: httputil.py From opendevops with GNU General Public License v3.0 | 6 votes |
def write_headers( self, start_line: Union["RequestStartLine", "ResponseStartLine"], headers: HTTPHeaders, chunk: bytes = None, ) -> "Future[None]": """Write an HTTP header block. :arg start_line: a `.RequestStartLine` or `.ResponseStartLine`. :arg headers: a `.HTTPHeaders` instance. :arg chunk: the first (optional) chunk of data. This is an optimization so that small responses can be written in the same call as their headers. The ``version`` field of ``start_line`` is ignored. Returns a future for flow control. .. versionchanged:: 6.0 The ``callback`` argument was removed. """ raise NotImplementedError()
Example #5
Source File: httputil.py From pySINDy with MIT License | 6 votes |
def write_headers(self, start_line, headers, chunk=None, callback=None): """Write an HTTP header block. :arg start_line: a `.RequestStartLine` or `.ResponseStartLine`. :arg headers: a `.HTTPHeaders` instance. :arg chunk: the first (optional) chunk of data. This is an optimization so that small responses can be written in the same call as their headers. :arg callback: a callback to be run when the write is complete. The ``version`` field of ``start_line`` is ignored. Returns a `.Future` if no callback is given. .. deprecated:: 5.1 The ``callback`` argument is deprecated and will be removed in Tornado 6.0. """ raise NotImplementedError()
Example #6
Source File: httputil.py From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International | 6 votes |
def write_headers( self, start_line: Union["RequestStartLine", "ResponseStartLine"], headers: HTTPHeaders, chunk: bytes = None, ) -> "Future[None]": """Write an HTTP header block. :arg start_line: a `.RequestStartLine` or `.ResponseStartLine`. :arg headers: a `.HTTPHeaders` instance. :arg chunk: the first (optional) chunk of data. This is an optimization so that small responses can be written in the same call as their headers. The ``version`` field of ``start_line`` is ignored. Returns a future for flow control. .. versionchanged:: 6.0 The ``callback`` argument was removed. """ raise NotImplementedError()
Example #7
Source File: __init__.py From fireREST with GNU General Public License v3.0 | 6 votes |
def _request(self, method: str, url: str, params=None, auth=None, data=None): if params: logger.info('[%s] %s?%s', method.upper(), url, urlencode(params)) else: logger.info('[%s] %s', method.upper(), url) if data: logger.debug(data) response = self.session.request( method=method, url=url, params=params, data=data, auth=auth, headers=self.headers, timeout=self.timeout, verify=self.verify_cert, ) logger.info('[RESPONSE] %s (%s)', http_responses[response.status_code], response.status_code) if response.text: if method == 'get': logger.debug('\n%s', json.dumps(response.json(), sort_keys=True, indent=4)) else: logger.debug(response.text) return response
Example #8
Source File: test_dj.py From restless with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_handle_build_err(self): # Special-cased above for testing. self.res.request = FakeHttpRequest('POST') settings.DEBUG = False self.addCleanup(setattr, settings, 'DEBUG', True) resp = self.res.handle('detail') self.assertEqual(resp['Content-Type'], 'application/json') self.assertEqual(resp.status_code, 500) self.assertEqual(resp.reason_phrase.title(), responses[500]) self.assertEqual(json.loads(resp.content.decode('utf-8')), { 'error': { 'code': 'random-crazy', 'message': 'This is a random & crazy exception.', } })
Example #9
Source File: test_httplib.py From android_universal with MIT License | 5 votes |
def test_responses(self): self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Example #10
Source File: test_httplib.py From android_universal with MIT License | 5 votes |
def test_all(self): # Documented objects defined in the module should be in __all__ expected = {"responses"} # White-list documented dict() object # HTTPMessage, parse_headers(), and the HTTP status code constants are # intentionally omitted for simplicity blacklist = {"HTTPMessage", "parse_headers"} for name in dir(client): if name.startswith("_") or name in blacklist: continue module_object = getattr(client, name) if getattr(module_object, "__module__", None) == "http.client": expected.add(name) self.assertCountEqual(client.__all__, expected)
Example #11
Source File: scanner.py From wagtail-linkchecker with BSD 3-Clause "New" or "Revised" License | 5 votes |
def message(self): if self.error: return self.error elif self.status_code in range(100, 300): message = "Success" elif self.status_code in range(500, 600) and self.url.startswith(self.site.root_url): message = str(self.status_code) + ': ' + _('Internal server error, please notify the site administrator.') else: try: message = str(self.status_code) + ': ' + client.responses[self.status_code] + '.' except KeyError: message = str(self.status_code) + ': ' + _('Unknown error.') return message
Example #12
Source File: test_dj.py From restless with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_http404_exception_handling(self): # Make sure we get a proper Not Found exception rather than a # generic 500, when code raises a Http404 exception. res = DjTestResourceHttp404Handling() res.request = FakeHttpRequest('GET') settings.DEBUG = False self.addCleanup(setattr, settings, 'DEBUG', True) resp = res.handle('detail', 1001) self.assertEqual(resp['Content-Type'], 'application/json') self.assertEqual(resp.status_code, 404) self.assertEqual(resp.reason_phrase.title(), responses[404]) self.assertEqual(json.loads(resp.content.decode('utf-8')), { 'error': 'Model with pk 1001 not found.' })
Example #13
Source File: test_dj.py From restless with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_object_does_not_exist(self): # Make sure we get a proper Not Found exception rather than a # generic 500, when code raises a ObjectDoesNotExist exception. self.res.request = FakeHttpRequest('GET') settings.DEBUG = False self.addCleanup(setattr, settings, 'DEBUG', True) resp = self.res.handle('detail', 1001) self.assertEqual(resp['Content-Type'], 'application/json') self.assertEqual(resp.status_code, 404) self.assertEqual(resp.reason_phrase.title(), responses[404]) self.assertEqual(json.loads(resp.content.decode('utf-8')), { 'error': 'Model with pk 1001 not found.' })
Example #14
Source File: test_dj.py From restless with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_handle_not_authenticated(self): # Special-cased above for testing. self.res.request = FakeHttpRequest('DELETE') # First with DEBUG on resp = self.res.handle('list') self.assertEqual(resp['Content-Type'], 'application/json') self.assertEqual(resp.status_code, 401) self.assertEqual(resp.reason_phrase.title(), responses[401]) resp_json = json.loads(resp.content.decode('utf-8')) self.assertEqual(resp_json['error'], 'Unauthorized.') self.assertIn('traceback', resp_json) # Now with DEBUG off. settings.DEBUG = False self.addCleanup(setattr, settings, 'DEBUG', True) resp = self.res.handle('list') self.assertEqual(resp['Content-Type'], 'application/json') self.assertEqual(resp.status_code, 401) resp_json = json.loads(resp.content.decode('utf-8')) self.assertEqual(resp_json, { 'error': 'Unauthorized.', }) self.assertNotIn('traceback', resp_json) # Last, with bubble_exceptions. class Bubbly(DjTestResource): def bubble_exceptions(self): return True with self.assertRaises(Unauthorized): bubb = Bubbly() bubb.request = FakeHttpRequest('DELETE') bubb.handle('list')
Example #15
Source File: test_dj.py From restless with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_handle_not_implemented(self): self.res.request = FakeHttpRequest('TRACE') resp = self.res.handle('list') self.assertEqual(resp['Content-Type'], 'application/json') self.assertEqual(resp.status_code, 501) self.assertEqual(resp.reason_phrase.title(), responses[501]) resp_json = json.loads(resp.content.decode('utf-8')) self.assertEqual( resp_json['error'], "Unsupported method 'TRACE' for list endpoint.") self.assertIn('traceback', resp_json)
Example #16
Source File: test_httplib.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_responses(self): self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Example #17
Source File: test_httplib.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_all(self): # Documented objects defined in the module should be in __all__ expected = {"responses"} # White-list documented dict() object # HTTPMessage, parse_headers(), and the HTTP status code constants are # intentionally omitted for simplicity blacklist = {"HTTPMessage", "parse_headers"} for name in dir(client): if name.startswith("_") or name in blacklist: continue module_object = getattr(client, name) if getattr(module_object, "__module__", None) == "http.client": expected.add(name) self.assertCountEqual(client.__all__, expected)
Example #18
Source File: utils.py From fireREST with GNU General Public License v3.0 | 5 votes |
def log_request(action): ''' decorator that adds additional debug logging for api requests ''' def inner_function(f): @wraps(f) def wrapper(*args, **kwargs): logger = args[0].logger request = args[1] request_id = str(uuid4())[:8] try: data = args[3] except IndexError: data = None logger.debug('[%s] [%s] %s', request_id, action, request) if data: logger.debug('[%s] [Data] %s', request_id, data) result = f(*args) status_code = result.status_code status_code_name = http_responses[status_code] logger.debug('[%s] [Response] %s (%s)', request_id, status_code_name, status_code) if status_code >= 299: logger.debug('[%s] [Message] %s', request_id, result.content) return result return wrapper return inner_function
Example #19
Source File: decorators.py From fireREST with GNU General Public License v3.0 | 5 votes |
def log_request(action): ''' decorator that adds additional debug logging for api requests ''' def inner_function(f): @wraps(f) def wrapper(*args, **kwargs): logger = args[0].logger request = args[1] request_id = str(uuid4())[:8] try: data = args[3] except IndexError: data = None logger.debug('[%s] [%s] %s', request_id, action, request) if data: logger.debug('[%s] [Data] %s', request_id, data) result = f(*args) status_code = result.status_code status_code_name = http_responses[status_code] logger.debug('[%s] [Response] %s (%s)', request_id, status_code_name, status_code) if status_code >= 299: logger.debug('[%s] [Message] %s', request_id, result.content) return result return wrapper return inner_function
Example #20
Source File: docnado.py From docnado with MIT License | 5 votes |
def detect_broken_links(self, process_pool): """ Go through all the `web_links` and the `relative_links` and report which are broken (i.e. do not resolve to HTTP200OK or a file on disk). """ result = process_pool.map(self.validate_url, self.web_links) for response, url in result: if not response == 200: yield url + ' Status: ' + (responses[response] if response is int else "Exception") for file in self.relative_links: if not os.path.exists(file): yield file
Example #21
Source File: test_httplib.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_responses(self): self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Example #22
Source File: test_httplib.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_all(self): # Documented objects defined in the module should be in __all__ expected = {"responses"} # White-list documented dict() object # HTTPMessage, parse_headers(), and the HTTP status code constants are # intentionally omitted for simplicity blacklist = {"HTTPMessage", "parse_headers"} for name in dir(client): if name in blacklist: continue module_object = getattr(client, name) if getattr(module_object, "__module__", None) == "http.client": expected.add(name) self.assertCountEqual(client.__all__, expected)
Example #23
Source File: test_httplib.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_responses(self): self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Example #24
Source File: test_httplib.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_all(self): # Documented objects defined in the module should be in __all__ expected = {"responses"} # White-list documented dict() object # HTTPMessage, parse_headers(), and the HTTP status code constants are # intentionally omitted for simplicity blacklist = {"HTTPMessage", "parse_headers"} for name in dir(client): if name in blacklist: continue module_object = getattr(client, name) if getattr(module_object, "__module__", None) == "http.client": expected.add(name) self.assertCountEqual(client.__all__, expected)
Example #25
Source File: minio_mocks.py From minio-py with Apache License 2.0 | 5 votes |
def __init__(self, method, url, headers, status_code, response_headers=None, content=None): self.method = method self.url = url self.request_headers = FoldCaseDict() for header in headers: self.request_headers[header] = headers[header] self.status = status_code self.headers = response_headers self.data = content if content is None: self.reason = httplib.responses[status_code] # noinspection PyUnusedLocal
Example #26
Source File: runapp.py From pdfminer3 with MIT License | 4 votes |
def run_cgi(self): rest = self.path i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = '/' + script scriptfile = self.translate_path(scriptname) env = {} env['SERVER_SOFTWARE'] = self.version_string() env['SERVER_NAME'] = self.server.server_name env['GATEWAY_INTERFACE'] = 'CGI/1.1' env['SERVER_PROTOCOL'] = self.protocol_version env['SERVER_PORT'] = str(self.server.server_port) env['REQUEST_METHOD'] = self.command uqrest = urllib.parse.unquote(rest) env['PATH_INFO'] = uqrest env['PATH_TRANSLATED'] = self.translate_path(uqrest) env['SCRIPT_NAME'] = scriptname if query: env['QUERY_STRING'] = query host = self.address_string() if host != self.client_address[0]: env['REMOTE_HOST'] = host env['REMOTE_ADDR'] = self.client_address[0] if self.headers.typeheader is None: env['CONTENT_TYPE'] = self.headers.type else: env['CONTENT_TYPE'] = self.headers.typeheader length = self.headers.getheader('content-length') if length: env['CONTENT_LENGTH'] = length accept = [] for line in self.headers.getallmatchingheaders('accept'): if line[:1] in "\t\n\r ": accept.append(line.strip()) else: accept = accept + line[7:].split(',') env['HTTP_ACCEPT'] = ','.join(accept) ua = self.headers.getheader('user-agent') if ua: env['HTTP_USER_AGENT'] = ua co = [_f for _f in self.headers.getheaders('cookie') if _f] if co: env['HTTP_COOKIE'] = ', '.join(co) for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH', 'HTTP_USER_AGENT', 'HTTP_COOKIE'): env.setdefault(k, "") app = self.APP_CLASS(infp=self.rfile, outfp=self.wfile, environ=env) status = app.setup() self.send_response(status, responses[status]) app.run() return # main