buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
from django.core.exceptions import SuspiciousOperation from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.http import ( HttpRequest, HttpResponse, RawPostDataException, UnreadablePostError, build_request_repr, parse_cookie, ) from django.test import RequestFactory, SimpleTestCase, over...
from django.core.exceptions import SuspiciousOperation from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.http import ( HttpRequest, HttpResponse, RawPostDataException, UnreadablePostError, build_request_repr, ) from django.test import RequestFactory, SimpleTestCase, override_settings ...
class RequestsTests(SimpleTestCase): request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, "/سلام/") def test_parse_cookie(self): self.assertEqual(parse_cookie('invalid@key=true'), {}) def test_httpr...
class RequestsTests(SimpleTestCase): request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, "/سلام/") def test_httprequest_location(self): request = HttpRequest() self.assertEqual(request.build_abs...
def do_setup(): 'gunicorn>=19.5.0, <20.0', 'iso8601>=0.1.12', 'json-merge-patch==0.2', 'jinja2>=2.7.3, <=2.10.0', 'lxml>=4.0.0', 'markdown>=2.5.2, <3.0', 'pandas>=0.17.1, <1.0.0', 'pendulum==1.4.4',
def do_setup(): 'gunicorn>=19.5.0, <20.0', 'iso8601>=0.1.12', 'json-merge-patch==0.2', 'jinja2>=2.10.1, <2.11.0', 'markdown>=2.5.2, <3.0', 'pandas>=0.17.1, <1.0.0', 'pendulum==1.4.4',
class VComment(mutagen.Metadata, list): count = cdata.uint_le(fileobj.read(4)) for i in range(count): length = cdata.uint_le(fileobj.read(4)) string = fileobj.read(length).decode('utf-8', errors) try: tag, value = string.split('=', 1) ...
class VComment(mutagen.Metadata, list): count = cdata.uint_le(fileobj.read(4)) for i in range(count): length = cdata.uint_le(fileobj.read(4)) try: string = fileobj.read(length).decode('utf-8', errors) except (OverflowError, MemoryError): ...
class MetadataBlock(object): codes[-1][0] |= 128 for code, datum in codes: byte = chr(code) length = struct.pack(">I", len(datum))[-3:] data.append(byte + length + datum) return "".join(data)
class MetadataBlock(object): codes[-1][0] |= 128 for code, datum in codes: byte = chr(code) if len(datum) > 2**24: raise error("block is too long to write") length = struct.pack(">I", len(datum))[-3:] data.append(byte + length + datum) ...
class Padding(MetadataBlock): def __init__(self, data=""): super(Padding, self).__init__(data) def load(self, data): self.length = len(data.read()) def write(self): return "\x00" * self.length def __eq__(self, other): return isinstance(other, Padding) and self.length == other.length def __r...
class Padding(MetadataBlock): def __init__(self, data=""): super(Padding, self).__init__(data) def load(self, data): self.length = len(data.read()) def write(self): try: return "\x00" * self.length except OverflowError: raise error("cannot write %d bytes" % self.length) def ...
class FLAC(FileType): size = to_int_be(file.read(3)) try: data = file.read(size) block = self.METADATA_BLOCKS[byte & 0x7F](data) except (IndexError, TypeError): block = MetadataBlock(data)
class FLAC(FileType): size = to_int_be(file.read(3)) try: data = file.read(size) if len(data) != size: raise error( "file said %d bytes, read %d bytes" % (size, len(data))) block = self.METADATA_BLOCKS[byte & 0x7F](data) exc...
class TFLACFile(TestCase): add(TFLACFile) NOTFOUND = os.system("tools/notarealprogram 2> %s" % devnull) have_flac = True
class TFLACFile(TestCase): add(TFLACFile) class CVE20074619(TestCase): uses_mmap = True # Tests to ensure Mutagen is not vulnerable to a number of security # issues found in libFLAC. # http://research.eeye.com/html/advisories/published/AD20071115.html def test_1(self): # "Editing any Met...
class FrameIDValidate(TestCase): self.failIf(is_valid_frame_id("+ABC")) class BadTYER(TestCase): filename = join('tests', 'data', 'bad-TYER-frame.mp3') def setUp(self): self.audio = ID3(self.filename)
class FrameIDValidate(TestCase): self.failIf(is_valid_frame_id("+ABC")) class BadTYER(TestCase): uses_mmap = False filename = join('tests', 'data', 'bad-TYER-frame.mp3') def setUp(self): self.audio = ID3(self.filename)
class GalaxyCLI(CLI): ''' create an options parser for bin/ansible ''' super(GalaxyCLI, self).init_parser( desc="Perform various Role related operations.", ) # common
class GalaxyCLI(CLI): ''' create an options parser for bin/ansible ''' super(GalaxyCLI, self).init_parser( desc="Perform various Role and Collection related operations.", ) # common
class GalaxyCLI(CLI): obj_name = context.CLIARGS['{0}_name'.format(galaxy_type)] inject_data = dict( description='your description', ansible_plugin_list_dir=get_versioned_doclink('plugins/plugins.html'), ) if galaxy_type == 'role':
class GalaxyCLI(CLI): obj_name = context.CLIARGS['{0}_name'.format(galaxy_type)] inject_data = dict( description='your {0} description'.format(galaxy_type), ansible_plugin_list_dir=get_versioned_doclink('plugins/plugins.html'), ) if galaxy_type == 'role':
class GalaxyCLI(CLI): if not os.path.exists(b_dir_path): os.makedirs(b_dir_path) display.display("- %s was created successfully" % obj_name) def execute_info(self): """
class GalaxyCLI(CLI): if not os.path.exists(b_dir_path): os.makedirs(b_dir_path) display.display("- %s %s was created successfully" % (galaxy_type.title(), obj_name)) def execute_info(self): """
def test_collection_default(collection_skeleton): assert metadata['authors'] == ['your name <example@domain.com>'] assert metadata['readme'] == 'README.md' assert metadata['version'] == '1.0.0' assert metadata['description'] == 'your description' assert metadata['license'] == ['GPL-2.0-or-later'] ...
def test_collection_default(collection_skeleton): assert metadata['authors'] == ['your name <example@domain.com>'] assert metadata['readme'] == 'README.md' assert metadata['version'] == '1.0.0' assert metadata['description'] == 'your collection description' assert metadata['license'] == ['GPL-2.0-or...
def test_collection_build(collection_artifact): assert coll_info['authors'] == ['your name <example@domain.com>'] assert coll_info['readme'] == 'README.md' assert coll_info['tags'] == [] assert coll_info['description'] == 'your description' assert coll_info['license'] == ['GPL-2....
def test_collection_build(collection_artifact): assert coll_info['authors'] == ['your name <example@domain.com>'] assert coll_info['readme'] == 'README.md' assert coll_info['tags'] == [] assert coll_info['description'] == 'your collection description' assert coll_info['license'] ...
class Errors(object): "details: https://spacy.io/api/lemmatizer#init") E174 = ("Architecture '{name}' not found in registry. Available " "names: {names}") @add_codes
class Errors(object): "details: https://spacy.io/api/lemmatizer#init") E174 = ("Architecture '{name}' not found in registry. Available " "names: {names}") E175 = ("Can't remove rule for unknown match pattern ID: {key}") @add_codes
def test_matcher_sets_return_correct_tokens(en_vocab): matches = matcher(doc) texts = [Span(doc, s, e, label=L).text for L, s, e in matches] assert texts == ["zero", "one", "two"]
def test_matcher_sets_return_correct_tokens(en_vocab): matches = matcher(doc) texts = [Span(doc, s, e, label=L).text for L, s, e in matches] assert texts == ["zero", "one", "two"] def test_matcher_remove(en_vocab): matcher = Matcher(en_vocab) pattern = [{"ORTH": "test"}, {"OP": "?"}] assert le...
def setUp(self): def tearDown(self): # wait on the server thread to terminate self.evt.wait(4.0) # XXX this code does not work, and in fact stop_serving doesn't exist. if not self.evt.is_set(): self.evt.set() stop_serving() raise RuntimeError("tim...
def setUp(self): def tearDown(self): # wait on the server thread to terminate self.evt.wait() # disable traceback reporting xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = False
def test_unicode_host(self): server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT)) self.assertEqual(server.add("a", "\xe9"), "a\xe9") class MultiPathServerTestCase(BaseServerTestCase): threadFunc = staticmethod(http_multi_server) request_count = 2
def test_unicode_host(self): server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT)) self.assertEqual(server.add("a", "\xe9"), "a\xe9") def test_partial_post(self): # Check that a partial POST doesn't make the server loop: issue #14001. conn = http.client.HTTPConnection(A...
def do_POST(self): L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) L.append(self.rfile.read(chunk_size)) size_remaining -= len(L[-1]) data = b''.join(L)
def do_POST(self): L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk = self.rfile.read(chunk_size) if not chunk: break L.append(chunk) size_remaining -= len(L[-1]...
import time import traceback import math from tornado.concurrent import TracebackFuture, is_future from tornado.log import app_log, gen_log from tornado.platform.auto import set_close_exec, Waker from tornado import stack_context
import time import traceback import math from tornado.concurrent import TracebackFuture, is_future, chain_future from tornado.log import app_log, gen_log from tornado.platform.auto import set_close_exec, Waker from tornado import stack_context
class IOLoop(Configurable): from tornado.process import cpu_count self._executor = ThreadPoolExecutor(max_workers=(cpu_count() * 5)) executor = self._executor return executor.submit(func, *args) def set_default_executor(self, executor): """Sets the defau...
class IOLoop(Configurable): from tornado.process import cpu_count self._executor = ThreadPoolExecutor(max_workers=(cpu_count() * 5)) executor = self._executor c_future = executor.submit(func, *args) # Concurrent Futures are not usable with await. Wrap this in ...
class TestIOLoopFutures(AsyncTestCase): event1 = threading.Event() event2 = threading.Event() def callback(self_event, other_event): self_event.set() time.sleep(0.01) self.assertTrue(other_event.is_set()) return self_event res = yield [ ...
class TestIOLoopFutures(AsyncTestCase): event1 = threading.Event() event2 = threading.Event() def sync_func(self_event, other_event): self_event.set() other_event.wait() # Note that return value doesn't actually do anything, # it is just passed th...
class RegexPattern(CheckURLMixin): self.converters = {} def match(self, path): match = self.regex.search(path) if match: # If there are any named groups, use those as kwargs, ignoring # non-named groups. Otherwise, pass all non-named arguments as
class RegexPattern(CheckURLMixin): self.converters = {} def match(self, path): match = ( self.regex.fullmatch(path) if self._is_endpoint and self.regex.pattern.endswith('$') else self.regex.search(path) ) if match: # If there are any n...
def _route_to_regex(route, is_endpoint=False): converters[parameter] = converter parts.append('(?P<' + parameter + '>' + converter.regex + ')') if is_endpoint: parts.append('$') return ''.join(parts), converters
def _route_to_regex(route, is_endpoint=False): converters[parameter] = converter parts.append('(?P<' + parameter + '>' + converter.regex + ')') if is_endpoint: parts.append(r'\Z') return ''.join(parts), converters
class SimplifiedURLTests(SimpleTestCase): match = p.resolve('space%s/1/' % string.whitespace) self.assertEqual(match.kwargs, {'num': 1}) @override_settings(ROOT_URLCONF='urlpatterns.converter_urls') class ConverterTests(SimpleTestCase):
class SimplifiedURLTests(SimpleTestCase): match = p.resolve('space%s/1/' % string.whitespace) self.assertEqual(match.kwargs, {'num': 1}) def test_path_trailing_newlines(self): tests = [ '/articles/2003/\n', '/articles/2010/\n', '/en/foo/\n', '...
def tenumerate(iterable, start=0, total=None, tqdm_class=tqdm_auto, if isinstance(iterable, np.ndarray): return tqdm_class(np.ndenumerate(iterable), total=total or len(iterable), **tqdm_kwargs) return enumerate(tqdm_class(iterable, start, **tqdm_kwargs)) def _tzip...
def tenumerate(iterable, start=0, total=None, tqdm_class=tqdm_auto, if isinstance(iterable, np.ndarray): return tqdm_class(np.ndenumerate(iterable), total=total or len(iterable), **tqdm_kwargs) return enumerate(tqdm_class(iterable, **tqdm_kwargs), start) def _tzip...
def test_enumerate(): with closing(StringIO()) as our_file: a = range(9) assert list(tenumerate(a, file=our_file)) == list(enumerate(a)) @with_setup(pretest, posttest)
def test_enumerate(): with closing(StringIO()) as our_file: a = range(9) assert list(tenumerate(a, file=our_file)) == list(enumerate(a)) assert list(tenumerate(a, 42, file=our_file)) == list(enumerate(a, 42)) @with_setup(pretest, posttest)
class Progbar(object): info = ' - %.0fs' % (now - self.start) if self.verbose == 1: if (not force and (now - self.last_update) < self.interval and current < self.target): return prev_total_width = self.total_width
class Progbar(object): info = ' - %.0fs' % (now - self.start) if self.verbose == 1: if (not force and (now - self.last_update) < self.interval and (self.target is not None and current < self.target)): return prev_total_width = self.total_width
from keras import regularizers def test_progbar(): n = 2 input_arr = np.random.random((n, n, n)) bar = Progbar(n) for i, arr in enumerate(input_arr): bar.update(i, list(arr))
from keras import regularizers def test_progbar(): n = 2 input_arr = np.random.random((n, n, n)) bar = Progbar(n) for i, arr in enumerate(input_arr): bar.update(i, list(arr)) bar = Progbar(None) for i, arr in enumerate(input_arr): bar.update(i, list(arr))
import socks except (ImportError, AttributeError): socks = None # Build the appropriate socket wrapper for ssl ssl = None
import socks except (ImportError, AttributeError): socks = None from httplib2 import auth from httplib2.error import * # Build the appropriate socket wrapper for ssl ssl = None
ssl_CertificateError = getattr(ssl, "CertificateError", None) def _ssl_wrap_socket( sock, key_file, cert_file, disable_validation, ca_certs, ssl_version, hostname, key_password ): if disable_validation: cert_reqs = ssl.CERT_NONE else:
ssl_CertificateError = getattr(ssl, "CertificateError", None) def _ssl_wrap_socket(sock, key_file, cert_file, disable_validation, ca_certs, ssl_version, hostname, key_password): if disable_validation: cert_reqs = ssl.CERT_NONE else:
def _ssl_wrap_socket( if key_password: raise NotSupportedOnThisPlatform("Certificate with password is not supported.") return ssl.wrap_socket( sock, keyfile=key_file, certfile=cert_file, cert_reqs=cert_reqs, ca_certs=ca_certs, ...
def _ssl_wrap_socket( if key_password: raise NotSupportedOnThisPlatform("Certificate with password is not supported.") return ssl.wrap_socket( sock, keyfile=key_file, certfile=cert_file, cert_reqs=cert_reqs, ca_certs=ca_certs, ssl_version=ssl_version, )
class NotRunningAppEngineEnvironment(HttpLib2Error): DEFAULT_MAX_REDIRECTS = 5 from httplib2 import certs CA_CERTS = certs.where() # Which headers are hop-by-hop headers by default
class NotRunningAppEngineEnvironment(HttpLib2Error): DEFAULT_MAX_REDIRECTS = 5 from httplib2 import certs CA_CERTS = certs.where() # Which headers are hop-by-hop headers by default
def safename(filename): def _normalize_headers(headers): return dict( [ (key.lower(), NORMALIZE_SPACE.sub(value, " ").strip()) for (key, value) in headers.iteritems() ] ) def _parse_cache_control(headers):
def safename(filename): def _normalize_headers(headers): return dict([(key.lower(), NORMALIZE_SPACE.sub(value, " ").strip()) for (key, value) in headers.iteritems()]) def _parse_cache_control(headers):
def _parse_cache_control(headers): if "cache-control" in headers: parts = headers["cache-control"].split(",") parts_with_args = [ tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=") ] parts_wo_args = [ ...
def _parse_cache_control(headers): if "cache-control" in headers: parts = headers["cache-control"].split(",") parts_with_args = [ tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=") ] parts_wo_args = [(name.strip().lower(), 1) ...
def _parse_cache_control(headers): # Set to true to turn on, usefull for testing servers. USE_WWW_AUTH_STRICT_PARSING = 0 # In regex below: # [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP # "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-st...
def _parse_cache_control(headers): # Set to true to turn on, usefull for testing servers. USE_WWW_AUTH_STRICT_PARSING = 0 # TODO: add current time as _entry_disposition argument to avoid sleep in tests def _entry_disposition(response_headers, request_headers):
def _entry_disposition(response_headers, request_headers): cc = _parse_cache_control(request_headers) cc_response = _parse_cache_control(response_headers) if ( "pragma" in request_headers and request_headers["pragma"].lower().find("no-cache") != -1 ): retval = "TRANSPARENT" ...
def _entry_disposition(response_headers, request_headers): cc = _parse_cache_control(request_headers) cc_response = _parse_cache_control(response_headers) if "pragma" in request_headers and request_headers["pragma"].lower().find("no-cache") != -1: retval = "TRANSPARENT" if "cache-control" n...
def _decompressContent(response, new_content): except (IOError, zlib.error): content = "" raise FailedToDecompressContent( _("Content purported to be compressed with %s but failed to decompress.") % response.get("content-encoding"), response, content, ...
def _decompressContent(response, new_content): except (IOError, zlib.error): content = "" raise FailedToDecompressContent( _("Content purported to be compressed with %s but failed to decompress.") % response.get("content-encoding"), response, content, )
def _updateCache(request_headers, response_headers, content, cache, cachekey): def _cnonce(): dig = _md5( "%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)]) ).hexdigest() return dig[:16] def _wsse_username_token(cnonce, iso_now, password): return base...
def _updateCache(request_headers, response_headers, content, cache, cachekey): def _cnonce(): dig = _md5("%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])).hexdigest() return dig[:16] def _wsse_username_token(cnonce, iso_now, password): return base64.b64encode(_sha("%s%...
def _wsse_username_token(cnonce, iso_now, password): class Authentication(object): def __init__( self, credentials, host, request_uri, headers, response, content, http ): (scheme, authority, path, query, fragment) = parse_uri(request_uri) self.path = path self.host = host
def _wsse_username_token(cnonce, iso_now, password): class Authentication(object): def __init__(self, credentials, host, request_uri, headers, response, content, http): (scheme, authority, path, query, fragment) = parse_uri(request_uri) self.path = path self.host = host
def response(self, response, content): class BasicAuthentication(Authentication): def __init__( self, credentials, host, request_uri, headers, response, content, http ): Authentication.__init__( self, credentials, host, request_uri, headers, response, content, http ) d...
def response(self, response, content): class BasicAuthentication(Authentication): def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) def request(self, method, request_uri...
def request(self, method, request_uri, headers, content, cnonce=None): def response(self, response, content): if "authentication-info" not in response: challenge = _parse_www_authenticate(response, "www-authenticate").get( "digest", {} ) if "true" == chal...
def request(self, method, request_uri, headers, content, cnonce=None): def response(self, response, content): if "authentication-info" not in response: challenge = auth._parse_www_authenticate(response, "www-authenticate").get("digest", {}) if "true" == challenge.get("stale"): ...
class HmacDigestAuthentication(Authentication): __author__ = "Thomas Broyer (t.broyer@ltgt.net)" def __init__( self, credentials, host, request_uri, headers, response, content, http ): Authentication.__init__( self, credentials, host, request_uri, headers, response, content, ht...
class HmacDigestAuthentication(Authentication): __author__ = "Thomas Broyer (t.broyer@ltgt.net)" def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) challenge = aut...
def __init__( self.challenge["pw-algorithm"] = self.challenge.get("pw-algorithm", "SHA-1") if self.challenge["pw-algorithm"] not in ["SHA-1", "MD5"]: raise UnimplementedHmacDigestAuthOptionError( _( "Unsupported value for pw-algorithm: %s." ...
def __init__( self.challenge["pw-algorithm"] = self.challenge.get("pw-algorithm", "SHA-1") if self.challenge["pw-algorithm"] not in ["SHA-1", "MD5"]: raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for pw-algorithm: %s." % self.challenge["pw-algorithm"]) ...
def __init__( [ self.credentials[0], ":", self.pwhashmod.new( "".join([self.credentials[1], self.challenge["salt"]]) ) .hexdigest() .lower(), ":", self.challeng...
def __init__( [ self.credentials[0], ":", self.pwhashmod.new("".join([self.credentials[1], self.challenge["salt"]])).hexdigest().lower(), ":", self.challenge["realm"], ]
def request(self, method, request_uri, headers, content): headers_val = "".join([headers[k] for k in keys]) created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % ( method, request_uri, cnonc...
def request(self, method, request_uri, headers, content): headers_val = "".join([headers[k] for k in keys]) created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge["snonce"], headers_...
def request(self, method, request_uri, headers, content): ) def response(self, response, content): challenge = _parse_www_authenticate(response, "www-authenticate").get( "hmacdigest", {} ) if challenge.get("reason") in ["integrity", "stale"]: return True ...
def request(self, method, request_uri, headers, content): ) def response(self, response, content): challenge = auth._parse_www_authenticate(response, "www-authenticate").get("hmacdigest", {}) if challenge.get("reason") in ["integrity", "stale"]: return True return False
class WsseAuthentication(Authentication): challenge but instead requiring your client to telepathically know that their endpoint is expecting WSSE profile="UsernameToken".""" def __init__( self, credentials, host, request_uri, headers, response, content, http ): Authentication.__init__(...
class WsseAuthentication(Authentication): challenge but instead requiring your client to telepathically know that their endpoint is expecting WSSE profile="UsernameToken".""" def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credenti...
def request(self, method, request_uri, headers, content): iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1]) headers["X-WSSE"] = ( 'UsernameToken Username="%s", PasswordD...
def request(self, method, request_uri, headers, content): iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1]) headers["X-WSSE"] = ('UsernameToken Username="%s", PasswordDigest="%s", '...
def __init__( # elif request_uri.find("spreadsheets") > 0: # service = "wise" auth = dict( Email=credentials[0], Passwd=credentials[1], service=service, source=headers["user-agent"], ) resp, content = self.http.request( ...
def __init__( # elif request_uri.find("spreadsheets") > 0: # service = "wise" auth = dict(Email=credentials[0], Passwd=credentials[1], service=service, source=headers["user-agent"],) resp, content = self.http.request( "https://www.google.com/accounts/ClientLogin", ...
class FileCache(object): be running on the same cache. """ def __init__( self, cache, safe=safename ): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior self.cache = cache self.safe = safe if not os.path.exists(cache):
class FileCache(object): be running on the same cache. """ def __init__(self, cache, safe=safename): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior self.cache = cache self.safe = safe if not os.path.exists(cache):
def iter(self, domain): class KeyCerts(Credentials): """Identical to Credentials except that name/password are mapped to key/cert.""" def add(self, key, cert, domain, password): self.credentials.append((domain.lower(), key, cert, password))
def iter(self, domain): class KeyCerts(Credentials): """Identical to Credentials except that name/password are mapped to key/cert.""" def add(self, key, cert, domain, password): self.credentials.append((domain.lower(), key, cert, password))
class ProxyInfo(object): bypass_hosts = () def __init__( self, proxy_type, proxy_host, proxy_port, proxy_rdns=True, proxy_user=None, proxy_pass=None, proxy_headers=None, ): """Args:
class ProxyInfo(object): bypass_hosts = () def __init__( self, proxy_type, proxy_host, proxy_port, proxy_rdns=True, proxy_user=None, proxy_pass=None, proxy_headers=None, ): """Args:
def connect(self): """Connect to the host and port specified in __init__.""" # Mostly verbatim from httplib.py. if self.proxy_info and socks is None: raise ProxiesUnavailableError( "Proxy support missing but proxy use was requested!" ) if self.prox...
def connect(self): """Connect to the host and port specified in __init__.""" # Mostly verbatim from httplib.py. if self.proxy_info and socks is None: raise ProxiesUnavailableError("Proxy support missing but proxy use was requested!") if self.proxy_info and self.proxy_info.isg...
def connect(self): if use_proxy: self.sock = socks.socksocket(af, socktype, proto) self.sock.setproxy( proxy_type, proxy_host, proxy_port, proxy_rdns, ...
def connect(self): if use_proxy: self.sock = socks.socksocket(af, socktype, proto) self.sock.setproxy( proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers, ) else: ...
def connect(self): if use_proxy: print( "proxy: %s ************" % str( ( proxy_host, proxy_port, ...
def connect(self): if use_proxy: print( "proxy: %s ************" % str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,)) ) if use_proxy: ...
def connect(self): if use_proxy: print( "proxy: %s" % str( ( proxy_host, proxy_port, ...
def connect(self): if use_proxy: print( "proxy: %s" % str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,)) ) if self.sock: self.soc...
def connect(self): if self.proxy_info and self.proxy_info.isgood(): use_proxy = True proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = ( self.proxy_info.astuple() ) host = proxy_host port = proxy_...
def connect(self): if self.proxy_info and self.proxy_info.isgood(): use_proxy = True ( proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers, ...
def connect(self): sock = socks.socksocket(family, socktype, proto) sock.setproxy( proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, ...
def connect(self): sock = socks.socksocket(family, socktype, proto) sock.setproxy( proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers, ) else: sock = socket.socket(...
def connect(self): if use_proxy: print( "proxy: %s" % str( ( proxy_host, proxy_port, ...
def connect(self): if use_proxy: print( "proxy: %s" % str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,)) ) if not self.disable_ssl_certificate_valida...
def connect(self): if use_proxy: print( "proxy: %s" % str( ( proxy_host, proxy_port, ...
def connect(self): if use_proxy: print( "proxy: %s" % str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,)) ) if self.sock: self.soc...
def connect(self): def _new_fixed_fetch(validate_certificate): def fixed_fetch( url, payload=None, method="GET", headers={}, allow_truncated=False, follow_redirects=True, deadline=None, ): return fetch( url,
def connect(self): def _new_fixed_fetch(validate_certificate): def fixed_fetch( url, payload=None, method="GET", headers={}, allow_truncated=False, follow_redirects=True, deadline=None, ): return fetch( url,
def __init__( disable_ssl_certificate_validation=False, ssl_version=None, ): httplib.HTTPConnection.__init__( self, host, port=port, strict=strict, timeout=timeout ) class AppEngineHttpsConnection(httplib.HTTPSConnection):
def __init__( disable_ssl_certificate_validation=False, ssl_version=None, ): httplib.HTTPConnection.__init__(self, host, port=port, strict=strict, timeout=timeout) class AppEngineHttpsConnection(httplib.HTTPSConnection):
def __init__( if key_password: raise NotSupportedOnThisPlatform("Certificate with password is not supported.") httplib.HTTPSConnection.__init__( self, host, port=port, key_file=key_file, cert_file=cert_file, strict=stric...
def __init__( if key_password: raise NotSupportedOnThisPlatform("Certificate with password is not supported.") httplib.HTTPSConnection.__init__( self, host, port=port, key_file=key_file, cert_file=cert_file, strict=strict, timeout=timeout, ) self._fetch = _new_fix...
def is_gae_instance(): raise NotRunningAppEngineEnvironment() from google.appengine.api import apiproxy_stub_map if apiproxy_stub_map.apiproxy.GetStub("urlfetch") is None: raise ImportError
def is_gae_instance(): raise NotRunningAppEngineEnvironment() from google.appengine.api import apiproxy_stub_map if apiproxy_stub_map.apiproxy.GetStub("urlfetch") is None: raise ImportError
def _auth_from_challenge(self, host, request_uri, headers, response, content): """A generator that creates Authorization objects that can be applied to requests. """ challenges = _parse_www_authenticate(response, "www-authenticate") for cred in self.credentials.iter(host): ...
def _auth_from_challenge(self, host, request_uri, headers, response, content): """A generator that creates Authorization objects that can be applied to requests. """ challenges = auth._parse_www_authenticate(response, "www-authenticate") for cred in self.credentials.iter(host)...
def _conn_request(self, conn, request_uri, method, body, headers): return (response, content) def _request( self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey, ): """Do the ac...
def _conn_request(self, conn, request_uri, method, body, headers): return (response, content) def _request( self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey, ): """Do the actual request using the connection object and also follow one lev...
def _request( del headers["if-none-match"] if "if-modified-since" in headers: del headers["if-modified-since"] if ( "authorization" in headers and not self.forward_authorization_header...
def _request( del headers["if-none-match"] if "if-modified-since" in headers: del headers["if-modified-since"] if "authorization" in headers and not self.forward_authorization_headers: del headers["authorizat...
def _request( redirect_method = "GET" body = None (response, content) = self.request( location, method=redirect_method, body=body, ...
def _request( redirect_method = "GET" body = None (response, content) = self.request( location, method=redirect_method, body=body, headers=headers, redirections=redirections - 1, ) ...
def _normalize_headers(self, headers): # including all socket.* and httplib.* exceptions. def request( self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None, ): """ Performs a single HTTP re...
def _normalize_headers(self, headers): # including all socket.* and httplib.* exceptions. def request( self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None, ): """ Performs a single HTTP request.
def request( being and instance of the 'Response' class, the second being a string that contains the response entity body. """ conn_key = '' try: if headers is None:
def request( being and instance of the 'Response' class, the second being a string that contains the response entity body. """ conn_key = "" try: if headers is None:
def request( # Should cached permanent redirects be counted in our redirection count? For now, yes. if redirections <= 0: raise RedirectLimit( "Redirected more times than rediection_limit allows.", {}...
def request( # Should cached permanent redirects be counted in our redirection count? For now, yes. if redirections <= 0: raise RedirectLimit( "Redirected more times than rediection_limit allows.", {}, "", ...
def request( return (response, content) if entry_disposition == "STALE": if ( "etag" in info and not self.ignore_etag and not "if-none-match" in headers ...
def request( return (response, content) if entry_disposition == "STALE": if "etag" in info and not self.ignore_etag and not "if-none-match" in headers: headers["if-none-match"] = info["etag"] if "las...
def request( pass (response, new_content) = self._request( conn, authority, uri, request_uri, method, body, ...
def request( pass (response, new_content) = self._request( conn, authority, uri, request_uri, method, body, headers, redirections, cachekey, ) if response.status == 304 and method == "GET":
def request( merged_response = Response(info) if hasattr(response, "_stale_digest"): merged_response._stale_digest = response._stale_digest _updateCache( headers, merged_response, content, self.cache, cachekey ...
def request( merged_response = Response(info) if hasattr(response, "_stale_digest"): merged_response._stale_digest = response._stale_digest _updateCache(headers, merged_response, content, self.cache, cachekey) respon...
def request( content = "" else: (response, content) = self._request( conn, authority, uri, request_uri, method, body, ...
def request( content = "" else: (response, content) = self._request( conn, authority, uri, request_uri, method, body, headers, redirections, cachekey, ) except Exception as e: is_timeout = isinstance(...
def request( response.reason = str(e) elif is_timeout: content = "Request Timeout" response = Response( { "content-type": "text/plain", "status": "408", ...
def request( response.reason = str(e) elif is_timeout: content = "Request Timeout" response = Response({"content-type": "text/plain", "status": "408", "content-length": len(content),}) response.reason = "Request Timeout" ...
# TODO: remove this fallback and copypasted socksipy module upon py2/3 merge, # idea is to have soft-dependency on any compatible module called socks from . import socks from .iri2uri import iri2uri
# TODO: remove this fallback and copypasted socksipy module upon py2/3 merge, # idea is to have soft-dependency on any compatible module called socks from . import socks from . import auth from .error import * from .iri2uri import iri2uri
def has_timeout(timeout): RETRIES = 2 # All exceptions raised here derive from HttpLib2Error class HttpLib2Error(Exception): pass # Some exceptions can be caught and optionally # be turned back into responses. class HttpLib2ErrorWithResponse(HttpLib2Error): def __init__(self, desc, response, content): ...
def has_timeout(timeout): RETRIES = 2 # Open Items: # -----------
class ProxiesUnavailableError(HttpLib2Error): from httplib2 import certs CA_CERTS = certs.where() # PROTOCOL_TLS is python 3.5.3+. PROTOCOL_SSLv23 is deprecated.
class ProxiesUnavailableError(HttpLib2Error): from httplib2 import certs CA_CERTS = certs.where() # PROTOCOL_TLS is python 3.5.3+. PROTOCOL_SSLv23 is deprecated.
class ProxiesUnavailableError(HttpLib2Error): # > Selects the highest protocol version that both the client and server support. # > Despite the name, this option can select “TLS” protocols as well as “SSL”. # source: https://docs.python.org/3.5/library/ssl.html#ssl.PROTOCOL_TLS DEFAULT_TLS_VERSION = getattr(ssl, "PROTO...
class ProxiesUnavailableError(HttpLib2Error): # > Selects the highest protocol version that both the client and server support. # > Despite the name, this option can select “TLS” protocols as well as “SSL”. # source: https://docs.python.org/3.5/library/ssl.html#ssl.PROTOCOL_TLS DEFAULT_TLS_VERSION = getattr(ssl, "PROTO...
def safename(filename): def _normalize_headers(headers): return dict( [ ( _convert_byte_str(key).lower(), NORMALIZE_SPACE.sub(_convert_byte_str(value), " ").strip(), ) for (key, value) in headers.items() ] )
def safename(filename): def _normalize_headers(headers): return dict( [ (_convert_byte_str(key).lower(), NORMALIZE_SPACE.sub(_convert_byte_str(value), " ").strip(),) for (key, value) in headers.items() ] )
def _parse_cache_control(headers): if "cache-control" in headers: parts = headers["cache-control"].split(",") parts_with_args = [ tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=") ] parts_wo_args = [ ...
def _parse_cache_control(headers): if "cache-control" in headers: parts = headers["cache-control"].split(",") parts_with_args = [ tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=") ] parts_wo_args = [(name.strip().lower(), 1) ...
def _parse_cache_control(headers): # Set to true to turn on, useful for testing servers. USE_WWW_AUTH_STRICT_PARSING = 0 # In regex below: # [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP # "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-str...
def _parse_cache_control(headers): # Set to true to turn on, useful for testing servers. USE_WWW_AUTH_STRICT_PARSING = 0 def _entry_disposition(response_headers, request_headers): """Determine freshness from the Date, Expires and Cache-Control headers.
def _entry_disposition(response_headers, request_headers): cc = _parse_cache_control(request_headers) cc_response = _parse_cache_control(response_headers) if ( "pragma" in request_headers and request_headers["pragma"].lower().find("no-cache") != -1 ): retval = "TRANSPARENT" ...
def _entry_disposition(response_headers, request_headers): cc = _parse_cache_control(request_headers) cc_response = _parse_cache_control(response_headers) if "pragma" in request_headers and request_headers["pragma"].lower().find("no-cache") != -1: retval = "TRANSPARENT" if "cache-control" n...
def _decompressContent(response, new_content): except (IOError, zlib.error): content = "" raise FailedToDecompressContent( _("Content purported to be compressed with %s but failed to decompress.") % response.get("content-encoding"), response, content, ...
def _decompressContent(response, new_content): except (IOError, zlib.error): content = "" raise FailedToDecompressContent( _("Content purported to be compressed with %s but failed to decompress.") % response.get("content-encoding"), response, content, )
def _write_headers(self): print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp) else: # email.Header got lots of smarts, so use it. headers = header.Header( v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h ...
def _write_headers(self): print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp) else: # email.Header got lots of smarts, so use it. headers = header.Header(v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h) print(headers....
def _updateCache(request_headers, response_headers, content, cache, cachekey): header_str = info.as_string() header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str) text = b"".join( [status_header.encode("utf-8"), header_str.encode("utf-8"), content] ...
def _updateCache(request_headers, response_headers, content, cache, cachekey): header_str = info.as_string() header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str) text = b"".join([status_header.encode("utf-8"), header_str.encode("utf-8"), content]) cache.set...
def _wsse_username_token(cnonce, iso_now, password): class Authentication(object): def __init__( self, credentials, host, request_uri, headers, response, content, http ): (scheme, authority, path, query, fragment) = parse_uri(request_uri) self.path = path self.host = host
def _wsse_username_token(cnonce, iso_now, password): class Authentication(object): def __init__(self, credentials, host, request_uri, headers, response, content, http): (scheme, authority, path, query, fragment) = parse_uri(request_uri) self.path = path self.host = host
def __bool__(self): class BasicAuthentication(Authentication): def __init__( self, credentials, host, request_uri, headers, response, content, http ): Authentication.__init__( self, credentials, host, request_uri, headers, response, content, http ) def request(self, me...
def __bool__(self): class BasicAuthentication(Authentication): def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) def request(self, method, request_uri, headers, content)...
class DigestAuthentication(Authentication): """Only do qop='auth' and MD5, since that is all Apache currently implements""" def __init__( self, credentials, host, request_uri, headers, response, content, http ): Authentication.__init__( self, credentials, host, request_uri, ...
class DigestAuthentication(Authentication): """Only do qop='auth' and MD5, since that is all Apache currently implements""" def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content,...
def request(self, method, request_uri, headers, content, cnonce=None): def response(self, response, content): if "authentication-info" not in response: challenge = _parse_www_authenticate(response, "www-authenticate").get( "digest", {} ) if "true" == chal...
def request(self, method, request_uri, headers, content, cnonce=None): def response(self, response, content): if "authentication-info" not in response: challenge = auth._parse_www_authenticate(response, "www-authenticate").get("digest", {}) if "true" == challenge.get("stale"): ...
class HmacDigestAuthentication(Authentication): __author__ = "Thomas Broyer (t.broyer@ltgt.net)" def __init__( self, credentials, host, request_uri, headers, response, content, http ): Authentication.__init__( self, credentials, host, request_uri, headers, response, content, ht...
class HmacDigestAuthentication(Authentication): __author__ = "Thomas Broyer (t.broyer@ltgt.net)" def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) challenge = aut...
def __init__( self.challenge["pw-algorithm"] = self.challenge.get("pw-algorithm", "SHA-1") if self.challenge["pw-algorithm"] not in ["SHA-1", "MD5"]: raise UnimplementedHmacDigestAuthOptionError( _( "Unsupported value for pw-algorithm: %s." ...
def __init__( self.challenge["pw-algorithm"] = self.challenge.get("pw-algorithm", "SHA-1") if self.challenge["pw-algorithm"] not in ["SHA-1", "MD5"]: raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for pw-algorithm: %s." % self.challenge["pw-algorithm"]) ...
def __init__( [ self.credentials[0], ":", self.pwhashmod.new( "".join([self.credentials[1], self.challenge["salt"]]) ) .hexdigest() .lower(), ":", self.challeng...
def __init__( [ self.credentials[0], ":", self.pwhashmod.new("".join([self.credentials[1], self.challenge["salt"]])).hexdigest().lower(), ":", self.challenge["realm"], ]
def request(self, method, request_uri, headers, content): headers_val = "".join([headers[k] for k in keys]) created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % ( method, request_uri, cnonc...
def request(self, method, request_uri, headers, content): headers_val = "".join([headers[k] for k in keys]) created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge["snonce"], headers_...
def request(self, method, request_uri, headers, content): ) def response(self, response, content): challenge = _parse_www_authenticate(response, "www-authenticate").get( "hmacdigest", {} ) if challenge.get("reason") in ["integrity", "stale"]: return True ...
def request(self, method, request_uri, headers, content): ) def response(self, response, content): challenge = auth._parse_www_authenticate(response, "www-authenticate").get("hmacdigest", {}) if challenge.get("reason") in ["integrity", "stale"]: return True return False
class WsseAuthentication(Authentication): challenge but instead requiring your client to telepathically know that their endpoint is expecting WSSE profile="UsernameToken".""" def __init__( self, credentials, host, request_uri, headers, response, content, http ): Authentication.__init__(...
class WsseAuthentication(Authentication): challenge but instead requiring your client to telepathically know that their endpoint is expecting WSSE profile="UsernameToken".""" def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credenti...
def request(self, method, request_uri, headers, content): iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1]) headers["X-WSSE"] = ( 'UsernameToken Username="%s", PasswordD...
def request(self, method, request_uri, headers, content): iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1]) headers["X-WSSE"] = ('UsernameToken Username="%s", PasswordDigest="%s", '...
def __init__( # elif request_uri.find("spreadsheets") > 0: # service = "wise" auth = dict( Email=credentials[0], Passwd=credentials[1], service=service, source=headers["user-agent"], ) resp, content = self.http.request( ...
def __init__( # elif request_uri.find("spreadsheets") > 0: # service = "wise" auth = dict(Email=credentials[0], Passwd=credentials[1], service=service, source=headers["user-agent"],) resp, content = self.http.request( "https://www.google.com/accounts/ClientLogin", ...