本文整理汇总了Python中httplib.BadStatusLine方法的典型用法代码示例。如果您正苦于以下问题:Python httplib.BadStatusLine方法的具体用法?Python httplib.BadStatusLine怎么用?Python httplib.BadStatusLine使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类httplib
的用法示例。
在下文中一共展示了httplib.BadStatusLine方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_handle_script_request_unexpected_instance_exception
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BadStatusLine [as 别名]
def test_handle_script_request_unexpected_instance_exception(self):
self.servr._instance_factory.new_instance(
mox.IgnoreArg(),
expect_ready_request=False).AndReturn(self.inst)
self.inst.start()
self.inst.handle(
self.environ,
self.start_response,
self.url_map,
self.match,
self.request_id,
instance.INTERACTIVE_REQUEST).AndRaise(httplib.BadStatusLine('line'))
self.mox.ReplayAll()
self.assertRaises(
httplib.BadStatusLine,
self.servr._handle_script_request,
self.environ,
self.start_response,
self.url_map,
self.match,
self.request_id)
self.mox.VerifyAll()
示例2: processTarget
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BadStatusLine [as 别名]
def processTarget(self, t, port):
if not self.seentarget(t + str(port)):
self.addseentarget(t + str(port))
self.display.verbose(self.shortName + " - Connecting to " + t)
try:
conn = httplib.HTTPConnection(t, port, timeout=10)
conn.request('GET', '/')
response = conn.getresponse()
serverver = response.getheader('server')
if (serverver):
outfile = self.config["proofsDir"] + self.shortName + "_" + t + "_" + str(
port) + "_" + Utils.getRandStr(10)
Utils.writeFile("Identified Server Version of %s : %s\n\nFull Headers:\n%s" % (
t, serverver, self.print_dict(response.getheaders())), outfile)
kb.add("host/" + t + "/files/" + self.shortName + "/" + outfile.replace("/", "%2F"))
except httplib.BadStatusLine:
pass
# except socket.error as e:
except:
pass
示例3: request
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BadStatusLine [as 别名]
def request(self, host, handler, request_body, verbose=0):
#retry request once if cached connection has gone cold
for i in (0, 1):
try:
return self.single_request(host, handler, request_body, verbose)
except socket.error, e:
if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE):
raise
except httplib.BadStatusLine: #close after we sent request
if i:
raise
##
# Send a complete request, and parse the response.
#
# @param host Target host.
# @param handler Target PRC handler.
# @param request_body XML-RPC request body.
# @param verbose Debugging flag.
# @return Parsed response.
示例4: test_status_lines
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BadStatusLine [as 别名]
def test_status_lines(self):
# Test HTTP status lines
body = "HTTP/1.1 200 Ok\r\n\r\nText"
sock = FakeSocket(body)
resp = httplib.HTTPResponse(sock)
resp.begin()
self.assertEqual(resp.read(0), '') # Issue #20007
self.assertFalse(resp.isclosed())
self.assertEqual(resp.read(), 'Text')
self.assertTrue(resp.isclosed())
body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
sock = FakeSocket(body)
resp = httplib.HTTPResponse(sock)
self.assertRaises(httplib.BadStatusLine, resp.begin)
示例5: _http_req
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BadStatusLine [as 别名]
def _http_req(self, method, path, payload=None, retries=2):
serialized_payload = json.dumps(payload) if payload is not None else None
try:
self._http.request(method, path, serialized_payload, self._COMMON_HEADERS)
http_response = self._http.getresponse()
except (http.BadStatusLine, http.CannotSendRequest):
self._http = http.HTTPConnection(self._host)
if retries > 0:
return self._http_req(method, path, payload, retries-1)
self._handle_error(self, None, Connection.OperationalError, "Connection has expired.")
if not http_response.status in [200, 201]:
message = "Server returned unexpected response: " + ustr(http_response.status) + ustr(http_response.read())
self._handle_error(self, None, Connection.OperationalError, message)
return http_response
示例6: catchupper
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BadStatusLine [as 别名]
def catchupper(pile, pile_catchup, twitterco, exit_event, debug=False):
while not exit_event.is_set() or not pile_catchup.empty():
todo = []
while not pile_catchup.empty() and len(todo) < 100:
todo.append(pile_catchup.get())
if todo:
try:
tweets = twitterco.statuses.lookup(_id=",".join(todo), tweet_mode="extended", _method="POST")
except (TwitterHTTPError, BadStatusLine, URLError, SSLError) as e:
log("WARNING", "API connection could not be established, retrying in 10 secs (%s: %s)" % (type(e), e))
for t in todo:
pile_catchup.put(t)
breakable_sleep(10, exit_event)
continue
if debug and tweets:
log("DEBUG", "[conversations] +%d tweets" % len(tweets))
for t in tweets:
t["gazouilloire_source"] = "thread"
pile.put(dict(t))
breakable_sleep(5, exit_event)
log("INFO", "FINISHED catchupper")
示例7: retry_http
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BadStatusLine [as 别名]
def retry_http( delays=default_delays, timeout=default_timeout, predicate=retryable_http_error ):
"""
>>> i = 0
>>> for attempt in retry_http(timeout=5): # doctest: +IGNORE_EXCEPTION_DETAIL
... with attempt:
... i += 1
... raise urllib.error.HTTPError('http://www.test.com', '408', 'some message', {}, None)
Traceback (most recent call last):
...
HTTPError: HTTP Error 408: some message
>>> i > 1
True
>>> i = 0
>>> for attempt in retry_http(timeout=5): # doctest: +IGNORE_EXCEPTION_DETAIL
... with attempt:
... i += 1
... raise BadStatusLine('sad-cloud.gif')
Traceback (most recent call last):
...
BadStatusLine: sad-cloud.gif
>>> i > 1
True
"""
return retry( delays=delays, timeout=timeout, predicate=predicate )
示例8: urlopen_house
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BadStatusLine [as 别名]
def urlopen_house(link,id):
#fetch html data on a house
numtries = 5
timeoutvalue = 40
for i in range(1,numtries+1):
i = str(i)
try:
u = urllib2.urlopen(link, timeout = timeoutvalue)
except BadStatusLine:
console_out('BadStatusLine for ID:' + id + '.' + ' Attempt: ' + i)
res = False
time.sleep(3)
except urllib2.URLError, e:
if hasattr(e, 'reason'):
console_out('We failed to reach a server for ID:' + id + ' Reason: ' + str(e.reason) + '.' + ' Attempt: ' + i)
elif hasattr(e, 'code'):
console_out('The server couldn\'t fulfill the request for ID: ' + id + ' Error code: ' + str(e.code) + '.' + ' Attempt: ' + i)
res = False
time.sleep(3)
except socket.timeout, e:
console_out('Connection timed out on urlopen() for ID: ' + id + '.' + ' Attempt: ' + i)
res = False
time.sleep(3)
示例9: run
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BadStatusLine [as 别名]
def run(self):
username, password = getword()
try:
print "-"*12
print "User:",username,"Password:",password
req = urllib2.Request(sys.argv[1])
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, sys.argv[1], username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
fd = opener.open(req)
print "\t\n\nUsername:",username,"Password:",password,"----- Login successful!!!\n\n"
print "Retrieved", fd.geturl()
info = fd.info()
for key, value in info.items():
print "%s = %s" % (key, value)
sys.exit(2)
except (urllib2.HTTPError, httplib.BadStatusLine,socket.error), msg:
print "An error occurred:", msg
pass
示例10: test_handle_script_request_restart
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BadStatusLine [as 别名]
def test_handle_script_request_restart(self):
def restart_and_raise(*args):
self.servr._inst = None
raise httplib.BadStatusLine('line')
start_response = start_response_utils.CapturingStartResponse()
self.servr._instance_factory.new_instance(
mox.IgnoreArg(),
expect_ready_request=False).AndReturn(self.inst)
self.inst.start()
self.inst.handle(
self.environ,
start_response,
self.url_map,
self.match,
self.request_id,
instance.INTERACTIVE_REQUEST).WithSideEffects(restart_and_raise)
self.mox.ReplayAll()
self.assertEqual(
['Instance was restarted while executing command'],
self.servr._handle_script_request(self.environ,
start_response,
self.url_map,
self.match,
self.request_id))
self.mox.VerifyAll()
self.assertEqual('503 Service Unavailable',
start_response.status)
示例11: request
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BadStatusLine [as 别名]
def request(self, host, handler, request_body, verbose=0):
"""Send XMLRPC request"""
uri = '{scheme}://{host}{handler}'.format(scheme=self._scheme,
host=host, handler=handler)
if self._passmgr:
self._passmgr.add_password(None, uri, self._username,
self._password)
if self.verbose:
_LOGGER.debug("FabricTransport: {0}".format(uri))
opener = urllib2.build_opener(*self._handlers)
headers = {
'Content-Type': 'text/xml',
'User-Agent': self.user_agent,
}
req = urllib2.Request(uri, request_body, headers=headers)
try:
return self.parse_response(opener.open(req))
except (urllib2.URLError, urllib2.HTTPError) as exc:
try:
code = -1
if exc.code == 400:
reason = 'Permission denied'
code = exc.code
else:
reason = exc.reason
msg = "{reason} ({code})".format(reason=reason, code=code)
except AttributeError:
if 'SSL' in str(exc):
msg = "SSL error"
else:
msg = str(exc)
raise InterfaceError("Connection with Fabric failed: " + msg)
except BadStatusLine:
raise InterfaceError("Connection with Fabric failed: check SSL")
示例12: processTarget
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BadStatusLine [as 别名]
def processTarget(self, t, port):
if not self.seentarget(t + str(port)):
self.addseentarget(t + str(port))
self.display.verbose(self.shortName + " - Connecting to " + t)
try:
conn = httplib.HTTPConnection(t, port, timeout=10)
conn.request('OPTIONS', '/')
response = conn.getresponse()
text = ""
allowed = response.getheader('allow')
outfile = self.config["proofsDir"] + self.shortName + "_" + t + "_" + str(
port) + "_" + Utils.getRandStr(10)
if (allowed):
badoptions = ['PUT', 'DELETE', 'TRACE', 'TRACK']
for badopt in badoptions:
if (allowed.contains(badopt)):
self.fire("httpOption" + badopt)
self.addVuln(t, "httpOption" + badopt,
{"port": str(port), "output": outfile.replace("/", "%2F")})
self.display.error("VULN [httpOption%s] Found on [%s:%i]" % (badopt, host, int(port)))
text = "Allowed HTTP Options for %s : %s\n\nFull Headers:\n%s" % (
t, allowed, self.print_dict(response.getheaders()))
else:
text = "Allowed HTTP Options for %s : OPTIONS VERB NOT ALLOWED\n\nFull Headers:\n%s" % (
t, self.print_dict(response.getheaders()))
Utils.writeFile(text, outfile)
except httplib.BadStatusLine:
pass
# except socket.error as e:
except:
pass
示例13: test_bad_status_repr
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BadStatusLine [as 别名]
def test_bad_status_repr(self):
exc = httplib.BadStatusLine('')
self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
示例14: test_overflowing_status_line
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BadStatusLine [as 别名]
def test_overflowing_status_line(self):
self.skipTest("disabled for HTTP 0.9 support")
body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
resp = httplib.HTTPResponse(FakeSocket(body))
self.assertRaises((httplib.LineTooLong, httplib.BadStatusLine), resp.begin)
示例15: test_error_leak
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BadStatusLine [as 别名]
def test_error_leak(self):
# Test that the socket is not leaked if getresponse() fails
conn = httplib.HTTPConnection('example.com')
response = []
class Response(httplib.HTTPResponse):
def __init__(self, *pos, **kw):
response.append(self) # Avoid garbage collector closing the socket
httplib.HTTPResponse.__init__(self, *pos, **kw)
conn.response_class = Response
conn.sock = FakeSocket('') # Emulate server dropping connection
conn.request('GET', '/')
self.assertRaises(httplib.BadStatusLine, conn.getresponse)
self.assertTrue(response)
#self.assertTrue(response[0].closed)
self.assertTrue(conn.sock.file_closed)