index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
69,868 |
suds.sudsobject
|
__delattr__
| null |
def __delattr__(self, name):
try:
del self.__dict__[name]
builtin = name.startswith("__") and name.endswith("__")
if not builtin:
self.__keylist__.remove(name)
except Exception:
cls = self.__class__.__name__
raise AttributeError("%s has no attribute '%s'" % (cls, name))
|
(self, name)
|
69,869 |
suds.sudsobject
|
__getitem__
| null |
def __getitem__(self, name):
if isinstance(name, int):
name = self.__keylist__[int(name)]
return getattr(self, name)
|
(self, name)
|
69,870 |
suds.sudsobject
|
__init__
| null |
def __init__(self, value):
Object.__init__(self)
self.value = value
|
(self, value)
|
69,871 |
suds.sudsobject
|
__iter__
| null |
def __iter__(self):
return Iter(self)
|
(self)
|
69,872 |
suds.sudsobject
|
__len__
| null |
def __len__(self):
return len(self.__keylist__)
|
(self)
|
69,874 |
suds.sudsobject
|
__setattr__
| null |
def __setattr__(self, name, value):
builtin = name.startswith("__") and name.endswith("__")
if not builtin and name not in self.__keylist__:
self.__keylist__.append(name)
self.__dict__[name] = value
|
(self, name, value)
|
69,875 |
suds.sudsobject
|
__setitem__
| null |
def __setitem__(self, name, value):
setattr(self, name, value)
|
(self, name, value)
|
69,877 |
suds.sudsobject
|
__unicode__
| null |
def __unicode__(self):
return self.__printer__.tostr(self)
|
(self)
|
69,878 |
suds.sudsobject
|
get
| null |
def get(self):
return self.value
|
(self)
|
69,879 |
suds.sudsobject
|
items
| null |
def items(self):
for item in self:
if item[0] != "value":
yield item
|
(self)
|
69,880 |
suds.sudsobject
|
set
| null |
def set(self, value):
self.value = value
return self
|
(self, value)
|
69,881 |
suds.sudsobject
|
Factory
| null |
class Factory:
cache = {}
@classmethod
def subclass(cls, name, bases, dict={}):
if not isinstance(bases, tuple):
bases = (bases,)
# name is of type unicode in python 2 -> not accepted by type()
name = str(name)
key = ".".join((name, str(bases)))
subclass = cls.cache.get(key)
if subclass is None:
subclass = type(name, bases, dict)
cls.cache[key] = subclass
return subclass
@classmethod
def object(cls, classname=None, dict={}):
if classname is not None:
subclass = cls.subclass(classname, Object)
inst = subclass()
else:
inst = Object()
for a in list(dict.items()):
setattr(inst, a[0], a[1])
return inst
@classmethod
def metadata(cls):
return Metadata()
@classmethod
def property(cls, name, value=None):
subclass = cls.subclass(name, Property)
return subclass(value)
|
()
|
69,882 |
bingads.exceptions
|
SdkException
|
Base Exception for exceptions in SDK.
|
class SdkException(Exception):
""" Base Exception for exceptions in SDK. """
def __init__(self, message):
""" Initialize a new instance of this class with detailed message.
:param message: Detailed exception message.
:type message: str
"""
self._message = message
def __str__(self):
return self.message
@property
def message(self):
""" Detailed exception message.
:rtype: str
"""
return self._message
|
(message)
|
69,883 |
bingads.exceptions
|
__init__
|
Initialize a new instance of this class with detailed message.
:param message: Detailed exception message.
:type message: str
|
def __init__(self, message):
""" Initialize a new instance of this class with detailed message.
:param message: Detailed exception message.
:type message: str
"""
self._message = message
|
(self, message)
|
69,885 |
bingads.service_client
|
ServiceClient
|
Provides an interface for calling the methods of the specified Bing Ads service.
|
class ServiceClient:
""" Provides an interface for calling the methods of the specified Bing Ads service."""
def __init__(self, service, version, authorization_data=None, environment='production', **suds_options):
""" Initializes a new instance of this class.
:param service: The service name.
:type service: str
:param authorization_data: (optional) The authorization data, if not provided, cannot call operations on service
:type authorization_data: AuthorizationData or None
:param environment: (optional) The environment name, can only be 'production' or 'sandbox', the default is 'production'
:type environment: str
:param version: to specify the service version
:param suds_options: The suds options need to pass to suds client
"""
self._input_service = service
self._input_environment = environment
self._authorization_data = authorization_data
self._refresh_oauth_tokens_automatically = True
self._version = ServiceClient._format_version(version)
# Use in-memory cache by default.
if 'cache' not in suds_options:
suds_options['cache'] = DictCache()
# set cachingpolicy to 1 to reuse WSDL cache files, otherwise will only reuse XML files
if 'cachingpolicy' not in suds_options:
suds_options['cachingpolicy'] = 1
self._options = suds_options
self._service = ServiceClient._format_service(service)
self._environment = ServiceClient._format_environment(environment)
self.hp=HeaderPlugin()
suds_options['plugins'] = [self.hp]
self._soap_client = Client(self.service_url, **suds_options)
self._soap_client.factory.builder = BingAdsBuilder(self._soap_client.factory.builder.resolver)
def __getattr__(self, name):
# Set authorization data and options before every service call.
self.set_options(**self._options)
return _ServiceCall(self, name)
def get_response_header(self):
return self.hp.get_response_header()
def set_options(self, **kwargs):
""" Set suds options, these options will be passed to suds.
:param kwargs: suds options.
:rtype: None
"""
self._options = kwargs
kwargs = ServiceClient._ensemble_header(self.authorization_data, **self._options)
self._soap_client.set_options(**kwargs)
@property
def authorization_data(self):
""" Represents a user who intends to access the corresponding customer and account.
:rtype: AuthorizationData
"""
return self._authorization_data
@property
def soap_client(self):
""" The internal suds soap client.
:rtype: Client
"""
return self._soap_client
@property
def factory(self):
""" The internal suds soap client factory.
:rtype: Factory
"""
return self.soap_client.factory
@property
def service_url(self):
""" The wsdl url of service based on the specific service and environment.
:rtype: str
"""
key = (self._service, self._environment)
service_info_dict = ServiceClient._get_service_info_dict(self._version)
if key not in service_info_dict:
return service_info_dict[(self._service, 'sandbox')]
return service_info_dict[(self._service, self._environment)]
@property
def refresh_oauth_tokens_automatically(self):
""" A value indicating whether OAuth access and refresh tokens should be refreshed automatically upon access token expiration.
:rtype: bool
"""
return self._refresh_oauth_tokens_automatically
@refresh_oauth_tokens_automatically.setter
def refresh_oauth_tokens_automatically(self, value):
self._refresh_oauth_tokens_automatically = value
@staticmethod
def _ensemble_header(authorization_data, **kwargs):
""" Ensemble the request header send to API services.
:param authorization_data: the authorization data
:type authorization_data: AuthorizationData
:return: the ensemble request header
:rtype: dict
"""
if 'soapheaders' in kwargs:
raise Exception('cannot pass in kwargs contains soapheaders')
if authorization_data is None:
return kwargs
headers = {
'DeveloperToken': authorization_data.developer_token,
'CustomerId': str(authorization_data.customer_id),
'CustomerAccountId': str(authorization_data.account_id),
}
authorization_data.authentication.enrich_headers(headers)
http_headers = {
'User-Agent': USER_AGENT,
}
kwargs['soapheaders'] = headers
kwargs['headers'] = http_headers
return kwargs
@staticmethod
def _is_expired_token_exception(ex):
if isinstance(ex, WebFault):
if hasattr(ex.fault, 'detail') \
and hasattr(ex.fault.detail, 'AdApiFaultDetail') \
and hasattr(ex.fault.detail.AdApiFaultDetail, 'Errors') \
and hasattr(ex.fault.detail.AdApiFaultDetail.Errors, 'AdApiError'):
ad_api_errors = ex.fault.detail.AdApiFaultDetail.Errors.AdApiError
if type(ad_api_errors) == list:
for ad_api_error in ad_api_errors:
if ad_api_error.Code == '109':
return True
else:
if ad_api_errors.Code == '109':
return True
return False
@staticmethod
def _format_service(service):
""" Regularize the service name.
The regularized service name contains only lower character without spaces.
:param service: the service name
:type service: str
:return: the regularized service name
:rtype: str
"""
service = service.strip().lower()
service = service.replace('_', '')
service = service.replace('-', '')
service = service.replace(' ', '')
if service.endswith('service'):
service = service.replace('service', '') # remove postfix "service" if any
return service
@staticmethod
def _format_version(version):
"""
format the version to a int value.
:param version:
:return: int version
"""
if version == 'v13' or version == 13:
return 13
raise ValueError(str.format('version error: [{0}] is not supported.', version))
@staticmethod
def _get_service_info_dict(version):
"""
Get the service information dict by version
:param version:
:return: the service info dict
"""
return SERVICE_INFO_DICT[version]
@staticmethod
def _format_environment(environment):
""" Regularize the environment name.
the regularized version contains only lower character without spaces.
:param environment: the environment name
:type environment: str
:return: the regularized environment name
:rtype: str
"""
environment = environment.strip().lower()
return environment
|
(service, version, authorization_data=None, environment='production', **suds_options)
|
69,886 |
bingads.service_client
|
__getattr__
| null |
def __getattr__(self, name):
# Set authorization data and options before every service call.
self.set_options(**self._options)
return _ServiceCall(self, name)
|
(self, name)
|
69,887 |
bingads.service_client
|
__init__
|
Initializes a new instance of this class.
:param service: The service name.
:type service: str
:param authorization_data: (optional) The authorization data, if not provided, cannot call operations on service
:type authorization_data: AuthorizationData or None
:param environment: (optional) The environment name, can only be 'production' or 'sandbox', the default is 'production'
:type environment: str
:param version: to specify the service version
:param suds_options: The suds options need to pass to suds client
|
def __init__(self, service, version, authorization_data=None, environment='production', **suds_options):
""" Initializes a new instance of this class.
:param service: The service name.
:type service: str
:param authorization_data: (optional) The authorization data, if not provided, cannot call operations on service
:type authorization_data: AuthorizationData or None
:param environment: (optional) The environment name, can only be 'production' or 'sandbox', the default is 'production'
:type environment: str
:param version: to specify the service version
:param suds_options: The suds options need to pass to suds client
"""
self._input_service = service
self._input_environment = environment
self._authorization_data = authorization_data
self._refresh_oauth_tokens_automatically = True
self._version = ServiceClient._format_version(version)
# Use in-memory cache by default.
if 'cache' not in suds_options:
suds_options['cache'] = DictCache()
# set cachingpolicy to 1 to reuse WSDL cache files, otherwise will only reuse XML files
if 'cachingpolicy' not in suds_options:
suds_options['cachingpolicy'] = 1
self._options = suds_options
self._service = ServiceClient._format_service(service)
self._environment = ServiceClient._format_environment(environment)
self.hp=HeaderPlugin()
suds_options['plugins'] = [self.hp]
self._soap_client = Client(self.service_url, **suds_options)
self._soap_client.factory.builder = BingAdsBuilder(self._soap_client.factory.builder.resolver)
|
(self, service, version, authorization_data=None, environment='production', **suds_options)
|
69,888 |
bingads.service_client
|
_ensemble_header
|
Ensemble the request header send to API services.
:param authorization_data: the authorization data
:type authorization_data: AuthorizationData
:return: the ensemble request header
:rtype: dict
|
@staticmethod
def _ensemble_header(authorization_data, **kwargs):
""" Ensemble the request header send to API services.
:param authorization_data: the authorization data
:type authorization_data: AuthorizationData
:return: the ensemble request header
:rtype: dict
"""
if 'soapheaders' in kwargs:
raise Exception('cannot pass in kwargs contains soapheaders')
if authorization_data is None:
return kwargs
headers = {
'DeveloperToken': authorization_data.developer_token,
'CustomerId': str(authorization_data.customer_id),
'CustomerAccountId': str(authorization_data.account_id),
}
authorization_data.authentication.enrich_headers(headers)
http_headers = {
'User-Agent': USER_AGENT,
}
kwargs['soapheaders'] = headers
kwargs['headers'] = http_headers
return kwargs
|
(authorization_data, **kwargs)
|
69,889 |
bingads.service_client
|
_format_environment
|
Regularize the environment name.
the regularized version contains only lower character without spaces.
:param environment: the environment name
:type environment: str
:return: the regularized environment name
:rtype: str
|
@staticmethod
def _format_environment(environment):
""" Regularize the environment name.
the regularized version contains only lower character without spaces.
:param environment: the environment name
:type environment: str
:return: the regularized environment name
:rtype: str
"""
environment = environment.strip().lower()
return environment
|
(environment)
|
69,890 |
bingads.service_client
|
_format_service
|
Regularize the service name.
The regularized service name contains only lower character without spaces.
:param service: the service name
:type service: str
:return: the regularized service name
:rtype: str
|
@staticmethod
def _format_service(service):
""" Regularize the service name.
The regularized service name contains only lower character without spaces.
:param service: the service name
:type service: str
:return: the regularized service name
:rtype: str
"""
service = service.strip().lower()
service = service.replace('_', '')
service = service.replace('-', '')
service = service.replace(' ', '')
if service.endswith('service'):
service = service.replace('service', '') # remove postfix "service" if any
return service
|
(service)
|
69,891 |
bingads.service_client
|
_format_version
|
format the version to a int value.
:param version:
:return: int version
|
@staticmethod
def _format_version(version):
"""
format the version to a int value.
:param version:
:return: int version
"""
if version == 'v13' or version == 13:
return 13
raise ValueError(str.format('version error: [{0}] is not supported.', version))
|
(version)
|
69,892 |
bingads.service_client
|
_get_service_info_dict
|
Get the service information dict by version
:param version:
:return: the service info dict
|
@staticmethod
def _get_service_info_dict(version):
"""
Get the service information dict by version
:param version:
:return: the service info dict
"""
return SERVICE_INFO_DICT[version]
|
(version)
|
69,893 |
bingads.service_client
|
_is_expired_token_exception
| null |
@staticmethod
def _is_expired_token_exception(ex):
if isinstance(ex, WebFault):
if hasattr(ex.fault, 'detail') \
and hasattr(ex.fault.detail, 'AdApiFaultDetail') \
and hasattr(ex.fault.detail.AdApiFaultDetail, 'Errors') \
and hasattr(ex.fault.detail.AdApiFaultDetail.Errors, 'AdApiError'):
ad_api_errors = ex.fault.detail.AdApiFaultDetail.Errors.AdApiError
if type(ad_api_errors) == list:
for ad_api_error in ad_api_errors:
if ad_api_error.Code == '109':
return True
else:
if ad_api_errors.Code == '109':
return True
return False
|
(ex)
|
69,894 |
bingads.service_client
|
get_response_header
| null |
def get_response_header(self):
return self.hp.get_response_header()
|
(self)
|
69,895 |
bingads.service_client
|
set_options
|
Set suds options, these options will be passed to suds.
:param kwargs: suds options.
:rtype: None
|
def set_options(self, **kwargs):
""" Set suds options, these options will be passed to suds.
:param kwargs: suds options.
:rtype: None
"""
self._options = kwargs
kwargs = ServiceClient._ensemble_header(self.authorization_data, **self._options)
self._soap_client.set_options(**kwargs)
|
(self, **kwargs)
|
69,896 |
suds.sax.text
|
Text
|
An XML text object used to represent text content.
@ivar lang: The (optional) language flag.
@type lang: bool
@ivar escaped: The (optional) XML special character escaped flag.
@type escaped: bool
|
class Text(str):
"""
An XML text object used to represent text content.
@ivar lang: The (optional) language flag.
@type lang: bool
@ivar escaped: The (optional) XML special character escaped flag.
@type escaped: bool
"""
__slots__ = ('lang', 'escaped')
@classmethod
def __valid(cls, *args):
return len(args) and args[0] is not None
def __new__(cls, *args, **kwargs):
if cls.__valid(*args):
lang = kwargs.pop('lang', None)
escaped = kwargs.pop('escaped', False)
result = super(Text, cls).__new__(cls, *args, **kwargs)
result.lang = lang
result.escaped = escaped
else:
result = None
return result
def escape(self):
"""
Encode (escape) special XML characters.
@return: The text with XML special characters escaped.
@rtype: L{Text}
"""
if not self.escaped:
post = sax.encoder.encode(self)
escaped = ( post != self )
return Text(post, lang=self.lang, escaped=escaped)
return self
def unescape(self):
"""
Decode (unescape) special XML characters.
@return: The text with escaped XML special characters decoded.
@rtype: L{Text}
"""
if self.escaped:
post = sax.encoder.decode(self)
return Text(post, lang=self.lang)
return self
def trim(self):
post = self.strip()
return Text(post, lang=self.lang, escaped=self.escaped)
def __add__(self, other):
joined = ''.join((self, other))
result = Text(joined, lang=self.lang, escaped=self.escaped)
if isinstance(other, Text):
result.escaped = self.escaped or other.escaped
return result
def __repr__(self):
s = [self]
if self.lang is not None:
s.append(' [%s]' % self.lang)
if self.escaped:
s.append(' <escaped>')
return ''.join(s)
def __getstate__(self):
state = {}
for k in self.__slots__:
state[k] = getattr(self, k)
return state
def __setstate__(self, state):
for k in self.__slots__:
setattr(self, k, state[k])
|
(*args, **kwargs)
|
69,897 |
suds.sax.text
|
__add__
| null |
def __add__(self, other):
joined = ''.join((self, other))
result = Text(joined, lang=self.lang, escaped=self.escaped)
if isinstance(other, Text):
result.escaped = self.escaped or other.escaped
return result
|
(self, other)
|
69,898 |
suds.sax.text
|
__getstate__
| null |
def __getstate__(self):
state = {}
for k in self.__slots__:
state[k] = getattr(self, k)
return state
|
(self)
|
69,899 |
suds.sax.text
|
__new__
| null |
def __new__(cls, *args, **kwargs):
if cls.__valid(*args):
lang = kwargs.pop('lang', None)
escaped = kwargs.pop('escaped', False)
result = super(Text, cls).__new__(cls, *args, **kwargs)
result.lang = lang
result.escaped = escaped
else:
result = None
return result
|
(cls, *args, **kwargs)
|
69,900 |
suds.sax.text
|
__repr__
| null |
def __repr__(self):
s = [self]
if self.lang is not None:
s.append(' [%s]' % self.lang)
if self.escaped:
s.append(' <escaped>')
return ''.join(s)
|
(self)
|
69,901 |
suds.sax.text
|
__setstate__
| null |
def __setstate__(self, state):
for k in self.__slots__:
setattr(self, k, state[k])
|
(self, state)
|
69,902 |
suds.sax.text
|
escape
|
Encode (escape) special XML characters.
@return: The text with XML special characters escaped.
@rtype: L{Text}
|
def escape(self):
"""
Encode (escape) special XML characters.
@return: The text with XML special characters escaped.
@rtype: L{Text}
"""
if not self.escaped:
post = sax.encoder.encode(self)
escaped = ( post != self )
return Text(post, lang=self.lang, escaped=escaped)
return self
|
(self)
|
69,903 |
suds.sax.text
|
trim
| null |
def trim(self):
post = self.strip()
return Text(post, lang=self.lang, escaped=self.escaped)
|
(self)
|
69,904 |
suds.sax.text
|
unescape
|
Decode (unescape) special XML characters.
@return: The text with escaped XML special characters decoded.
@rtype: L{Text}
|
def unescape(self):
"""
Decode (unescape) special XML characters.
@return: The text with escaped XML special characters decoded.
@rtype: L{Text}
"""
if self.escaped:
post = sax.encoder.decode(self)
return Text(post, lang=self.lang)
return self
|
(self)
|
69,905 |
bingads.exceptions
|
TimeoutException
|
This exception is thrown if timeout occurs
|
class TimeoutException(SdkException):
""" This exception is thrown if timeout occurs """
def __init__(self, description):
""" Initializes a new instance of this class with the specified error messages.
:param description: The description of the file download error.
:type description: str
"""
super(TimeoutException, self).__init__(str(description))
|
(description)
|
69,906 |
bingads.exceptions
|
__init__
|
Initializes a new instance of this class with the specified error messages.
:param description: The description of the file download error.
:type description: str
|
def __init__(self, description):
""" Initializes a new instance of this class with the specified error messages.
:param description: The description of the file download error.
:type description: str
"""
super(TimeoutException, self).__init__(str(description))
|
(self, description)
|
69,908 |
suds
|
WebFault
| null |
class WebFault(Exception):
def __init__(self, fault, document):
if hasattr(fault, "faultstring"):
Exception.__init__(self, "Server raised fault: '%s'" %
(fault.faultstring,))
self.fault = fault
self.document = document
|
(fault, document)
|
69,909 |
suds
|
__init__
| null |
def __init__(self, fault, document):
if hasattr(fault, "faultstring"):
Exception.__init__(self, "Server raised fault: '%s'" %
(fault.faultstring,))
self.fault = fault
self.document = document
|
(self, fault, document)
|
69,913 |
tempfile
|
gettempdir
|
Returns tempfile.tempdir as str.
|
def gettempdir():
"""Returns tempfile.tempdir as str."""
return _os.fsdecode(_gettempdir())
|
()
|
69,914 |
getpass
|
getuser
|
Get the username from the environment or password database.
First try various environment variables, then the password
database. This works on Windows as long as USERNAME is set.
|
def getuser():
"""Get the username from the environment or password database.
First try various environment variables, then the password
database. This works on Windows as long as USERNAME is set.
"""
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
user = os.environ.get(name)
if user:
return user
# If this fails, the exception will "explain" why
import pwd
return pwd.getpwuid(os.getuid())[0]
|
()
|
69,930 |
apiclient.base
|
APIClient
| null |
class APIClient(object):
BASE_URL = 'http://localhost:5000/'
def __init__(self, rate_limit_lock=None, encoding='utf8'):
self.rate_limit_lock = rate_limit_lock
self.encoding = encoding
self.connection_pool = self._make_connection_pool()
def _make_connection_pool(self):
return urllib3.PoolManager( cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where())
def _compose_url(self, path, params=None):
return self.BASE_URL + path + '?' + urlencode(params)
def _handle_response(self, response):
return json.loads(response.data.decode(self.encoding))
def _request(self, method, path, params=None):
url = self._compose_url(path, params)
self.rate_limit_lock and self.rate_limit_lock.acquire()
r = self.connection_pool.urlopen(method.upper(), url)
return self._handle_response(r)
def call(self, path, **params):
return self._request('GET', path, params=params)
|
(rate_limit_lock=None, encoding='utf8')
|
69,931 |
apiclient.base
|
__init__
| null |
def __init__(self, rate_limit_lock=None, encoding='utf8'):
self.rate_limit_lock = rate_limit_lock
self.encoding = encoding
self.connection_pool = self._make_connection_pool()
|
(self, rate_limit_lock=None, encoding='utf8')
|
69,932 |
apiclient.base
|
_compose_url
| null |
def _compose_url(self, path, params=None):
return self.BASE_URL + path + '?' + urlencode(params)
|
(self, path, params=None)
|
69,933 |
apiclient.base
|
_handle_response
| null |
def _handle_response(self, response):
return json.loads(response.data.decode(self.encoding))
|
(self, response)
|
69,934 |
apiclient.base
|
_make_connection_pool
| null |
def _make_connection_pool(self):
return urllib3.PoolManager( cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where())
|
(self)
|
69,935 |
apiclient.base
|
_request
| null |
def _request(self, method, path, params=None):
url = self._compose_url(path, params)
self.rate_limit_lock and self.rate_limit_lock.acquire()
r = self.connection_pool.urlopen(method.upper(), url)
return self._handle_response(r)
|
(self, method, path, params=None)
|
69,936 |
apiclient.base
|
call
| null |
def call(self, path, **params):
return self._request('GET', path, params=params)
|
(self, path, **params)
|
69,937 |
apiclient.base
|
APIClient_SharedSecret
| null |
class APIClient_SharedSecret(APIClient):
API_KEY_PARAM = 'key'
def __init__(self, api_key, *args, **kw):
super(APIClient_SharedSecret, self).__init__(*args, **kw)
self.api_key = api_key
def _compose_url(self, path, params=None):
# TODO: fix this, as per our conversation at Oct. 4, 2011, 05:10 UTC
p = {self.API_KEY_PARAM: self.api_key}
if params:
p.update(params)
return self.BASE_URL + path + '?' + urlencode(p)
|
(api_key, *args, **kw)
|
69,938 |
apiclient.base
|
__init__
| null |
def __init__(self, api_key, *args, **kw):
super(APIClient_SharedSecret, self).__init__(*args, **kw)
self.api_key = api_key
|
(self, api_key, *args, **kw)
|
69,939 |
apiclient.base
|
_compose_url
| null |
def _compose_url(self, path, params=None):
# TODO: fix this, as per our conversation at Oct. 4, 2011, 05:10 UTC
p = {self.API_KEY_PARAM: self.api_key}
if params:
p.update(params)
return self.BASE_URL + path + '?' + urlencode(p)
|
(self, path, params=None)
|
69,944 |
apiclient.ratelimiter
|
RateLimiter
| null |
class RateLimiter(object):
def __init__(self, max_messages=10, every_seconds=1):
self.max_messages = max_messages
self.every_seconds = every_seconds
self.lock = Lock()
self._reset_window()
def _reset_window(self):
self.window_num = 0
self.window_time = time.time()
def acquire(self, block=True, timeout=None):
self.lock.acquire()
now = time.time()
if now - self.window_time > self.every_seconds:
# New rate window
self._reset_window()
if self.window_num >= self.max_messages:
# Rate exceeding
if not block:
self.lock.release()
raise RateExceededError()
wait_time = self.window_time + self.every_seconds - now
if timeout and wait_time > timeout:
self.lock.release()
time.sleep(timeout)
raise RateExceededError()
self.lock.release()
time.sleep(wait_time)
self.lock.acquire()
self._reset_window()
self.window_num += 1
self.lock.release()
|
(max_messages=10, every_seconds=1)
|
69,945 |
apiclient.ratelimiter
|
__init__
| null |
def __init__(self, max_messages=10, every_seconds=1):
self.max_messages = max_messages
self.every_seconds = every_seconds
self.lock = Lock()
self._reset_window()
|
(self, max_messages=10, every_seconds=1)
|
69,946 |
apiclient.ratelimiter
|
_reset_window
| null |
def _reset_window(self):
self.window_num = 0
self.window_time = time.time()
|
(self)
|
69,947 |
apiclient.ratelimiter
|
acquire
| null |
def acquire(self, block=True, timeout=None):
self.lock.acquire()
now = time.time()
if now - self.window_time > self.every_seconds:
# New rate window
self._reset_window()
if self.window_num >= self.max_messages:
# Rate exceeding
if not block:
self.lock.release()
raise RateExceededError()
wait_time = self.window_time + self.every_seconds - now
if timeout and wait_time > timeout:
self.lock.release()
time.sleep(timeout)
raise RateExceededError()
self.lock.release()
time.sleep(wait_time)
self.lock.acquire()
self._reset_window()
self.window_num += 1
self.lock.release()
|
(self, block=True, timeout=None)
|
69,950 |
slacker
|
API
| null |
class API(BaseAPI):
def test(self, error=None, **kwargs):
if error:
kwargs['error'] = error
return self.get('api.test', params=kwargs)
|
(token=None, timeout=10, proxies=None, session=None, rate_limit_retries=0)
|
69,951 |
slacker
|
__init__
| null |
def __init__(self, token=None, timeout=DEFAULT_TIMEOUT, proxies=None,
session=None, rate_limit_retries=DEFAULT_RETRIES):
self.token = token
self.timeout = timeout
self.proxies = proxies
self.session = session
self.rate_limit_retries = rate_limit_retries
|
(self, token=None, timeout=10, proxies=None, session=None, rate_limit_retries=0)
|
69,952 |
slacker
|
_request
| null |
def _request(self, request_method, method, **kwargs):
if self.token:
kwargs.setdefault('params', {})['token'] = self.token
url = get_api_url(method)
# while we have rate limit retries left, fetch the resource and back
# off as Slack's HTTP response suggests
for retry_num in range(self.rate_limit_retries):
response = request_method(
url, timeout=self.timeout, proxies=self.proxies, **kwargs
)
if response.status_code == requests.codes.ok:
break
# handle HTTP 429 as documented at
# https://api.slack.com/docs/rate-limits
if response.status_code == requests.codes.too_many:
time.sleep(int(
response.headers.get('retry-after', DEFAULT_WAIT)
))
continue
response.raise_for_status()
else:
# with no retries left, make one final attempt to fetch the
# resource, but do not handle too_many status differently
response = request_method(
url, timeout=self.timeout, proxies=self.proxies, **kwargs
)
response.raise_for_status()
response = Response(response.text)
if not response.successful:
raise Error(response.error)
return response
|
(self, request_method, method, **kwargs)
|
69,953 |
slacker
|
_session_get
| null |
def _session_get(self, url, params=None, **kwargs):
kwargs.setdefault('allow_redirects', True)
return self.session.request(
method='get', url=url, params=params, **kwargs
)
|
(self, url, params=None, **kwargs)
|
69,954 |
slacker
|
_session_post
| null |
def _session_post(self, url, data=None, **kwargs):
return self.session.request(
method='post', url=url, data=data, **kwargs
)
|
(self, url, data=None, **kwargs)
|
69,955 |
slacker
|
get
| null |
def get(self, api, **kwargs):
return self._request(
self._session_get if self.session else requests.get,
api, **kwargs
)
|
(self, api, **kwargs)
|
69,956 |
slacker
|
post
| null |
def post(self, api, **kwargs):
return self._request(
self._session_post if self.session else requests.post,
api, **kwargs
)
|
(self, api, **kwargs)
|
69,957 |
slacker
|
test
| null |
def test(self, error=None, **kwargs):
if error:
kwargs['error'] = error
return self.get('api.test', params=kwargs)
|
(self, error=None, **kwargs)
|
69,958 |
slacker
|
Apps
| null |
class Apps(BaseAPI):
def __init__(self, *args, **kwargs):
super(Apps, self).__init__(*args, **kwargs)
self._permissions = AppsPermissions(*args, **kwargs)
@property
def permissions(self):
return self._permissions
def uninstall(self, client_id, client_secret):
return self.get(
'apps.uninstall',
params={'client_id': client_id, 'client_secret': client_secret}
)
|
(*args, **kwargs)
|
69,959 |
slacker
|
__init__
| null |
def __init__(self, *args, **kwargs):
super(Apps, self).__init__(*args, **kwargs)
self._permissions = AppsPermissions(*args, **kwargs)
|
(self, *args, **kwargs)
|
69,965 |
slacker
|
uninstall
| null |
def uninstall(self, client_id, client_secret):
return self.get(
'apps.uninstall',
params={'client_id': client_id, 'client_secret': client_secret}
)
|
(self, client_id, client_secret)
|
69,966 |
slacker
|
AppsPermissions
| null |
class AppsPermissions(BaseAPI):
def info(self):
return self.get('apps.permissions.info')
def request(self, scopes, trigger_id):
return self.post('apps.permissions.request',
data={
scopes: ','.join(scopes),
trigger_id: trigger_id,
})
|
(token=None, timeout=10, proxies=None, session=None, rate_limit_retries=0)
|
69,972 |
slacker
|
info
| null |
def info(self):
return self.get('apps.permissions.info')
|
(self)
|
69,974 |
slacker
|
request
| null |
def request(self, scopes, trigger_id):
return self.post('apps.permissions.request',
data={
scopes: ','.join(scopes),
trigger_id: trigger_id,
})
|
(self, scopes, trigger_id)
|
69,975 |
slacker
|
Auth
| null |
class Auth(BaseAPI):
def test(self):
return self.get('auth.test')
def revoke(self, test=True):
return self.post('auth.revoke', data={'test': int(test)})
|
(token=None, timeout=10, proxies=None, session=None, rate_limit_retries=0)
|
69,982 |
slacker
|
revoke
| null |
def revoke(self, test=True):
return self.post('auth.revoke', data={'test': int(test)})
|
(self, test=True)
|
69,983 |
slacker
|
test
| null |
def test(self):
return self.get('auth.test')
|
(self)
|
69,984 |
slacker
|
BaseAPI
| null |
class BaseAPI(object):
def __init__(self, token=None, timeout=DEFAULT_TIMEOUT, proxies=None,
session=None, rate_limit_retries=DEFAULT_RETRIES):
self.token = token
self.timeout = timeout
self.proxies = proxies
self.session = session
self.rate_limit_retries = rate_limit_retries
def _request(self, request_method, method, **kwargs):
if self.token:
kwargs.setdefault('params', {})['token'] = self.token
url = get_api_url(method)
# while we have rate limit retries left, fetch the resource and back
# off as Slack's HTTP response suggests
for retry_num in range(self.rate_limit_retries):
response = request_method(
url, timeout=self.timeout, proxies=self.proxies, **kwargs
)
if response.status_code == requests.codes.ok:
break
# handle HTTP 429 as documented at
# https://api.slack.com/docs/rate-limits
if response.status_code == requests.codes.too_many:
time.sleep(int(
response.headers.get('retry-after', DEFAULT_WAIT)
))
continue
response.raise_for_status()
else:
# with no retries left, make one final attempt to fetch the
# resource, but do not handle too_many status differently
response = request_method(
url, timeout=self.timeout, proxies=self.proxies, **kwargs
)
response.raise_for_status()
response = Response(response.text)
if not response.successful:
raise Error(response.error)
return response
def _session_get(self, url, params=None, **kwargs):
kwargs.setdefault('allow_redirects', True)
return self.session.request(
method='get', url=url, params=params, **kwargs
)
def _session_post(self, url, data=None, **kwargs):
return self.session.request(
method='post', url=url, data=data, **kwargs
)
def get(self, api, **kwargs):
return self._request(
self._session_get if self.session else requests.get,
api, **kwargs
)
def post(self, api, **kwargs):
return self._request(
self._session_post if self.session else requests.post,
api, **kwargs
)
|
(token=None, timeout=10, proxies=None, session=None, rate_limit_retries=0)
|
69,991 |
slacker
|
Bots
| null |
class Bots(BaseAPI):
def info(self, bot=None):
return self.get('bots.info', params={'bot': bot})
|
(token=None, timeout=10, proxies=None, session=None, rate_limit_retries=0)
|
69,997 |
slacker
|
info
| null |
def info(self, bot=None):
return self.get('bots.info', params={'bot': bot})
|
(self, bot=None)
|
69,999 |
slacker
|
Channels
| null |
class Channels(BaseAPI):
def create(self, name):
return self.post('channels.create', data={'name': name})
def info(self, channel):
return self.get('channels.info', params={'channel': channel})
def list(self, exclude_archived=None, exclude_members=None):
return self.get('channels.list',
params={'exclude_archived': exclude_archived,
'exclude_members': exclude_members})
def history(self, channel, latest=None, oldest=None, count=None,
inclusive=False, unreads=False):
return self.get('channels.history',
params={
'channel': channel,
'latest': latest,
'oldest': oldest,
'count': count,
'inclusive': int(inclusive),
'unreads': int(unreads)
})
def mark(self, channel, ts):
return self.post('channels.mark',
data={'channel': channel, 'ts': ts})
def join(self, name):
return self.post('channels.join', data={'name': name})
def leave(self, channel):
return self.post('channels.leave', data={'channel': channel})
def invite(self, channel, user):
return self.post('channels.invite',
data={'channel': channel, 'user': user})
def kick(self, channel, user):
return self.post('channels.kick',
data={'channel': channel, 'user': user})
def rename(self, channel, name):
return self.post('channels.rename',
data={'channel': channel, 'name': name})
def replies(self, channel, thread_ts):
return self.get('channels.replies',
params={'channel': channel, 'thread_ts': thread_ts})
def archive(self, channel):
return self.post('channels.archive', data={'channel': channel})
def unarchive(self, channel):
return self.post('channels.unarchive', data={'channel': channel})
def set_purpose(self, channel, purpose):
return self.post('channels.setPurpose',
data={'channel': channel, 'purpose': purpose})
def set_topic(self, channel, topic):
return self.post('channels.setTopic',
data={'channel': channel, 'topic': topic})
def get_channel_id(self, channel_name):
channels = self.list().body['channels']
return get_item_id_by_name(channels, channel_name)
|
(token=None, timeout=10, proxies=None, session=None, rate_limit_retries=0)
|
70,004 |
slacker
|
archive
| null |
def archive(self, channel):
return self.post('channels.archive', data={'channel': channel})
|
(self, channel)
|
70,005 |
slacker
|
create
| null |
def create(self, name):
return self.post('channels.create', data={'name': name})
|
(self, name)
|
70,007 |
slacker
|
get_channel_id
| null |
def get_channel_id(self, channel_name):
channels = self.list().body['channels']
return get_item_id_by_name(channels, channel_name)
|
(self, channel_name)
|
70,008 |
slacker
|
history
| null |
def history(self, channel, latest=None, oldest=None, count=None,
inclusive=False, unreads=False):
return self.get('channels.history',
params={
'channel': channel,
'latest': latest,
'oldest': oldest,
'count': count,
'inclusive': int(inclusive),
'unreads': int(unreads)
})
|
(self, channel, latest=None, oldest=None, count=None, inclusive=False, unreads=False)
|
70,009 |
slacker
|
info
| null |
def info(self, channel):
return self.get('channels.info', params={'channel': channel})
|
(self, channel)
|
70,010 |
slacker
|
invite
| null |
def invite(self, channel, user):
return self.post('channels.invite',
data={'channel': channel, 'user': user})
|
(self, channel, user)
|
70,011 |
slacker
|
join
| null |
def join(self, name):
return self.post('channels.join', data={'name': name})
|
(self, name)
|
70,012 |
slacker
|
kick
| null |
def kick(self, channel, user):
return self.post('channels.kick',
data={'channel': channel, 'user': user})
|
(self, channel, user)
|
70,013 |
slacker
|
leave
| null |
def leave(self, channel):
return self.post('channels.leave', data={'channel': channel})
|
(self, channel)
|
70,014 |
slacker
|
list
| null |
def list(self, exclude_archived=None, exclude_members=None):
return self.get('channels.list',
params={'exclude_archived': exclude_archived,
'exclude_members': exclude_members})
|
(self, exclude_archived=None, exclude_members=None)
|
70,015 |
slacker
|
mark
| null |
def mark(self, channel, ts):
return self.post('channels.mark',
data={'channel': channel, 'ts': ts})
|
(self, channel, ts)
|
70,017 |
slacker
|
rename
| null |
def rename(self, channel, name):
return self.post('channels.rename',
data={'channel': channel, 'name': name})
|
(self, channel, name)
|
70,018 |
slacker
|
replies
| null |
def replies(self, channel, thread_ts):
return self.get('channels.replies',
params={'channel': channel, 'thread_ts': thread_ts})
|
(self, channel, thread_ts)
|
70,019 |
slacker
|
set_purpose
| null |
def set_purpose(self, channel, purpose):
return self.post('channels.setPurpose',
data={'channel': channel, 'purpose': purpose})
|
(self, channel, purpose)
|
70,020 |
slacker
|
set_topic
| null |
def set_topic(self, channel, topic):
return self.post('channels.setTopic',
data={'channel': channel, 'topic': topic})
|
(self, channel, topic)
|
70,021 |
slacker
|
unarchive
| null |
def unarchive(self, channel):
return self.post('channels.unarchive', data={'channel': channel})
|
(self, channel)
|
70,022 |
slacker
|
Chat
| null |
class Chat(BaseAPI):
def post_message(self, channel, text=None, username=None, as_user=None,
parse=None, link_names=None, attachments=None,
unfurl_links=None, unfurl_media=None, icon_url=None,
icon_emoji=None, thread_ts=None, reply_broadcast=None,
blocks=None, mrkdwn=True):
# Ensure attachments are json encoded
if attachments:
if isinstance(attachments, list):
attachments = json.dumps(attachments)
return self.post('chat.postMessage',
data={
'channel': channel,
'text': text,
'username': username,
'as_user': as_user,
'parse': parse,
'link_names': link_names,
'attachments': attachments,
'unfurl_links': unfurl_links,
'unfurl_media': unfurl_media,
'icon_url': icon_url,
'icon_emoji': icon_emoji,
'thread_ts': thread_ts,
'reply_broadcast': reply_broadcast,
'blocks': blocks,
'mrkdwn': mrkdwn,
})
def me_message(self, channel, text):
return self.post('chat.meMessage',
data={'channel': channel, 'text': text})
def command(self, channel, command, text):
return self.post('chat.command',
data={
'channel': channel,
'command': command,
'text': text
})
def update(self, channel, ts, text, attachments=None, parse=None,
link_names=False, as_user=None, blocks=None):
# Ensure attachments are json encoded
if attachments is not None and isinstance(attachments, list):
attachments = json.dumps(attachments)
return self.post('chat.update',
data={
'channel': channel,
'ts': ts,
'text': text,
'attachments': attachments,
'parse': parse,
'link_names': int(link_names),
'as_user': as_user,
'blocks': blocks
})
def delete(self, channel, ts, as_user=False):
return self.post('chat.delete',
data={
'channel': channel,
'ts': ts,
'as_user': as_user
})
def post_ephemeral(self, channel, text, user, as_user=None,
attachments=None, link_names=None, parse=None,
blocks=None):
# Ensure attachments are json encoded
if attachments is not None and isinstance(attachments, list):
attachments = json.dumps(attachments)
return self.post('chat.postEphemeral',
data={
'channel': channel,
'text': text,
'user': user,
'as_user': as_user,
'attachments': attachments,
'link_names': link_names,
'parse': parse,
'blocks': blocks
})
def unfurl(self, channel, ts, unfurls, user_auth_message=None,
user_auth_required=False, user_auth_url=None):
return self.post('chat.unfurl',
data={
'channel': channel,
'ts': ts,
'unfurls': unfurls,
'user_auth_message': user_auth_message,
'user_auth_required': user_auth_required,
'user_auth_url': user_auth_url,
})
def get_permalink(self, channel, message_ts):
return self.get('chat.getPermalink',
params={
'channel': channel,
'message_ts': message_ts
})
|
(token=None, timeout=10, proxies=None, session=None, rate_limit_retries=0)
|
70,027 |
slacker
|
command
| null |
def command(self, channel, command, text):
return self.post('chat.command',
data={
'channel': channel,
'command': command,
'text': text
})
|
(self, channel, command, text)
|
70,028 |
slacker
|
delete
| null |
def delete(self, channel, ts, as_user=False):
return self.post('chat.delete',
data={
'channel': channel,
'ts': ts,
'as_user': as_user
})
|
(self, channel, ts, as_user=False)
|
70,030 |
slacker
|
get_permalink
| null |
def get_permalink(self, channel, message_ts):
return self.get('chat.getPermalink',
params={
'channel': channel,
'message_ts': message_ts
})
|
(self, channel, message_ts)
|
70,031 |
slacker
|
me_message
| null |
def me_message(self, channel, text):
return self.post('chat.meMessage',
data={'channel': channel, 'text': text})
|
(self, channel, text)
|
70,033 |
slacker
|
post_ephemeral
| null |
def post_ephemeral(self, channel, text, user, as_user=None,
attachments=None, link_names=None, parse=None,
blocks=None):
# Ensure attachments are json encoded
if attachments is not None and isinstance(attachments, list):
attachments = json.dumps(attachments)
return self.post('chat.postEphemeral',
data={
'channel': channel,
'text': text,
'user': user,
'as_user': as_user,
'attachments': attachments,
'link_names': link_names,
'parse': parse,
'blocks': blocks
})
|
(self, channel, text, user, as_user=None, attachments=None, link_names=None, parse=None, blocks=None)
|
70,034 |
slacker
|
post_message
| null |
def post_message(self, channel, text=None, username=None, as_user=None,
parse=None, link_names=None, attachments=None,
unfurl_links=None, unfurl_media=None, icon_url=None,
icon_emoji=None, thread_ts=None, reply_broadcast=None,
blocks=None, mrkdwn=True):
# Ensure attachments are json encoded
if attachments:
if isinstance(attachments, list):
attachments = json.dumps(attachments)
return self.post('chat.postMessage',
data={
'channel': channel,
'text': text,
'username': username,
'as_user': as_user,
'parse': parse,
'link_names': link_names,
'attachments': attachments,
'unfurl_links': unfurl_links,
'unfurl_media': unfurl_media,
'icon_url': icon_url,
'icon_emoji': icon_emoji,
'thread_ts': thread_ts,
'reply_broadcast': reply_broadcast,
'blocks': blocks,
'mrkdwn': mrkdwn,
})
|
(self, channel, text=None, username=None, as_user=None, parse=None, link_names=None, attachments=None, unfurl_links=None, unfurl_media=None, icon_url=None, icon_emoji=None, thread_ts=None, reply_broadcast=None, blocks=None, mrkdwn=True)
|
70,035 |
slacker
|
unfurl
| null |
def unfurl(self, channel, ts, unfurls, user_auth_message=None,
user_auth_required=False, user_auth_url=None):
return self.post('chat.unfurl',
data={
'channel': channel,
'ts': ts,
'unfurls': unfurls,
'user_auth_message': user_auth_message,
'user_auth_required': user_auth_required,
'user_auth_url': user_auth_url,
})
|
(self, channel, ts, unfurls, user_auth_message=None, user_auth_required=False, user_auth_url=None)
|
70,036 |
slacker
|
update
| null |
def update(self, channel, ts, text, attachments=None, parse=None,
link_names=False, as_user=None, blocks=None):
# Ensure attachments are json encoded
if attachments is not None and isinstance(attachments, list):
attachments = json.dumps(attachments)
return self.post('chat.update',
data={
'channel': channel,
'ts': ts,
'text': text,
'attachments': attachments,
'parse': parse,
'link_names': int(link_names),
'as_user': as_user,
'blocks': blocks
})
|
(self, channel, ts, text, attachments=None, parse=None, link_names=False, as_user=None, blocks=None)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.