Python httplib.responses() Examples
The following are 30
code examples of httplib.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
httplib
, or try the search function
.
Example #1
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 #2
Source File: labels.py From encompass with GNU General Public License v3.0 | 6 votes |
def set_label(self, item,label, changed): if self.encode_password is None: return if not changed: return try: bundle = {"label": {"external_id": self.encode(item), "text": self.encode(label)}} params = json.dumps(bundle) connection = httplib.HTTPConnection(self.target_host) connection.request("POST", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())), params, {'Content-Type': 'application/json'}) response = connection.getresponse() if response.reason == httplib.responses[httplib.NOT_FOUND]: return response = json.loads(response.read()) except socket.gaierror as e: print_error('Error connecting to service: %s ' % e) return False
Example #3
Source File: NTLMAuthHandler.py From pth-toolkit with BSD 2-Clause "Simplified" License | 6 votes |
def _in_progress_response(start_response, ntlm_data=None, client_id=None, cookie_name=None): status = "401 %s" % httplib.responses[401] content = "More data needed..." headers = [("Content-Type", "text/plain"), ("Content-Length", "%d" % len(content))] if ntlm_data is None: www_auth_value = "NTLM" else: enc_ntlm_data = ntlm_data.encode("base64") www_auth_value = ("NTLM %s" % enc_ntlm_data.strip().replace("\n", "")) if client_id is not None: # MUST occur when ntlm_data is None, can still occur otherwise headers.append(("Set-Cookie", "%s=%s" % (cookie_name, client_id))) headers.append(("WWW-Authenticate", www_auth_value)) start_response(status, headers) return [content]
Example #4
Source File: blob_image.py From browserscope with Apache License 2.0 | 6 votes |
def serve_image(self, environ, start_response): """Dynamically serve an image from blobstore.""" blobkey, options = self._parse_path(environ['PATH_INFO']) # Make sure that the blob URL has been registered by # calling get_serving_url key = datastore.Key.from_path(_BLOB_SERVING_URL_KIND, blobkey, namespace='') try: datastore.Get(key) except datastore_errors.EntityNotFoundError: logging.error('The blobkey %s has not registered for image ' 'serving. Please ensure get_serving_url is ' 'called before attempting to serve blobs.', blobkey) start_response('404 %s' % httplib.responses[404], []) return [] image, mime_type = self._transform_image(blobkey, options) start_response('200 OK', [ ('Content-Type', mime_type), ('Cache-Control', 'public, max-age=600, no-transform')]) return [image]
Example #5
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 #6
Source File: apiserving.py From endpoints-python with Apache License 2.0 | 6 votes |
def __write_error(self, status_code, error_message=None): """Return the HTTP status line and body for a given error code and message. Args: status_code: HTTP status code to be returned. error_message: Error message to be returned. Returns: Tuple (http_status, body): http_status: HTTP status line, e.g. 200 OK. body: Body of the HTTP request. """ if error_message is None: error_message = httplib.responses[status_code] status = '%d %s' % (status_code, httplib.responses[status_code]) message = EndpointsErrorMessage( state=EndpointsErrorMessage.State.APPLICATION_ERROR, error_message=error_message) return status, self.__PROTOJSON.encode_message(message)
Example #7
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 #8
Source File: A10_LADS_Connector.py From Phantom-Cyber with MIT License | 6 votes |
def _test_connectivity(self, param, LADS): """ Called when the user depresses the test connectivity button on the Phantom UI. This query returns a list of configured applications https://api.a10networks.com/api/v2/applications """ self.debug_print("%s _test_connectivity %s" % (A10_LADS_Connector.BANNER, param)) msg = "test connectivity to %s status_code: " % (LADS.dashboard) if LADS.genericGET(uri="/api/v2/applications"): # True is success return self.set_status_save_progress(phantom.APP_SUCCESS, msg + "%s %s apps: %s" % (LADS.status_code, httplib.responses[LADS.status_code], LADS.get_names(LADS.response))) else: # None or False, is a failure based on incorrect IP address, username, passords return self.set_status_save_progress(phantom.APP_ERROR, msg + "%s %s" % (LADS.status_code, LADS.response))
Example #9
Source File: web.py From honeything with GNU General Public License v3.0 | 6 votes |
def _handle_request_exception(self, e): if isinstance(e, HTTPError): if e.log_message: format = "%d %s: " + e.log_message args = [e.status_code, self._request_summary()] + list(e.args) #logging.warning(format, *args) ht.logger.warning(format, *args) if e.status_code not in httplib.responses: #logging.error("Bad HTTP status code: %d", e.status_code) ht.logger.error("Bad HTTP status code: %d", e.status_code) self.send_error(500, exc_info=sys.exc_info()) else: self.send_error(e.status_code, exc_info=sys.exc_info()) else: #logging.error("Uncaught exception %s\n%r", self._request_summary(), # self.request, exc_info=True) ht.logger.error("Uncaught exception %s\n%r", self._request_summary(), self.request, exc_info=True) self.send_error(500, exc_info=sys.exc_info())
Example #10
Source File: F5_connector.py From Phantom-Cyber with MIT License | 6 votes |
def _test_connectivity(self, param): """ Called when the user depresses the test connectivity button on the Phantom UI. Use a basic query to determine if the IP address, username and password is correct, curl -k -u admin:redacted -X GET https://192.0.2.1/mgmt/tm/ltm/ """ self.debug_print("%s TEST_CONNECTIVITY %s" % (F5_Connector.BANNER, param)) config = self.get_config() host = config.get("device") F5 = iControl.BIG_IP(host=host, username=config.get("username"), password=config.get("password"), uri="/mgmt/tm/sys/software/image", method="GET") msg = "test connectivity to %s status_code: " % host if F5.genericGET(): # True is success return self.set_status_save_progress(phantom.APP_SUCCESS, msg + "%s %s" % (F5.status_code, httplib.responses[F5.status_code])) else: # None or False, is a failure based on incorrect IP address, username, passords return self.set_status_save_progress(phantom.APP_ERROR, msg + "%s %s" % (F5.status_code, F5.response))
Example #11
Source File: blob_image.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def __call__(self, environ, start_response): if environ['REQUEST_METHOD'] != 'GET': start_response('405 %s' % httplib.responses[405], []) return [] try: return self.serve_image(environ, start_response) except InvalidRequestError: start_response('400 %s' % httplib.responses[400], []) return []
Example #12
Source File: webserver.py From LibreNews-Server with GNU General Public License v3.0 | 5 votes |
def write_error(self, status_code, **kwargs): self.render("pages/error.html", message=httplib.responses[status_code], error=status_code)
Example #13
Source File: module.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def _error_response(self, environ, start_response, status, body=None): if body: start_response( '%d %s' % (status, httplib.responses[status]), [('Content-Type', 'text/html'), ('Content-Length', str(len(body)))]) return body start_response('%d %s' % (status, httplib.responses[status]), []) return []
Example #14
Source File: test_httplib.py From medicare-demo with Apache License 2.0 | 5 votes |
def test_responses(self): self.assertEquals(httplib.responses[httplib.NOT_FOUND], "Not Found")
Example #15
Source File: test_urllib2.py From medicare-demo with Apache License 2.0 | 5 votes |
def http_open(self, req): import mimetools, httplib, copy from StringIO import StringIO self.requests.append(copy.deepcopy(req)) if self._count == 0: self._count = self._count + 1 name = httplib.responses[self.code] msg = mimetools.Message(StringIO(self.headers)) return self.parent.error( "http", req, MockFile(), self.code, name, msg) else: self.req = req msg = mimetools.Message(StringIO("\r\n\r\n")) return MockResponse(200, "OK", msg, "", req.get_full_url())
Example #16
Source File: common.py From EasY_HaCk with Apache License 2.0 | 5 votes |
def showHttpErrorCodes(): """ Shows all HTTP error codes raised till now """ if kb.httpErrorCodes: warnMsg = "HTTP error codes detected during run:\n" warnMsg += ", ".join("%d (%s) - %d times" % (code, httplib.responses[code] if code in httplib.responses else '?', count) for code, count in kb.httpErrorCodes.items()) logger.warn(warnMsg) if any((str(_).startswith('4') or str(_).startswith('5')) and _ != httplib.INTERNAL_SERVER_ERROR and _ != kb.originalCode for _ in kb.httpErrorCodes.keys()): msg = "too many 4xx and/or 5xx HTTP error codes " msg += "could mean that some kind of protection is involved (e.g. WAF)" logger.debug(msg)
Example #17
Source File: webserver.py From LibreNews-Server with GNU General Public License v3.0 | 5 votes |
def write_error(self, status_code, **kwargs): self.render("pages/error.html", message=httplib.responses[status_code], error=status_code)
Example #18
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 #19
Source File: baseServer.py From DDDProxy with Apache License 2.0 | 5 votes |
def makeReseponse(self, data, ContentType="text/html", code=200, connection="close", header={}): def httpdate(): dt = datetime.now(); weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()] month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][dt.month - 1] return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month, dt.year, dt.hour, dt.minute, dt.second) if type(data) is unicode: data = data.encode("utf-8") elif not type(data) is str: try: data = json.dumps(data) except: log.log(3, data) data = "error" ContentType = "application/json" httpMessage = "" httpMessage += "HTTP/1.1 " + str(code) + " " + (httplib.responses[code]) + "\r\n" httpMessage += "Server: DDDProxy/%s\r\n"%(version) httpMessage += "Date: " + httpdate() + "\r\n" httpMessage += "Content-Length: " + str(len(data)) + "\r\n" httpMessage += "Content-Type: " + ContentType + "\r\n" httpMessage += "Connection: " + connection + "\r\n" for k, v in header.items(): httpMessage += k + ": " + v + "\r\n" httpMessage += "\r\n" httpMessage += data return httpMessage
Example #20
Source File: blob_image.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def serve_image(self, environ, start_response): """Dynamically serve an image from blobstore.""" blobkey, options = self._parse_path(environ['PATH_INFO']) # Make sure that the blob URL has been registered by # calling get_serving_url key = datastore.Key.from_path(_BLOB_SERVING_URL_KIND, blobkey, namespace='') try: datastore.Get(key) except datastore_errors.EntityNotFoundError: logging.error('The blobkey %s has not registered for image ' 'serving. Please ensure get_serving_url is ' 'called before attempting to serve blobs.', blobkey) start_response('404 %s' % httplib.responses[404], []) return [] resize, crop = self._parse_options(options) if resize is None and not crop: return self.serve_unresized_image(blobkey, environ, start_response) elif not _HAS_WORKING_IMAGES_STUB: logging.warning('Serving resized images requires a working Python "PIL" ' 'module. The image is served without resizing.') return self.serve_unresized_image(blobkey, environ, start_response) else: # Use Images service to transform blob. image, mime_type = self._transform_image(blobkey, resize, crop) start_response('200 OK', [ ('Content-Type', mime_type), ('Cache-Control', 'public, max-age=600, no-transform')]) return [image]
Example #21
Source File: blob_image_test.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def test_invalid_options(self): """Tests an image request with an invalid size.""" self.expect_datatore_lookup('SomeBlobKey', True) self.expect_open_image('SomeBlobKey', (1600, 1200)) self._environ['PATH_INFO'] += '=s%s' % (blob_image._SIZE_LIMIT + 1) self.mox.ReplayAll() self.assertResponse('400 %s' % httplib.responses[400], [], '', self.app, self._environ)
Example #22
Source File: blob_image_test.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def test_invalid_url(self): """Tests an image request with an invalid path.""" self._environ['PATH_INFO'] = '/_ah/img/' self.mox.ReplayAll() self.assertResponse('400 %s' % httplib.responses[400], [], '', self.app, self._environ)
Example #23
Source File: blob_image_test.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def test_not_get(self): """Tests POSTing to a url.""" self._environ['REQUEST_METHOD'] = 'POST' self.assertResponse('405 %s' % httplib.responses[405], [], '', self.app, self._environ)
Example #24
Source File: grpc_port.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def __call__(self, environ, start_response): """Handles WSGI requests. Args: environ: An environ dict for the current request as defined in PEP-333. start_response: A function with semantics defined in PEP-333. Returns: An environment variable GRPC_PORT. """ start_response('200 %s' % httplib.responses[200], []) return os.environ['GRPC_PORT']
Example #25
Source File: wsgi_server.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def __call__(self, environ, start_response): with self._lock: app = self._app error = self._error if app: return app(environ, start_response) else: start_response('%d %s' % (error, httplib.responses[error]), []) return []
Example #26
Source File: static_files_handler.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def _not_found_404(environ, start_response): status = httplib.NOT_FOUND start_response('%d %s' % (status, httplib.responses[status]), [('Content-Type', 'text/plain')]) return ['%s not found' % environ['PATH_INFO']]
Example #27
Source File: dispatcher.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def response_for_error(http_status): """Given an HTTP status code, returns a simple HTML error message.""" return wrappers.Response( ERROR_TEMPLATE.format(http_status=http_status, message=httplib.responses[http_status]), status=http_status)
Example #28
Source File: test_urllib2.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def http_open(self, req): import mimetools, httplib, copy from StringIO import StringIO self.requests.append(copy.deepcopy(req)) if self._count == 0: self._count = self._count + 1 name = httplib.responses[self.code] msg = mimetools.Message(StringIO(self.headers)) return self.parent.error( "http", req, MockFile(), self.code, name, msg) else: self.req = req msg = mimetools.Message(StringIO("\r\n\r\n")) return MockResponse(200, "OK", msg, "", req.get_full_url())
Example #29
Source File: test_httplib.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_responses(self): self.assertEqual(httplib.responses[httplib.NOT_FOUND], "Not Found")
Example #30
Source File: web.py From honeything with GNU General Public License v3.0 | 5 votes |
def _generate_headers(self): lines = [self.request.version + " " + str(self._status_code) + " " + httplib.responses[self._status_code]] lines.extend(["%s: %s" % (n, v) for n, v in self._headers.iteritems()]) for cookie_dict in getattr(self, "_new_cookies", []): for cookie in cookie_dict.values(): lines.append("Set-Cookie: " + cookie.OutputString(None)) return "\r\n".join(lines) + "\r\n\r\n"