desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Perform configuration which is common to root and non-root loggers.'
| def common_logger_config(self, logger, config, incremental=False):
| level = config.get('level', None)
if (level is not None):
logger.setLevel(_checkLevel(level))
if (not incremental):
for h in logger.handlers[:]:
logger.removeHandler(h)
handlers = config.get('handlers', None)
if handlers:
self.add_handlers(logger, hand... |
'Configure a non-root logger from a dictionary.'
| def configure_logger(self, name, config, incremental=False):
| logger = logging.getLogger(name)
self.common_logger_config(logger, config, incremental)
propagate = config.get('propagate', None)
if (propagate is not None):
logger.propagate = propagate
|
'Configure a root logger from a dictionary.'
| def configure_root(self, config, incremental=False):
| root = logging.getLogger()
self.common_logger_config(root, config, incremental)
|
'Handle a record. Does nothing in this class, but in other
handlers it typically filters and then emits the record in a
thread-safe way.'
| def handle(self, record):
| pass
|
'Emit a record. This does nothing and shouldn\'t be called during normal
processing, unless you redefine :meth:`~logutils.NullHandler.handle`.'
| def emit(self, record):
| pass
|
'Since this handler does nothing, it has no underlying I/O to protect
against multi-threaded access, so this method returns `None`.'
| def createLock(self):
| self.lock = None
|
'Initialize the formatter with specified format strings.
Initialize the formatter either with the specified format string, or a
default as described above. Allow for specialized date formatting with
the optional datefmt argument (if omitted, you get the ISO8601 format).
Use a style parameter of \'%\', \'{\' or \'$\' to... | def __init__(self, fmt=None, datefmt=None, style='%'):
| if (style not in _STYLES):
raise ValueError(('Style must be one of: %s' % ','.join(_STYLES.keys())))
self._style = _STYLES[style](fmt)
self._fmt = self._style._fmt
self.datefmt = datefmt
|
'Check if the format uses the creation time of the record.'
| def usesTime(self):
| return self._style.usesTime()
|
'Format the specified record as text.
The record\'s attribute dictionary is used as the operand to a
string formatting operation which yields the returned string.
Before formatting the dictionary, a couple of preparatory steps
are carried out. The message attribute of the record is computed
using LogRecord.getMessage()... | def format(self, record):
| record.message = record.getMessage()
if self.usesTime():
record.asctime = self.formatTime(record, self.datefmt)
s = self.formatMessage(record)
if record.exc_info:
if (not record.exc_text):
record.exc_text = self.formatException(record.exc_info)
if record.exc_text:
... |
'Initialize the adapter with a logger and a dict-like object which
provides contextual information. This constructor signature allows
easy stacking of LoggerAdapters, if so desired.
You can effectively pass keyword arguments as shown in the
following example:
adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))'
| def __init__(self, logger, extra):
| self.logger = logger
self.extra = extra
|
'Process the logging message and keyword arguments passed in to
a logging call to insert contextual information. You can either
manipulate the message itself, the keyword args or both. Return
the message and kwargs modified (or not) to suit your needs.
Normally, you\'ll only need to override this one method in a
Logger... | def process(self, msg, kwargs):
| kwargs['extra'] = self.extra
return (msg, kwargs)
|
'Delegate a debug call to the underlying logger.'
| def debug(self, msg, *args, **kwargs):
| self.log(logging.DEBUG, msg, *args, **kwargs)
|
'Delegate an info call to the underlying logger.'
| def info(self, msg, *args, **kwargs):
| self.log(logging.INFO, msg, *args, **kwargs)
|
'Delegate a warning call to the underlying logger.'
| def warning(self, msg, *args, **kwargs):
| self.log(logging.WARNING, msg, *args, **kwargs)
|
'Delegate an error call to the underlying logger.'
| def error(self, msg, *args, **kwargs):
| self.log(logging.ERROR, msg, *args, **kwargs)
|
'Delegate an exception call to the underlying logger.'
| def exception(self, msg, *args, **kwargs):
| kwargs['exc_info'] = 1
self.log(logging.ERROR, msg, *args, **kwargs)
|
'Delegate a critical call to the underlying logger.'
| def critical(self, msg, *args, **kwargs):
| self.log(logging.CRITICAL, msg, *args, **kwargs)
|
'Delegate a log call to the underlying logger, after adding
contextual information from this adapter instance.'
| def log(self, level, msg, *args, **kwargs):
| if self.isEnabledFor(level):
(msg, kwargs) = self.process(msg, kwargs)
self.logger._log(level, msg, args, **kwargs)
|
'Is this logger enabled for level \'level\'?'
| def isEnabledFor(self, level):
| if (self.logger.manager.disable >= level):
return False
return (level >= self.getEffectiveLevel())
|
'Set the specified level on the underlying logger.'
| def setLevel(self, level):
| self.logger.setLevel(level)
|
'Get the effective level for the underlying logger.'
| def getEffectiveLevel(self):
| return self.logger.getEffectiveLevel()
|
'See if the underlying logger has any handlers.'
| def hasHandlers(self):
| return logutils.hasHandlers(self.logger)
|
'Should the buffer be flushed?
This returns `False` - you\'ll need to flush manually, usually after
your unit test code checks the buffer contents against your
expectations.'
| def shouldFlush(self):
| return False
|
'Saves the `__dict__` of the record in the `buffer` attribute,
and the formatted records in the `formatted` attribute.
:param record: The record to emit.'
| def emit(self, record):
| self.formatted.append(self.format(record))
self.buffer.append(record.__dict__)
|
'Clears out the `buffer` and `formatted` attributes.'
| def flush(self):
| BufferingHandler.flush(self)
self.formatted = []
|
'Look for a saved dict whose keys/values match the supplied arguments.
Return `True` if found, else `False`.
:param kwargs: A set of keyword arguments whose names are LogRecord
attributes and whose values are what you want to
match in a stored LogRecord.'
| def matches(self, **kwargs):
| result = False
for d in self.buffer:
if self.matcher.matches(d, **kwargs):
result = True
break
return result
|
'Accept a list of keyword argument values and ensure that the handler\'s
buffer of stored records matches the list one-for-one.
Return `True` if exactly matched, else `False`.
:param kwarglist: A list of keyword-argument dictionaries, each of
which will be passed to :meth:`matches` with the
corresponding record from th... | def matchall(self, kwarglist):
| if (self.count != len(kwarglist)):
result = False
else:
result = True
for (d, kwargs) in zip(self.buffer, kwarglist):
if (not self.matcher.matches(d, **kwargs)):
result = False
break
return result
|
'The number of records in the buffer.'
| @property
def count(self):
| return len(self.buffer)
|
'Try to match a single dict with the supplied arguments.
Keys whose values are strings and which are in self._partial_matches
will be checked for partial (i.e. substring) matches. You can extend
this scheme to (for example) do regular expression matching, etc.
Return `True` if found, else `False`.
:param kwargs: A set ... | def matches(self, d, **kwargs):
| result = True
for k in kwargs:
v = kwargs[k]
dv = d.get(k)
if (not self.match_value(k, dv, v)):
result = False
break
return result
|
'Try to match a single stored value (dv) with a supplied value (v).
Return `True` if found, else `False`.
:param k: The key value (LogRecord attribute name).
:param dv: The stored value to match against.
:param v: The value to compare with the stored value.'
| def match_value(self, k, dv, v):
| if (type(v) != type(dv)):
result = False
elif ((type(dv) is not str) or (k not in self._partial_matches)):
result = (v == dv)
else:
result = (dv.find(v) >= 0)
return result
|
'Returns true if the handler\'s stream is a terminal.'
| @property
def is_tty(self):
| isatty = getattr(self.stream, 'isatty', None)
return (isatty and isatty())
|
'Colorize a message for a logging event.
This implementation uses the ``level_map`` class attribute to
map the LogRecord\'s level to a colour/intensity setting, which is
then applied to the whole message.
:param message: The message to colorize.
:param record: The ``LogRecord`` for the message.'
| def colorize(self, message, record):
| if (record.levelno in self.level_map):
(bg, fg, bold) = self.level_map[record.levelno]
params = []
if (bg in self.color_map):
params.append(str((self.color_map[bg] + 40)))
if (fg in self.color_map):
params.append(str((self.color_map[fg] + 30)))
if bold... |
'Formats a record for output.
This implementation colorizes the message line, but leaves
any traceback unolorized.'
| def format(self, record):
| message = logging.StreamHandler.format(self, record)
if self.is_tty:
parts = message.split('\n', 1)
parts[0] = self.colorize(parts[0], record)
message = '\n'.join(parts)
return message
|
'Initialize an instance.'
| def __init__(self, host, url, method='GET', secure=False, credentials=None):
| logging.Handler.__init__(self)
method = method.upper()
if (method not in ['GET', 'POST']):
raise ValueError('method must be GET or POST')
self.host = host
self.url = url
self.method = method
self.secure = secure
self.credentials = credentials
|
'Default implementation of mapping the log record into a dict
that is sent as the CGI data. Overwrite in your class.
Contributed by Franz Glasner.
:param record: The record to be mapped.'
| def mapLogRecord(self, record):
| return record.__dict__
|
'Emit a record.
Send the record to the Web server as a percent-encoded dictionary
:param record: The record to be emitted.'
| def emit(self, record):
| try:
import http.client, urllib.parse
host = self.host
if self.secure:
h = http.client.HTTPSConnection(host)
else:
h = http.client.HTTPConnection(host)
url = self.url
data = urllib.parse.urlencode(self.mapLogRecord(record))
if (self.met... |
'Modify the request headers to add the appropriate
Authorization header. Over-rise 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)
|
'The parameter proxy_type 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)'
| def __init__(self, proxy_type, proxy_host, proxy_port, proxy_rdns=None, proxy_user=None, proxy_pass=None):
| (self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns, self.proxy_user, self.proxy_pass) = (proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass)
|
'Connect to the host and port specified in __init__.'
| def connect(self):
| msg = 'getaddrinfo returns an empty list'
for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):
(af, socktype, proto, canonname, sa) = res
try:
if (self.proxy_info and self.proxy_info.isgood()):
self.sock = socks.socksocket(af, sockty... |
'Connect to a host on a given (SSL) port.'
| def connect(self):
| if (self.proxy_info and self.proxy_info.isgood()):
sock = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM)
sock.setproxy(*self.proxy_info.astuple())
else:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if has_timeout(self.timeout):
sock.settimeout(self.timeout)
... |
'The value of proxy_info is a ProxyInfo instance.
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.'
| def __init__(self, cache=None, timeout=None, proxy_info=None):
| self.proxy_info = proxy_info
self.connections = {}
if (cache and isinstance(cache, str)):
self.cache = FileCache(cache)
else:
self.cache = cache
self.credentials = Credentials()
self.certificates = KeyCerts()
self.authorizations = []
self.follow_redirects = True
self.... |
'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' % __version__)
uri = iri2uri(uri)
(scheme, authority, request_uri... |
'Return processed HTML as a single string'
| def output(self):
| return ''.join([str(p) for p in self.pieces])
|
'Adds an artist to the known list of artists tagged with this tag (if necessary), and sets the count of times
that that artist has been known to be tagged with this tag.'
| def set_artist_count(self, artist, count):
| self.artist_counts[artist] = count
|
'Takes parsed JSON response from \'inbox\' action on api
and updates the available subset of mailbox information.'
| def set_mbox_data(self, mbox_resp):
| self.current_page = mbox_resp['currentPage']
self.total_pages = mbox_resp['pages']
self.messages = [MailboxMessage(self.parent_api, m) for m in mbox_resp['messages']]
|
'Calls \'index\' API action, then updates this User objects information with it.
NOTE: Only call if this user is the logged-in user...throws InvalidUserException otherwise.'
| def update_index_data(self):
| response = self.parent_api.request(action='index')
self.set_index_data(response)
|
'Takes parsed JSON response from \'index\' action on api, and updates the available subset of user information.
ONLY callable if this User object represents the currently logged in user. Throws InvalidUserException otherwise.'
| def set_index_data(self, index_json_response):
| if (self.id != index_json_response['id']):
raise InvalidUserException(("Tried to update non-logged-in User's information from 'index' API call." + (' Should be %s, got %s' % (self.id, index_json_response['id']))))
self.username = index_json_response['username']
... |
'Takes parsed JSON response from \'user\' action on api, and updates relevant user information.
To avoid problems, only pass in user data from an API call that used this user\'s ID as an argument.'
| def set_user_data(self, user_json_response):
| if (self.username and (self.username != user_json_response['username'])):
raise InvalidUserException(("Tried to update a user's information from a 'user' API call with a different username." + (' Should be %s, got %s' % (self.username, user_json_respo... |
'Takes a single user result item from a \'usersearch\' API call and updates user info.'
| def set_search_result_data(self, search_result_item):
| if (self.id != search_result_item['userId']):
raise InvalidUserException("Tried to update existing user with another user's search result data (IDs don't match).")
self.username = search_result_item['username']
if (not self.personal):
self.personal = {}... |
'Private method.
Logs in user and gets authkey from server.'
| def _login(self):
| if self.logged_in():
return
self.wait_for_rate_limit()
loginpage = (self.site + 'login.php')
data = {'username': self.username, 'password': self.password, 'keeplogged': '1'}
r = self.session.post(loginpage, data=data, timeout=self.default_timeout, headers=self.default_headers)
self.past_... |
'Makes an AJAX request at a given action.
Pass an action and relevant arguments for that action.'
| def request(self, action, autologin=True, **kwargs):
| def make_request(action, **kwargs):
ajaxpage = 'ajax.php'
content = self.unparsed_request(ajaxpage, action, **kwargs)
try:
if (not isinstance(content, text_type)):
content = content.decode('utf-8')
parsed = json.loads(content)
if (parsed['s... |
'Makes a generic HTTP request at a given page with a given action.
Also pass relevant arguments for that action.'
| def unparsed_request(self, sitepage, action, **kwargs):
| self.wait_for_rate_limit()
url = ('%s%s' % (self.site, sitepage))
params = {'action': action}
if self.authkey:
params['auth'] = self.authkey
params.update(kwargs)
r = self.session.get(url, params=params, allow_redirects=False, timeout=self.default_timeout)
if ((r.status_code == 302) ... |
'Returns a User for the passed ID, associated with this API object. If the ID references the currently logged in
user, the user returned will be pre-populated with the information from an \'index\' API call. Otherwise, you\'ll
need to call User.update_user_data(). This is done on demand to reduce unnecessary API calls.... | def get_user(self, id):
| id = int(id)
if (id == self.userid):
return self.logged_in_user
elif (id in self.cached_users.keys()):
return self.cached_users[id]
else:
return User(id, self)
|
'Returns a list of users returned for the search query. You can search by name, part of name, and ID number. If
one of the returned users is the currently logged-in user, that user object will be pre-populated with the
information from an \'index\' API call. Otherwise only the limited info returned by the search will b... | def search_users(self, search_query):
| response = self.request(action='usersearch', search=search_query)
results = response['results']
found_users = []
for result in results:
user = self.get_user(result['userId'])
user.set_search_result_data(result)
found_users.append(user)
return found_users
|
'Returns the inbox Mailbox for the logged in user'
| def get_inbox(self, page='1', sort='unread'):
| return Mailbox(self, 'inbox', page, sort)
|
'Returns the sentbox Mailbox for the logged in user'
| def get_sentbox(self, page='1', sort='unread'):
| return Mailbox(self, 'sentbox', page, sort)
|
'Returns an Artist for the passed ID, associated with this API object. You\'ll need to call Artist.update_data()
if the artist hasn\'t already been cached. This is done on demand to reduce unnecessary API calls.'
| def get_artist(self, id=None, name=None):
| if id:
id = int(id)
if (id in self.cached_artists.keys()):
artist = self.cached_artists[id]
else:
artist = Artist(id, self)
if name:
artist.name = HTMLParser().unescape(name)
elif name:
artist = Artist((-1), self)
artist.name = ... |
'Returns a Tag for the passed name, associated with this API object. If you know the count value for this tag,
pass it to update the object. There is no way to query the count directly from the API, but it can be retrieved
from other calls such as \'artist\', however.'
| def get_tag(self, name):
| if (name in self.cached_tags.keys()):
return self.cached_tags[name]
else:
return Tag(name, self)
|
'Returns a Request for the passed ID, associated with this API object. You\'ll need to call Request.update_data()
if the request hasn\'t already been cached. This is done on demand to reduce unnecessary API calls.'
| def get_request(self, id):
| id = int(id)
if (id in self.cached_requests.keys()):
return self.cached_requests[id]
else:
return Request(id, self)
|
'Returns a TorrentGroup for the passed ID, associated with this API object.'
| def get_torrent_group(self, id):
| id = int(id)
if (id in self.cached_torrent_groups.keys()):
return self.cached_torrent_groups[id]
else:
return TorrentGroup(id, self)
|
'Returns a Torrent for the passed ID, associated with this API object.'
| def get_torrent(self, id):
| id = int(id)
if (id in self.cached_torrents.keys()):
return self.cached_torrents[id]
else:
return Torrent(id, self)
|
'Returns a Torrent for the passed info hash (if one exists), associated with this API object.'
| def get_torrent_from_info_hash(self, info_hash):
| try:
response = self.request(action='torrent', hash=info_hash.upper())
except RequestException:
return None
id = int(response['torrent']['id'])
if (id in self.cached_torrents.keys()):
torrent = self.cached_torrents[id]
else:
torrent = Torrent(id, self)
torrent.set... |
'Returns a Category for the passed ID, associated with this API object.'
| def get_category(self, id, name=None):
| id = int(id)
if (id in self.cached_categories.keys()):
cat = self.cached_categories[id]
else:
cat = Category(id, self)
if name:
cat.name = name
return cat
|
'Lists the top <limit> items of <type>. Type can be "torrents", "tags", or "users". Limit MUST be
10, 25, or 100...it can\'t just be an arbitrary number (unfortunately). Results are organized into a list of hashes.
Each hash contains the results for a specific time frame, like \'day\', or \'week\'. In the hash, the \'r... | def get_top_10(self, type='torrents', limit=25):
| response = self.request(action='top10', type=type, limit=limit)
top_items = []
if (not response):
raise RequestException
for category in response:
results = []
if (type == 'torrents'):
for item in category['results']:
torrent = self.get_torrent(item['t... |
'Searches based on the args you pass and returns torrent groups filled with torrents.
Pass strings unless otherwise specified.
Valid search args:
searchstr (any arbitrary string to search for)
page (page to display -- default: 1)
artistname (self explanatory)
groupname (torrent group name, equivalent to album)
recordla... | def search_torrents(self, **kwargs):
| response = self.request(action='browse', **kwargs)
results = response['results']
if len(results):
curr_page = response['currentPage']
pages = response['pages']
else:
curr_page = 1
pages = 1
matching_torrents = []
for torrent_group_dict in results:
torrent_... |
'Takes parsed JSON response from \'torrentgroup\' action on api, and updates relevant information.
To avoid problems, only pass in data from an API call that used this torrentgroup\'s ID as an argument.'
| def set_group_data(self, torrent_group_json_response):
| if (self.id != torrent_group_json_response['group']['id']):
raise InvalidTorrentGroupException(("Tried to update a TorrentGroup's information from an 'artist' API call with a different id." + (' Should be %s, got %s' % (self.id, torrent_group_json_res... |
'Takes torrentgroup section from parsed JSON response from \'artist\' action on api, and updates relevant information.'
| def set_artist_group_data(self, artist_group_json_response):
| if (self.id != artist_group_json_response['groupId']):
raise InvalidTorrentGroupException(("Tried to update a TorrentGroup's information from an 'artist' API call with a different id." + (' Should be %s, got %s' % (self.id, artist_group_json_response[... |
'Returns the first argument used to construct this error.'
| @property
def message(self):
| return self.args[0]
|
'An object to hold a Twitter status message.
This class is normally instantiated by the twitter.Api class and
returned in a sequence.
Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007"
Args:
created_at:
The time this status message was posted. [Optional]
favorited:
Whether this is a favorite of the aut... | def __init__(self, created_at=None, favorited=None, favorite_count=None, id=None, text=None, location=None, user=None, in_reply_to_screen_name=None, in_reply_to_user_id=None, in_reply_to_status_id=None, truncated=None, source=None, now=None, urls=None, user_mentions=None, hashtags=None, media=None, geo=None, place=None... | self.created_at = created_at
self.favorited = favorited
self.favorite_count = favorite_count
self.id = id
self.text = text
self.location = location
self.user = user
self.now = now
self.in_reply_to_screen_name = in_reply_to_screen_name
self.in_reply_to_user_id = in_reply_to_user_i... |
'Get the time this status message was posted.
Returns:
The time this status message was posted'
| def GetCreatedAt(self):
| return self._created_at
|
'Set the time this status message was posted.
Args:
created_at:
The time this status message was created'
| def SetCreatedAt(self, created_at):
| self._created_at = created_at
|
'Get the time this status message was posted, in seconds since the epoch.
Returns:
The time this status message was posted, in seconds since the epoch.'
| def GetCreatedAtInSeconds(self):
| return calendar.timegm(rfc822.parsedate(self.created_at))
|
'Get the favorited setting of this status message.
Returns:
True if this status message is favorited; False otherwise'
| def GetFavorited(self):
| return self._favorited
|
'Set the favorited state of this status message.
Args:
favorited:
boolean True/False favorited state of this status message'
| def SetFavorited(self, favorited):
| self._favorited = favorited
|
'Get the favorite count of this status message.
Returns:
number of times this status message has been favorited'
| def GetFavoriteCount(self):
| return self._favorite_count
|
'Set the favorited state of this status message.
Args:
favorite_count:
int number of favorites for this status message'
| def SetFavoriteCount(self, favorite_count):
| self._favorite_count = favorite_count
|
'Get the unique id of this status message.
Returns:
The unique id of this status message'
| def GetId(self):
| return self._id
|
'Set the unique id of this status message.
Args:
id:
The unique id of this status message'
| def SetId(self, id):
| self._id = id
|
'Get the text of this status message.
Returns:
The text of this status message.'
| def GetText(self):
| return self._text
|
'Set the text of this status message.
Args:
text:
The text of this status message'
| def SetText(self, text):
| self._text = text
|
'Get the geolocation associated with this status message
Returns:
The geolocation string of this status message.'
| def GetLocation(self):
| return self._location
|
'Set the geolocation associated with this status message
Args:
location:
The geolocation string of this status message'
| def SetLocation(self, location):
| self._location = location
|
'Get a human readable string representing the posting time
Returns:
A human readable string representing the posting time'
| def GetRelativeCreatedAt(self):
| fudge = 1.25
delta = (long(self.now) - long(self.created_at_in_seconds))
if (delta < (1 * fudge)):
return 'about a second ago'
elif (delta < (60 * (1 / fudge))):
return ('about %d seconds ago' % delta)
elif (delta < (60 * fudge)):
return 'about a minut... |
'Get a twitter.User representing the entity posting this status message.
Returns:
A twitter.User representing the entity posting this status message'
| def GetUser(self):
| return self._user
|
'Set a twitter.User representing the entity posting this status message.
Args:
user:
A twitter.User representing the entity posting this status message'
| def SetUser(self, user):
| self._user = user
|
'Get the wallclock time for this status message.
Used to calculate relative_created_at. Defaults to the time
the object was instantiated.
Returns:
Whatever the status instance believes the current time to be,
in seconds since the epoch.'
| def GetNow(self):
| if (self._now is None):
self._now = time.time()
return self._now
|
'Set the wallclock time for this status message.
Used to calculate relative_created_at. Defaults to the time
the object was instantiated.
Args:
now:
The wallclock time for this instance.'
| def SetNow(self, now):
| self._now = now
|
'A string representation of this twitter.Status instance.
The return value is the same as the JSON string representation.
Returns:
A string representation of this twitter.Status instance.'
| def __str__(self):
| return self.AsJsonString()
|
'A JSON string representation of this twitter.Status instance.
Returns:
A JSON string representation of this twitter.Status instance'
| def AsJsonString(self):
| return simplejson.dumps(self.AsDict(), sort_keys=True)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.