desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Retrieve the server version info from the given connection. This is used by the default implementation to populate the "server_version_info" attribute and is called exactly once upon first connect.'
def _get_server_version_info(self, connection):
raise NotImplementedError()
'Return the string name of the currently selected schema from the given connection. This is used by the default implementation to populate the "default_schema_name" attribute and is called exactly once upon first connect.'
def _get_default_schema_name(self, connection):
raise NotImplementedError()
'Provide an implementation of ``connection.begin()``, given a DB-API connection. The DBAPI has no dedicated "begin" method and it is expected that transactions are implicit. This hook is provided for those DBAPIs that might need additional help in this area. Note that :meth:`.Dialect.do_begin` is not called unless a :...
def do_begin(self, dbapi_connection):
raise NotImplementedError()
'Provide an implementation of ``connection.rollback()``, given a DB-API connection. :param dbapi_connection: a DBAPI connection, typically proxied within a :class:`.ConnectionFairy`.'
def do_rollback(self, dbapi_connection):
raise NotImplementedError()
'Provide an implementation of ``connection.commit()``, given a DB-API connection. :param dbapi_connection: a DBAPI connection, typically proxied within a :class:`.ConnectionFairy`.'
def do_commit(self, dbapi_connection):
raise NotImplementedError()
'Provide an implementation of ``connection.close()``, given a DBAPI connection. This hook is called by the :class:`.Pool` when a connection has been detached from the pool, or is being returned beyond the normal capacity of the pool. .. versionadded:: 0.8'
def do_close(self, dbapi_connection):
raise NotImplementedError()
'Create a two-phase transaction ID. This id will be passed to do_begin_twophase(), do_rollback_twophase(), do_commit_twophase(). Its format is unspecified.'
def create_xid(self):
raise NotImplementedError()
'Create a savepoint with the given name. :param connection: a :class:`.Connection`. :param name: savepoint name.'
def do_savepoint(self, connection, name):
raise NotImplementedError()
'Rollback a connection to the named savepoint. :param connection: a :class:`.Connection`. :param name: savepoint name.'
def do_rollback_to_savepoint(self, connection, name):
raise NotImplementedError()
'Release the named savepoint on a connection. :param connection: a :class:`.Connection`. :param name: savepoint name.'
def do_release_savepoint(self, connection, name):
raise NotImplementedError()
'Begin a two phase transaction on the given connection. :param connection: a :class:`.Connection`. :param xid: xid'
def do_begin_twophase(self, connection, xid):
raise NotImplementedError()
'Prepare a two phase transaction on the given connection. :param connection: a :class:`.Connection`. :param xid: xid'
def do_prepare_twophase(self, connection, xid):
raise NotImplementedError()
'Rollback a two phase transaction on the given connection. :param connection: a :class:`.Connection`. :param xid: xid :param is_prepared: whether or not :meth:`.TwoPhaseTransaction.prepare` was called. :param recover: if the recover flag was passed.'
def do_rollback_twophase(self, connection, xid, is_prepared=True, recover=False):
raise NotImplementedError()
'Commit a two phase transaction on the given connection. :param connection: a :class:`.Connection`. :param xid: xid :param is_prepared: whether or not :meth:`.TwoPhaseTransaction.prepare` was called. :param recover: if the recover flag was passed.'
def do_commit_twophase(self, connection, xid, is_prepared=True, recover=False):
raise NotImplementedError()
'Recover list of uncommited prepared two phase transaction identifiers on the given connection. :param connection: a :class:`.Connection`.'
def do_recover_twophase(self, connection):
raise NotImplementedError()
'Provide an implementation of ``cursor.executemany(statement, parameters)``.'
def do_executemany(self, cursor, statement, parameters, context=None):
raise NotImplementedError()
'Provide an implementation of ``cursor.execute(statement, parameters)``.'
def do_execute(self, cursor, statement, parameters, context=None):
raise NotImplementedError()
'Provide an implementation of ``cursor.execute(statement)``. The parameter collection should not be sent.'
def do_execute_no_params(self, cursor, statement, parameters, context=None):
raise NotImplementedError()
'Return True if the given DB-API error indicates an invalid connection'
def is_disconnect(self, e, connection, cursor):
raise NotImplementedError()
'return a callable which sets up a newly created DBAPI connection. The callable accepts a single argument "conn" which is the DBAPI connection itself. It has no return value. This is used to set dialect-wide per-connection options such as isolation modes, unicode modes, etc. If a callable is returned, it will be assem...
def connect(self):
return None
'Given a DBAPI connection, revert its isolation to the default.'
def reset_isolation_level(self, dbapi_conn):
raise NotImplementedError()
'Given a DBAPI connection, set its isolation level.'
def set_isolation_level(self, dbapi_conn, level):
raise NotImplementedError()
'Given a DBAPI connection, return its isolation level.'
def get_isolation_level(self, dbapi_conn):
raise NotImplementedError()
'Return a new cursor generated from this ExecutionContext\'s connection. Some dialects may wish to change the behavior of connection.cursor(), such as postgresql which may return a PG "server side" cursor.'
def create_cursor(self):
raise NotImplementedError()
'Called before an execution of a compiled statement. If a compiled statement was passed to this ExecutionContext, the `statement` and `parameters` datamembers must be initialized after this statement is complete.'
def pre_exec(self):
raise NotImplementedError()
'Called after the execution of a compiled statement. If a compiled statement was passed to this ExecutionContext, the `last_insert_ids`, `last_inserted_params`, etc. datamembers should be available after this method completes.'
def post_exec(self):
raise NotImplementedError()
'Return a result object corresponding to this ExecutionContext. Returns a ResultProxy.'
def result(self):
raise NotImplementedError()
'Receive a DBAPI exception which occurred upon execute, result fetch, etc.'
def handle_dbapi_exception(self, e):
raise NotImplementedError()
'Parse the given textual statement and return True if it refers to a "committable" statement'
def should_autocommit_text(self, statement):
raise NotImplementedError()
'Return True if the last INSERT or UPDATE row contained inlined or database-side defaults.'
def lastrow_has_defaults(self):
raise NotImplementedError()
'Return the DBAPI ``cursor.rowcount`` value, or in some cases an interpreted value. See :attr:`.ResultProxy.rowcount` for details on this.'
def get_rowcount(self):
raise NotImplementedError()
'Return a :class:`.Connection` object which may be part of an ongoing context. Depending on context, this may be ``self`` if this object is already an instance of :class:`.Connection`, or a newly procured :class:`.Connection` if this object is an instance of :class:`.Engine`.'
def contextual_connect(self):
raise NotImplementedError()
'Emit CREATE statements for the given schema entity.'
@util.deprecated('0.7', 'Use the create() method on the given schema object directly, i.e. :meth:`.Table.create`, :meth:`.Index.create`, :meth:`.MetaData.create_all`') def create(self, entity, **kwargs):
raise NotImplementedError()
'Emit DROP statements for the given schema entity.'
@util.deprecated('0.7', 'Use the drop() method on the given schema object directly, i.e. :meth:`.Table.drop`, :meth:`.Index.drop`, :meth:`.MetaData.drop_all`') def drop(self, entity, **kwargs):
raise NotImplementedError()
'Executes the given construct and returns a :class:`.ResultProxy`.'
def execute(self, object, *multiparams, **params):
raise NotImplementedError()
'Executes and returns the first column of the first row. The underlying cursor is closed after execution.'
def scalar(self, object, *multiparams, **params):
raise NotImplementedError()
'Initialize a new :class:`.Inspector`. :param bind: a :class:`~sqlalchemy.engine.Connectable`, which is typically an instance of :class:`~sqlalchemy.engine.Engine` or :class:`~sqlalchemy.engine.Connection`. For a dialect-specific instance of :class:`.Inspector`, see :meth:`.Inspector.from_engine`'
def __init__(self, bind):
self.bind = bind if hasattr(bind, 'engine'): self.engine = bind.engine else: self.engine = bind if (self.engine is bind): bind.connect().close() self.dialect = self.engine.dialect self.info_cache = {}
'Construct a new dialect-specific Inspector object from the given engine or connection. :param bind: a :class:`~sqlalchemy.engine.Connectable`, which is typically an instance of :class:`~sqlalchemy.engine.Engine` or :class:`~sqlalchemy.engine.Connection`. This method differs from direct a direct constructor call of :cl...
@classmethod def from_engine(cls, bind):
if hasattr(bind.dialect, 'inspector'): return bind.dialect.inspector(bind) return Inspector(bind)
'Return the default schema name presented by the dialect for the current engine\'s database user. E.g. this is typically ``public`` for Postgresql and ``dbo`` for SQL Server.'
@property def default_schema_name(self):
return self.dialect.default_schema_name
'Return all schema names.'
def get_schema_names(self):
if hasattr(self.dialect, 'get_schema_names'): return self.dialect.get_schema_names(self.bind, info_cache=self.info_cache) return []
'Return all table names in referred to within a particular schema. The names are expected to be real tables only, not views. Views are instead returned using the :meth:`.Inspector.get_view_names` method. :param schema: Schema name. If ``schema`` is left at ``None``, the database\'s default schema is used, else the name...
def get_table_names(self, schema=None, order_by=None):
if hasattr(self.dialect, 'get_table_names'): tnames = self.dialect.get_table_names(self.bind, schema, info_cache=self.info_cache) else: tnames = self.engine.table_names(schema) if (order_by == 'foreign_key'): tuples = [] for tname in tnames: for fkey in self.get_f...
'Return a dictionary of options specified when the table of the given name was created. This currently includes some options that apply to MySQL tables. :param table_name: string name of the table. For special quoting, use :class:`.quoted_name`. :param schema: string schema name; if omitted, uses the default schema of...
def get_table_options(self, table_name, schema=None, **kw):
if hasattr(self.dialect, 'get_table_options'): return self.dialect.get_table_options(self.bind, table_name, schema, info_cache=self.info_cache, **kw) return {}
'Return all view names in `schema`. :param schema: Optional, retrieve names from a non-default schema. For special quoting, use :class:`.quoted_name`.'
def get_view_names(self, schema=None):
return self.dialect.get_view_names(self.bind, schema, info_cache=self.info_cache)
'Return definition for `view_name`. :param schema: Optional, retrieve names from a non-default schema. For special quoting, use :class:`.quoted_name`.'
def get_view_definition(self, view_name, schema=None):
return self.dialect.get_view_definition(self.bind, view_name, schema, info_cache=self.info_cache)
'Return information about columns in `table_name`. Given a string `table_name` and an optional string `schema`, return column information as a list of dicts with these keys: name the column\'s name type :class:`~sqlalchemy.types.TypeEngine` nullable boolean default the column\'s default value attrs dict containing opti...
def get_columns(self, table_name, schema=None, **kw):
col_defs = self.dialect.get_columns(self.bind, table_name, schema, info_cache=self.info_cache, **kw) for col_def in col_defs: coltype = col_def['type'] if (not isinstance(coltype, TypeEngine)): col_def['type'] = coltype() return col_defs
'Return information about primary keys in `table_name`. Given a string `table_name`, and an optional string `schema`, return primary key information as a list of column names.'
@deprecated('0.7', 'Call to deprecated method get_primary_keys. Use get_pk_constraint instead.') def get_primary_keys(self, table_name, schema=None, **kw):
return self.dialect.get_pk_constraint(self.bind, table_name, schema, info_cache=self.info_cache, **kw)['constrained_columns']
'Return information about primary key constraint on `table_name`. Given a string `table_name`, and an optional string `schema`, return primary key information as a dictionary with these keys: constrained_columns a list of column names that make up the primary key name optional name of the primary key constraint. :param...
def get_pk_constraint(self, table_name, schema=None, **kw):
return self.dialect.get_pk_constraint(self.bind, table_name, schema, info_cache=self.info_cache, **kw)
'Return information about foreign_keys in `table_name`. Given a string `table_name`, and an optional string `schema`, return foreign key information as a list of dicts with these keys: constrained_columns a list of column names that make up the foreign key referred_schema the name of the referred schema referred_table ...
def get_foreign_keys(self, table_name, schema=None, **kw):
return self.dialect.get_foreign_keys(self.bind, table_name, schema, info_cache=self.info_cache, **kw)
'Return information about indexes in `table_name`. Given a string `table_name` and an optional string `schema`, return index information as a list of dicts with these keys: name the index\'s name column_names list of column names in order unique boolean :param table_name: string name of the table. For special quoting,...
def get_indexes(self, table_name, schema=None, **kw):
return self.dialect.get_indexes(self.bind, table_name, schema, info_cache=self.info_cache, **kw)
'Return information about unique constraints in `table_name`. Given a string `table_name` and an optional string `schema`, return unique constraint information as a list of dicts with these keys: name the unique constraint\'s name column_names list of column names in order :param table_name: string name of the table. ...
def get_unique_constraints(self, table_name, schema=None, **kw):
return self.dialect.get_unique_constraints(self.bind, table_name, schema, info_cache=self.info_cache, **kw)
'Given a Table object, load its internal constructs based on introspection. This is the underlying method used by most dialects to produce table reflection. Direct usage is like:: from sqlalchemy import create_engine, MetaData, Table from sqlalchemy.engine import reflection engine = create_engine(\'...\') meta = MetaD...
def reflecttable(self, table, include_columns, exclude_columns=()):
dialect = self.bind.dialect schema = table.schema table_name = table.name reflection_options = dict(((k, table.dialect_kwargs.get(k)) for k in dialect.reflection_options if (k in table.dialect_kwargs))) tbl_opts = self.get_table_options(table_name, schema, **table.dialect_kwargs) if tbl_opts: ...
'return a callable which sets up a newly created DBAPI connection. This is used to set dialect-wide per-connection options such as isolation modes, unicode modes, etc. If a callable is returned, it will be assembled into a pool listener that receives the direct DBAPI connection, with all wrappers removed. If None is re...
def on_connect(self):
return None
'Provide a database-specific :class:`.TypeEngine` object, given the generic object which comes from the types module. This method looks for a dictionary called ``colspecs`` as a class or instance-level variable, and passes on to :func:`.types.adapt_type`.'
def type_descriptor(self, typeobj):
return sqltypes.adapt_type(typeobj, self.colspecs)
'Compatibility method, adapts the result of get_primary_keys() for those dialects which don\'t implement get_pk_constraint().'
def get_pk_constraint(self, conn, table_name, schema=None, **kw):
return {'constrained_columns': self.get_primary_keys(conn, table_name, schema=schema, **kw)}
'Create a random two-phase transaction ID. This id will be passed to do_begin_twophase(), do_rollback_twophase(), do_commit_twophase(). Its format is unspecified.'
def create_xid(self):
return ('_sa_%032x' % random.randint(0, (2 ** 128)))
'Initialize execution context for a DDLElement construct.'
@classmethod def _init_ddl(cls, dialect, connection, dbapi_connection, compiled_ddl):
self = cls.__new__(cls) self.dialect = dialect self.root_connection = connection self._dbapi_connection = dbapi_connection self.engine = connection.engine self.compiled = compiled = compiled_ddl self.isddl = True self.execution_options = compiled.statement._execution_options if conne...
'Initialize execution context for a Compiled construct.'
@classmethod def _init_compiled(cls, dialect, connection, dbapi_connection, compiled, parameters):
self = cls.__new__(cls) self.dialect = dialect self.root_connection = connection self._dbapi_connection = dbapi_connection self.engine = connection.engine self.compiled = compiled if (not compiled.can_execute): raise exc.ArgumentError('Not an executable clause') self.exe...
'Initialize execution context for a string SQL statement.'
@classmethod def _init_statement(cls, dialect, connection, dbapi_connection, statement, parameters):
self = cls.__new__(cls) self.dialect = dialect self.root_connection = connection self._dbapi_connection = dbapi_connection self.engine = connection.engine self.execution_options = connection._execution_options if (not parameters): if self.dialect.positional: self.paramete...
'Initialize execution context for a ColumnDefault construct.'
@classmethod def _init_default(cls, dialect, connection, dbapi_connection):
self = cls.__new__(cls) self.dialect = dialect self.root_connection = connection self._dbapi_connection = dbapi_connection self.engine = connection.engine self.execution_options = connection._execution_options self.cursor = self.create_cursor() return self
'Execute a string statement on the current cursor, returning a scalar result. Used to fire off sequences, default phrases, and "select lastrowid" types of statements individually or in the context of a parent INSERT or UPDATE statement.'
def _execute_scalar(self, stmt, type_):
conn = self.root_connection if (isinstance(stmt, util.text_type) and (not self.dialect.supports_unicode_statements)): stmt = self.dialect._encoder(stmt)[0] if self.dialect.positional: default_params = self.dialect.execute_sequence_format() else: default_params = {} conn._curs...
'Return a \'result processor\' for a given type as present in cursor.description. This has a default implementation that dialects can override for context-sensitive result type handling.'
def get_result_processor(self, type_, colname, coltype):
return type_._cached_result_processor(self.dialect, coltype)
'return self.cursor.lastrowid, or equivalent, after an INSERT. This may involve calling special cursor functions, issuing a new SELECT on the cursor (or a new one), or returning a stored value that was calculated within post_exec(). This function will only be called for dialects which support "implicit" primary key gen...
def get_lastrowid(self):
return self.cursor.lastrowid
'Given a cursor and ClauseParameters, call the appropriate style of ``setinputsizes()`` on the cursor, using DB-API types from the bind parameter\'s ``TypeEngine`` objects. This method only called by those dialects which require it, currently cx_oracle.'
def set_input_sizes(self, translate=None, exclude_types=None):
if (not hasattr(self.compiled, 'bind_names')): return types = dict(((self.compiled.bind_names[bindparam], bindparam.type) for bindparam in self.compiled.bind_names)) if self.dialect.positional: inputsizes = [] for key in self.compiled.positiontup: typeengine = types[key] ...
'Generate default values for compiled insert/update statements, and generate inserted_primary_key collection.'
def __process_defaults(self):
key_getter = self.compiled._key_getters_for_crud_column[2] if self.executemany: if len(self.compiled.prefetch): scalar_defaults = {} for c in self.prefetch_cols: if (self.isinsert and c.default and c.default.is_scalar): scalar_defaults[c] = c.d...
'Return the SQLAlchemy database dialect class corresponding to this URL\'s driver name.'
def get_dialect(self):
if ('+' not in self.drivername): name = self.drivername else: name = self.drivername.replace('+', '.') cls = registry.load(name) if (hasattr(cls, 'dialect') and isinstance(cls.dialect, type) and issubclass(cls.dialect, Dialect)): return cls.dialect else: return cls
'Translate url attributes into a dictionary of connection arguments. Returns attributes of this url (`host`, `database`, `username`, `password`, `port`) as a plain dictionary. The attribute names are used as the keys by default. Unset or false attributes are omitted from the final dictionary. :param \**kw: Optional, ...
def translate_connect_args(self, names=[], **kw):
translated = {} attribute_names = ['host', 'database', 'username', 'password', 'port'] for sname in attribute_names: if names: name = names.pop(0) elif (sname in kw): name = kw[sname] else: name = sname if ((name is not None) and getattr(se...
'Given arguments, returns a new Engine instance.'
def create(self, *args, **kwargs):
raise NotImplementedError()
'Modify the request headers to add the appropriate Authorization header. Over-ride this in sub-classes.'
def request(self, method, request_uri, headers, content):
pass
'Gives us a chance to update with new nonces or such returned from the last authorized response. Over-rise this in sub-classes if necessary. Return TRUE is the request is to be retried, for example Digest may return stale=true.'
def response(self, response, content):
return False
'Modify the request headers to add the appropriate Authorization header.'
def request(self, method, request_uri, headers, content):
headers['authorization'] = ('Basic ' + base64.b64encode(('%s:%s' % self.credentials)).strip())
'Modify the request headers'
def request(self, method, request_uri, headers, content, cnonce=None):
H = (lambda x: _md5(x).hexdigest()) KD = (lambda s, d: H(('%s:%s' % (s, d)))) A2 = ''.join([method, ':', request_uri]) self.challenge['cnonce'] = (cnonce or _cnonce()) request_digest = ('"%s"' % KD(H(self.A1), ('%s:%s:%s:%s:%s' % (self.challenge['nonce'], ('%08x' % self.challenge['nc']), self.challe...
'Modify the request headers'
def request(self, method, request_uri, headers, content):
keys = _get_end2end_headers(headers) keylist = ''.join([('%s ' % k) for k in keys]) 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.challen...
'Modify the request headers to add the appropriate Authorization header.'
def request(self, method, request_uri, headers, content):
headers['authorization'] = 'WSSE profile="UsernameToken"' 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", N...
'Modify the request headers to add the appropriate Authorization header.'
def request(self, method, request_uri, headers, content):
headers['authorization'] = ('GoogleLogin Auth=' + self.Auth)
'Args: proxy_type: The type of proxy server. This must be set to one of socks.PROXY_TYPE_XXX constants. For example: p = ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host=\'localhost\', proxy_port=8000) proxy_host: The hostname or IP address of the proxy server. proxy_port: The port that the proxy server is runn...
def __init__(self, proxy_type, proxy_host, proxy_port, proxy_rdns=True, proxy_user=None, proxy_pass=None):
self.proxy_type = proxy_type self.proxy_host = proxy_host self.proxy_port = proxy_port self.proxy_rdns = proxy_rdns self.proxy_user = proxy_user self.proxy_pass = proxy_pass
'Has this host been excluded from the proxy config'
def bypass_host(self, hostname):
if (self.bypass_hosts is AllHosts): return True bypass = False for domain in self.bypass_hosts: if hostname.endswith(domain): bypass = True return bypass
'Connect to the host and port specified in __init__.'
def connect(self):
if (self.proxy_info and (socks is None)): raise ProxiesUnavailableError('Proxy support missing but proxy use was requested!') msg = 'getaddrinfo returns an empty list' if (self.proxy_info and self.proxy_info.isgood()): use_proxy = True (proxy_type, pr...
'Returns a list of valid host globs for an SSL certificate. Args: cert: A dictionary representing an SSL certificate. Returns: list: A list of valid host globs.'
def _GetValidHostsForCert(self, cert):
if ('subjectAltName' in cert): return [x[1] for x in cert['subjectAltName'] if (x[0].lower() == 'dns')] else: return [x[0][1] for x in cert['subject'] if (x[0][0].lower() == 'commonname')]
'Validates that a given hostname is valid for an SSL certificate. Args: cert: A dictionary representing an SSL certificate. hostname: The hostname to test. Returns: bool: Whether or not the hostname is valid for this certificate.'
def _ValidateCertificateHostname(self, cert, hostname):
hosts = self._GetValidHostsForCert(cert) for host in hosts: host_re = host.replace('.', '\\.').replace('*', '[^.]*') if re.search(('^%s$' % (host_re,)), hostname, re.I): return True return False
'Connect to a host on a given (SSL) port.'
def connect(self):
msg = 'getaddrinfo returns an empty list' if (self.proxy_info and self.proxy_info.isgood()): use_proxy = True (proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass) = self.proxy_info.astuple() host = proxy_host port = proxy_port else: use...
'If \'cache\' is a string then it is used as a directory name for a disk cache. Otherwise it must be an object that supports the same interface as FileCache. All timeouts are in seconds. If None is passed for timeout then Python\'s default timeout for sockets will be used. See for example the docs of socket.setdefaultt...
def __init__(self, cache=None, timeout=None, proxy_info=proxy_info_from_environment, ca_certs=None, disable_ssl_certificate_validation=False):
self.proxy_info = proxy_info self.ca_certs = ca_certs self.disable_ssl_certificate_validation = disable_ssl_certificate_validation self.connections = {} if (cache and isinstance(cache, basestring)): self.cache = FileCache(cache) else: self.cache = cache self.credentials = Cre...
'A generator that creates Authorization objects that can be applied to requests.'
def _auth_from_challenge(self, host, request_uri, headers, response, content):
challenges = _parse_www_authenticate(response, 'www-authenticate') for cred in self.credentials.iter(host): for scheme in AUTH_SCHEME_ORDER: if challenges.has_key(scheme): (yield AUTH_SCHEME_CLASSES[scheme](cred, host, request_uri, headers, response, content, self))
'Add a name and password that will be used any time a request requires authentication.'
def add_credentials(self, name, password, domain=''):
self.credentials.add(name, password, domain)
'Add a key and cert that will be used any time a request requires authentication.'
def add_certificate(self, key, cert, domain):
self.certificates.add(key, cert, domain)
'Remove all the names and passwords that are used for authentication'
def clear_credentials(self):
self.credentials.clear() self.authorizations = []
'Do the actual request using the connection object and also follow one level of redirects if necessary'
def _request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey):
auths = [(auth.depth(request_uri), auth) for auth in self.authorizations if auth.inscope(host, request_uri)] auth = ((auths and sorted(auths)[0][1]) or None) if auth: auth.request(method, request_uri, headers, body) (response, content) = self._conn_request(conn, request_uri, method, body, header...
'Performs a single HTTP request. The \'uri\' is the URI of the HTTP resource and can begin with either \'http\' or \'https\'. The value of \'uri\' must be an absolute URI. The \'method\' is the HTTP method to perform, such as GET, POST, DELETE, etc. There is no restriction on the methods allowed. The \'body\' is the en...
def request(self, uri, method='GET', body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None):
try: if (headers is None): headers = {} else: headers = self._normalize_headers(headers) if (not headers.has_key('user-agent')): headers['user-agent'] = ('Python-httplib2/%s (gzip)' % __version__) uri = iri2uri(uri) (scheme, authority, r...
'Return a ProxyInfo instance (or None) based on the scheme and authority.'
def _get_proxy_info(self, scheme, authority):
(hostname, port) = urllib.splitport(authority) proxy_info = self.proxy_info if callable(proxy_info): proxy_info = proxy_info(scheme) if (hasattr(proxy_info, 'applies_to') and (not proxy_info.applies_to(hostname))): proxy_info = None return proxy_info
'__recvall(count) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received.'
def __recvall(self, count):
data = self.recv(count) while (len(data) < count): d = self.recv((count - len(data))) if (not d): raise GeneralProxyError((0, 'connection closed unexpectedly')) data = (data + d) return data
'override socket.socket.sendall method to rewrite the header for non-tunneling proxies if needed'
def sendall(self, content, *args):
if (not self.__httptunnel): content = self.__rewriteproxy(content) return super(socksocket, self).sendall(content, *args)
'rewrite HTTP request headers to support non-tunneling proxies (i.e. those which do not support the CONNECT method). This only works for HTTP (not HTTPS) since HTTPS requires tunneling.'
def __rewriteproxy(self, header):
(host, endpt) = (None, None) hdrs = header.split('\r\n') for hdr in hdrs: if hdr.lower().startswith('host:'): host = hdr elif (hdr.lower().startswith('get') or hdr.lower().startswith('post')): endpt = hdr if (host and endpt): hdrs.remove(host) hdrs...
'setproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets the proxy to be used. proxytype - The type of the proxy to be used. Three types are supported: PROXY_TYPE_SOCKS4 (including socks4a), PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP addr - The address of the server (IP or DNS). port - The po...
def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
self.__proxy = (proxytype, addr, port, rdns, username, password)
'__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server.'
def __negotiatesocks5(self, destaddr, destport):
if ((self.__proxy[4] != None) and (self.__proxy[5] != None)): self.sendall(struct.pack('BBBB', 5, 2, 0, 2)) else: self.sendall(struct.pack('BBB', 5, 1, 0)) chosenauth = self.__recvall(2) if (chosenauth[0:1] != chr(5).encode()): self.close() raise GeneralProxyError((1, _ge...
'getsockname() -> address info Returns the bound IP address and port number at the proxy.'
def getproxysockname(self):
return self.__proxysockname
'getproxypeername() -> address info Returns the IP and port number of the proxy.'
def getproxypeername(self):
return _orgsocket.getpeername(self)
'getpeername() -> address info Returns the IP address and port number of the destination machine (note: getproxypeername returns the proxy)'
def getpeername(self):
return self.__proxypeername
'__negotiatesocks4(self,destaddr,destport) Negotiates a connection through a SOCKS4 server.'
def __negotiatesocks4(self, destaddr, destport):
rmtrslv = False try: ipaddr = socket.inet_aton(destaddr) except socket.error: if self.__proxy[3]: ipaddr = struct.pack('BBBB', 0, 0, 0, 1) rmtrslv = True else: ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = (struct.pack('>BBH',...
'__negotiatehttp(self,destaddr,destport) Negotiates a connection through an HTTP server.'
def __negotiatehttp(self, destaddr, destport):
if (not self.__proxy[3]): addr = socket.gethostbyname(destaddr) else: addr = destaddr headers = ['CONNECT ', addr, ':', str(destport), ' HTTP/1.1\r\n'] headers += ['Host: ', destaddr, '\r\n'] if ((self.__proxy[4] != None) and (self.__proxy[5] != None)): headers += [s...
'connect(self, despair) Connects to the specified destination through a proxy. destpar - A tuple of the IP/DNS address and the port number. (identical to socket\'s connect). To select the proxy server use setproxy().'
def connect(self, destpair):
if ((not (type(destpair) in (list, tuple))) or (len(destpair) < 2) or (not isinstance(destpair[0], basestring)) or (type(destpair[1]) != int)): raise GeneralProxyError((5, _generalerrors[5])) if (self.__proxy[0] == PROXY_TYPE_SOCKS5): if (self.__proxy[2] != None): portnum = self.__pr...
'Handle one request at a time until shutdown. Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread.'
def serve_forever(self, poll_interval=0.1):
self.__serving = True self.__is_shut_down.clear() while self.__serving: (r, w, e) = select.select([self.socket], [], [], poll_interval) if r: self._handle_request_noblock() self.__is_shut_down.set()