desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return twitter search results for a given term. Args: term: Term to search by. Optional if you include geocode. since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occu...
def GetSearch(self, term=None, geocode=None, since_id=None, max_id=None, until=None, count=15, lang=None, locale=None, result_type='mixed', include_entities=None):
parameters = {} if since_id: try: parameters['since_id'] = long(since_id) except: raise TwitterError('since_id must be an integer') if max_id: try: parameters['max_id'] = long(max_id) except: raise TwitterError('max_...
'Return twitter user search results for a given term. Args: term: Term to search by. page: Page of results to return. Default is 1 [Optional] count: Number of results to return. Default is 20 [Optional] include_entities: If True, each tweet will include a node called "entities,". This node offers a variety of metadata...
def GetUsersSearch(self, term=None, page=1, count=20, include_entities=None):
parameters = {} if (term is not None): parameters['q'] = term if include_entities: parameters['include_entities'] = 1 try: parameters['count'] = int(count) except: raise TwitterError('count must be an integer') url = ('%s/users/search.json' % self.base...
'Get the current top trending topics (global) Args: exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with 10 entries. Each entry contains a trend.'
def GetTrendsCurrent(self, exclude=None):
return self.GetTrendsWoeid(id=1, exclude=exclude)
'Return the top 10 trending topics for a specific WOEID, if trending information is available for it. Args: woeid: the Yahoo! Where On Earth ID for a location. exclude: Appends the exclude parameter as a request parameter. Currently only exclude=hashtags is supported. [Optional] Returns: A list with 10 entries. Each en...
def GetTrendsWoeid(self, id, exclude=None):
url = ('%s/trends/place.json' % self.base_url) parameters = {'id': id} if exclude: parameters['exclude'] = exclude json = self._FetchUrl(url, parameters=parameters) data = self._ParseAndCheckTwitter(json) trends = [] timestamp = data[0]['as_of'] for trend in data[0]['trends']: ...
'Fetch a collection of the most recent Tweets and retweets posted by the authenticating user and the users they follow. The home timeline is central to how most users interact with the Twitter service. The twitter.Api instance must be authenticated. Args: count: Specifies the number of statuses to retrieve. May not be ...
def GetHomeTimeline(self, count=None, since_id=None, max_id=None, trim_user=False, exclude_replies=False, contributor_details=False, include_entities=True):
url = ('%s/statuses/home_timeline.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('API must be authenticated.') parameters = {} if (count is not None): try: if (int(count) > 200): raise TwitterError("'count' may not b...
'Fetch the sequence of public Status messages for a single user. The twitter.Api instance must be authenticated if the user is private. Args: user_id: Specifies the ID of the user for whom to return the user_timeline. Helpful for disambiguating when a valid user ID is also a valid screen name. [Optional] screen_name: S...
def GetUserTimeline(self, user_id=None, screen_name=None, since_id=None, max_id=None, count=None, include_rts=None, trim_user=None, exclude_replies=None):
parameters = {} url = ('%s/statuses/user_timeline.json' % self.base_url) if user_id: parameters['user_id'] = user_id elif screen_name: parameters['screen_name'] = screen_name if since_id: try: parameters['since_id'] = long(since_id) except: rai...
'Returns a single status message, specified by the id parameter. The twitter.Api instance must be authenticated. Args: id: The numeric ID of the status you are trying to retrieve. trim_user: When set to True, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Om...
def GetStatus(self, id, trim_user=False, include_my_retweet=True, include_entities=True):
url = ('%s/statuses/show.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('API must be authenticated.') parameters = {} try: parameters['id'] = long(id) except ValueError: raise TwitterError("'id' must be an integer.") if trim_...
'Destroys the status specified by the required ID parameter. The twitter.Api instance must be authenticated and the authenticating user must be the author of the specified status. Args: id: The numerical ID of the status you\'re trying to destroy. Returns: A twitter.Status instance representing the destroyed status mes...
def DestroyStatus(self, id, trim_user=False):
if (not self._oauth_consumer): raise TwitterError('API must be authenticated.') try: post_data = {'id': long(id)} except: raise TwitterError('id must be an integer') url = ('%s/statuses/destroy/%s.json' % (self.base_url, id)) if trim_user: post_da...
'Post a twitter status message from the authenticated user. The twitter.Api instance must be authenticated. https://dev.twitter.com/docs/api/1.1/post/statuses/update Args: status: The message text to be posted. Must be less than or equal to 140 characters. in_reply_to_status_id: The ID of an existing status that the st...
def PostUpdate(self, status, in_reply_to_status_id=None, latitude=None, longitude=None, place_id=None, display_coordinates=False, trim_user=False):
if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') url = ('%s/statuses/update.json' % self.base_url) if (isinstance(status, unicode) or (self._input_encoding is None)): u_status = status else: u_status = unicode(sta...
'Post one or more twitter status messages from the authenticated user. Unlike api.PostUpdate, this method will post multiple status updates if the message is longer than 140 characters. The twitter.Api instance must be authenticated. Args: status: The message text to be posted. May be longer than 140 characters. contin...
def PostUpdates(self, status, continuation=None, **kwargs):
results = list() if (continuation is None): continuation = '' line_length = (CHARACTER_LIMIT - len(continuation)) lines = textwrap.wrap(status, line_length) for line in lines[0:(-1)]: results.append(self.PostUpdate((line + continuation), **kwargs)) results.append(self.PostUpdate(...
'Retweet a tweet with the Retweet API. The twitter.Api instance must be authenticated. Args: original_id: The numerical id of the tweet that will be retweeted trim_user: If True the returned payload will only contain the user IDs, otherwise the payload will contain the full user data item. [Optional] Returns: A twitter...
def PostRetweet(self, original_id, trim_user=False):
if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') try: if (int(original_id) <= 0): raise TwitterError("'original_id' must be a positive number") except ValueError: raise TwitterError("'origin...
'Fetch the sequence of retweets made by the authenticated user. The twitter.Api instance must be authenticated. Args: count: The number of status messages to retrieve. [Optional] since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets whic...
def GetUserRetweets(self, count=None, since_id=None, max_id=None, trim_user=False):
return self.GetUserTimeline(since_id=since_id, count=count, max_id=max_id, trim_user=trim_user, exclude_replies=True, include_rts=True)
'Get a sequence of status messages representing the 20 most recent replies (status updates prefixed with @twitterID) to the authenticating user. Args: since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through th...
def GetReplies(self, since_id=None, count=None, max_id=None, trim_user=False):
return self.GetUserTimeline(since_id=since_id, count=count, max_id=max_id, trim_user=trim_user, exclude_replies=False, include_rts=False)
'Returns up to 100 of the first retweets of the tweet identified by statusid Args: statusid: The ID of the tweet for which retweets should be searched for count: The number of status messages to retrieve. [Optional] trim_user: If True the returned payload will only contain the user IDs, otherwise the payload will conta...
def GetRetweets(self, statusid, count=None, trim_user=False):
if (not self._oauth_consumer): raise TwitterError('The twitter.Api instsance must be authenticated.') url = ('%s/statuses/retweets/%s.json' % (self.base_url, statusid)) parameters = {} if trim_user: parameters['trim_user'] = 'true' if count: try: pa...
'Returns up to 100 of the most recent tweets of the user that have been retweeted by others. Args: count: The number of retweets to retrieve, up to 100. If omitted, 20 is assumed. since_id: Returns results with an ID greater than (newer than) this ID. max_id: Returns results with an ID less than or equal to this ID. tr...
def GetRetweetsOfMe(self, count=None, since_id=None, max_id=None, trim_user=False, include_entities=True, include_user_entities=True):
if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') url = ('%s/statuses/retweets_of_me.json' % self.base_url) parameters = {} if (count is not None): try: if (int(count) > 100): raise TwitterError...
'Fetch the sequence of twitter.User instances, one for each friend. The twitter.Api instance must be authenticated. Args: user_id: The twitter id of the user whose friends you are fetching. If not specified, defaults to the authenticated user. [Optional] screen_name: The twitter name of the user whose friends you are f...
def GetFriends(self, user_id=None, screen_name=None, cursor=(-1), skip_status=False, include_user_entities=False):
if (not self._oauth_consumer): raise TwitterError('twitter.Api instance must be authenticated') url = ('%s/friends/list.json' % self.base_url) result = [] parameters = {} if (user_id is not None): parameters['user_id'] = user_id if (screen_name is not None): p...
'Returns a list of twitter user id\'s for every person the specified user is following. Args: user_id: The id of the user to retrieve the id list for [Optional] screen_name: The screen_name of the user to retrieve the id list for [Optional] cursor: Specifies the Twitter API Cursor location to start at. Note: there are ...
def GetFriendIDs(self, user_id=None, screen_name=None, cursor=(-1), stringify_ids=False, count=None):
url = ('%s/friends/ids.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('twitter.Api instance must be authenticated') parameters = {} if (user_id is not None): parameters['user_id'] = user_id if (screen_name is not None): parameters['screen...
'Returns a list of twitter user id\'s for every person that is following the specified user. Args: user_id: The id of the user to retrieve the id list for [Optional] screen_name: The screen_name of the user to retrieve the id list for [Optional] cursor: Specifies the Twitter API Cursor location to start at. Note: there...
def GetFollowerIDs(self, user_id=None, screen_name=None, cursor=(-1), stringify_ids=False, count=None, total_count=None):
url = ('%s/followers/ids.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('twitter.Api instance must be authenticated') parameters = {} if (user_id is not None): parameters['user_id'] = user_id if (screen_name is not None): parameters['scre...
'Fetch the sequence of twitter.User instances, one for each follower The twitter.Api instance must be authenticated. Args: user_id: The twitter id of the user whose followers you are fetching. If not specified, defaults to the authenticated user. [Optional] screen_name: The twitter name of the user whose followers you ...
def GetFollowers(self, user_id=None, screen_name=None, cursor=(-1), skip_status=False, include_user_entities=False):
if (not self._oauth_consumer): raise TwitterError('twitter.Api instance must be authenticated') url = ('%s/followers/list.json' % self.base_url) result = [] parameters = {} if (user_id is not None): parameters['user_id'] = user_id if (screen_name is not None): ...
'Fetch extended information for the specified users. Users may be specified either as lists of either user_ids, screen_names, or twitter.User objects. The list of users that are queried is the union of all specified parameters. The twitter.Api instance must be authenticated. Args: user_id: A list of user_ids to retriev...
def UsersLookup(self, user_id=None, screen_name=None, users=None, include_entities=True):
if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') if ((not user_id) and (not screen_name) and (not users)): raise TwitterError('Specify at least one of user_id, screen_name, or users.') url = ('%s/users...
'Returns a single user. The twitter.Api instance must be authenticated. Args: user_id: The id of the user to retrieve. [Optional] screen_name: The screen name of the user for whom to return results for. Either a user_id or screen_name is required for this method. [Optional] include_entities: if set to False, the \'enti...
def GetUser(self, user_id=None, screen_name=None, include_entities=True):
url = ('%s/users/show.json' % self.base_url) parameters = {} if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') if user_id: parameters['user_id'] = user_id elif screen_name: parameters['screen_name'] = screen_na...
'Returns a list of the direct messages sent to the authenticating user. The twitter.Api instance must be authenticated. Args: since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tw...
def GetDirectMessages(self, since_id=None, max_id=None, count=None, include_entities=True, skip_status=False):
url = ('%s/direct_messages.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') parameters = {} if since_id: parameters['since_id'] = since_id if max_id: parameters['max_id'] = max_id if...
'Returns a list of the direct messages sent by the authenticating user. The twitter.Api instance must be authenticated. Args: since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tw...
def GetSentDirectMessages(self, since_id=None, max_id=None, count=None, page=None, include_entities=True):
url = ('%s/direct_messages/sent.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') parameters = {} if since_id: parameters['since_id'] = since_id if page: parameters['page'] = page if ...
'Post a twitter direct message from the authenticated user The twitter.Api instance must be authenticated. user_id or screen_name must be specified. Args: text: The message text to be posted. Must be less than 140 characters. user_id: The ID of the user who should receive the direct message. [Optional] screen_name: Th...
def PostDirectMessage(self, text, user_id=None, screen_name=None):
if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') url = ('%s/direct_messages/new.json' % self.base_url) data = {'text': text} if user_id: data['user_id'] = user_id elif screen_name: data['screen_name'] = screen...
'Destroys the direct message specified in the required ID parameter. The twitter.Api instance must be authenticated, and the authenticating user must be the recipient of the specified direct message. Args: id: The id of the direct message to be destroyed Returns: A twitter.DirectMessage instance representing the messag...
def DestroyDirectMessage(self, id, include_entities=True):
url = ('%s/direct_messages/destroy.json' % self.base_url) data = {'id': id} if (not include_entities): data['include_entities'] = 'false' json = self._FetchUrl(url, post_data=data) data = self._ParseAndCheckTwitter(json) return DirectMessage.NewFromJsonDict(data)
'Befriends the user specified by the user_id or screen_name. The twitter.Api instance must be authenticated. Args: user_id: A user_id to follow [Optional] screen_name: A screen_name to follow [Optional] follow: Set to False to disable notifications for the target user Returns: A twitter.User instance representing the b...
def CreateFriendship(self, user_id=None, screen_name=None, follow=True):
url = ('%s/friendships/create.json' % self.base_url) data = {} if user_id: data['user_id'] = user_id elif screen_name: data['screen_name'] = screen_name else: raise TwitterError('Specify at least one of user_id or screen_name.') if follow: dat...
'Discontinues friendship with a user_id or screen_name. The twitter.Api instance must be authenticated. Args: user_id: A user_id to unfollow [Optional] screen_name: A screen_name to unfollow [Optional] Returns: A twitter.User instance representing the discontinued friend.'
def DestroyFriendship(self, user_id=None, screen_name=None):
url = ('%s/friendships/destroy.json' % self.base_url) data = {} if user_id: data['user_id'] = user_id elif screen_name: data['screen_name'] = screen_name else: raise TwitterError('Specify at least one of user_id or screen_name.') json = self._FetchUrl...
'Favorites the specified status object or id as the authenticating user. Returns the favorite status when successful. The twitter.Api instance must be authenticated. Args: id: The id of the twitter status to mark as a favorite. [Optional] status: The twitter.Status object to mark as a favorite. [Optional] include_entit...
def CreateFavorite(self, status=None, id=None, include_entities=True):
url = ('%s/favorites/create.json' % self.base_url) data = {} if id: data['id'] = id elif status: data['id'] = status.id else: raise TwitterError('Specify id or status') if (not include_entities): data['include_entities'] = 'false' json = self._FetchUr...
'Un-Favorites the specified status object or id as the authenticating user. Returns the un-favorited status when successful. The twitter.Api instance must be authenticated. Args: id: The id of the twitter status to unmark as a favorite. [Optional] status: The twitter.Status object to unmark as a favorite. [Optional] in...
def DestroyFavorite(self, status=None, id=None, include_entities=True):
url = ('%s/favorites/destroy.json' % self.base_url) data = {} if id: data['id'] = id elif status: data['id'] = status.id else: raise TwitterError('Specify id or status') if (not include_entities): data['include_entities'] = 'false' json = self._FetchU...
'Return a list of Status objects representing favorited tweets. By default, returns the (up to) 20 most recent tweets for the authenticated user. Args: user: The twitter name or id of the user whose favorites you are fetching. If not specified, defaults to the authenticated user. [Optional] page: Specifies the page of ...
def GetFavorites(self, user_id=None, screen_name=None, count=None, since_id=None, max_id=None, include_entities=True):
parameters = {} url = ('%s/favorites/list.json' % self.base_url) if user_id: parameters['user_id'] = user_id elif screen_name: parameters['screen_name'] = user_id if since_id: try: parameters['since_id'] = long(since_id) except: raise TwitterEr...
'Returns the 20 most recent mentions (status containing @screen_name) for the authenticating user. Args: count: Specifies the number of tweets to try and retrieve, up to a maximum of 200. The value of count is best thought of as a limit to the number of tweets to return because suspended or deleted content is removed a...
def GetMentions(self, count=None, since_id=None, max_id=None, trim_user=False, contributor_details=False, include_entities=True):
url = ('%s/statuses/mentions_timeline.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') parameters = {} if count: try: parameters['count'] = int(count) except: raise T...
'Creates a new list with the give name for the authenticated user. The twitter.Api instance must be authenticated. Args: name: New name for the list mode: \'public\' or \'private\'. Defaults to \'public\'. [Optional] description: Description of the list. [Optional] Returns: A twitter.List instance representing the new ...
def CreateList(self, name, mode=None, description=None):
url = ('%s/lists/create.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') parameters = {'name': name} if (mode is not None): parameters['mode'] = mode if (description is not None): parame...
'Destroys the list identified by list_id or owner_screen_name/owner_id and slug. The twitter.Api instance must be authenticated. Args: owner_screen_name: The screen_name of the user who owns the list being requested by a slug. owner_id: The user ID of the user who owns the list being requested by a slug. list_id: The n...
def DestroyList(self, owner_screen_name=False, owner_id=False, list_id=None, slug=None):
url = ('%s/lists/destroy.json' % self.base_url) data = {} if list_id: try: data['list_id'] = long(list_id) except: raise TwitterError('list_id must be an integer') elif slug: data['slug'] = slug if owner_id: try: ...
'Creates a subscription to a list by the authenticated user The twitter.Api instance must be authenticated. Args: owner_screen_name: The screen_name of the user who owns the list being requested by a slug. owner_id: The user ID of the user who owns the list being requested by a slug. list_id: The numerical id of the li...
def CreateSubscription(self, owner_screen_name=False, owner_id=False, list_id=None, slug=None):
url = ('%s/lists/subscribers/create.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') data = {} if list_id: try: data['list_id'] = long(list_id) except: raise TwitterE...
'Destroys the subscription to a list for the authenticated user The twitter.Api instance must be authenticated. Args: owner_screen_name: The screen_name of the user who owns the list being requested by a slug. owner_id: The user ID of the user who owns the list being requested by a slug. list_id: The numerical id of th...
def DestroySubscription(self, owner_screen_name=False, owner_id=False, list_id=None, slug=None):
url = ('%s/lists/subscribers/destroy.json' % self.base_url) if (not self._oauth_consumer): raise TwitterError('The twitter.Api instance must be authenticated.') data = {} if list_id: try: data['list_id'] = long(list_id) except: raise Twitter...
'Obtain a collection of the lists the specified user is subscribed to, 20 lists per page by default. Does not include the user\'s own lists. The twitter.Api instance must be authenticated. Args: user_id: The ID of the user for whom to return results for. [Optional] screen_name: The screen name of the user for whom to r...
def GetSubscriptions(self, user_id=None, screen_name=None, count=20, cursor=(-1)):
if (not self._oauth_consumer): raise TwitterError('twitter.Api instance must be authenticated') url = ('%s/lists/subscriptions.json' % self.base_url) parameters = {} try: parameters['cursor'] = int(cursor) except: raise TwitterError('cursor must be an ...
'Fetch the sequence of lists for a user. The twitter.Api instance must be authenticated. Args: user_id: The ID of the user for whom to return results for. [Optional] screen_name: The screen name of the user for whom to return results for. [Optional] count: The amount of results to return per page. Defaults to 20. No mo...
def GetLists(self, user_id=None, screen_name=None, count=None, cursor=(-1)):
if (not self._oauth_consumer): raise TwitterError('twitter.Api instance must be authenticated') url = ('%s/lists/ownerships.json' % self.base_url) result = [] parameters = {} if (user_id is not None): try: parameters['user_id'] = long(user_id) except: ...
'Returns a twitter.User instance if the authenticating user is valid. Returns: A twitter.User instance representing that user if the credentials are valid, None otherwise.'
def VerifyCredentials(self):
if (not self._oauth_consumer): raise TwitterError('Api instance must first be given user credentials.') url = ('%s/account/verify_credentials.json' % self.base_url) try: json = self._FetchUrl(url, no_cache=True) except urllib2.HTTPError as http_error: if (htt...
'Override the default cache. Set to None to prevent caching. Args: cache: An instance that supports the same API as the twitter._FileCache'
def SetCache(self, cache):
if (cache == DEFAULT_CACHE): self._cache = _FileCache() else: self._cache = cache
'Override the default urllib implementation. Args: urllib: An instance that supports the same API as the urllib2 module'
def SetUrllib(self, urllib):
self._urllib = urllib
'Override the default cache timeout. Args: cache_timeout: Time, in seconds, that responses should be reused.'
def SetCacheTimeout(self, cache_timeout):
self._cache_timeout = cache_timeout
'Override the default user agent Args: user_agent: A string that should be send to the server as the User-agent'
def SetUserAgent(self, user_agent):
self._request_headers['User-Agent'] = user_agent
'Set the X-Twitter HTTP headers that will be sent to the server. Args: client: The client name as a string. Will be sent to the server as the \'X-Twitter-Client\' header. url: The URL of the meta.xml as a string. Will be sent to the server as the \'X-Twitter-Client-URL\' header. version: The client version as a strin...
def SetXTwitterHeaders(self, client, url, version):
self._request_headers['X-Twitter-Client'] = client self._request_headers['X-Twitter-Client-URL'] = url self._request_headers['X-Twitter-Client-Version'] = version
'Suggest the "from source" value to be displayed on the Twitter web site. The value of the \'source\' parameter must be first recognized by the Twitter server. New source values are authorized on a case by case basis by the Twitter development team. Args: source: The source name as a string. Will be sent to the serve...
def SetSource(self, source):
self._default_params['source'] = source
'Fetch the rate limit status for the currently authorized user. Args: resources: A comma seperated list of resource families you want to know the current rate limit disposition of. [Optional] Returns: A dictionary containing the time the limit will reset (reset_time), the number of remaining hits allowed before the res...
def GetRateLimitStatus(self, resources=None):
parameters = {} if (resources is not None): parameters['resources'] = resources url = ('%s/application/rate_limit_status.json' % self.base_url) json = self._FetchUrl(url, parameters=parameters, no_cache=True) data = self._ParseAndCheckTwitter(json) return data
'Determines the minimum number of seconds that a program must wait before hitting the server again without exceeding the rate_limit imposed for the currently authenticated user. Returns: The minimum second interval that a program must use so as to not exceed the rate_limit imposed for the user.'
def MaximumHitFrequency(self):
rate_status = self.GetRateLimitStatus() reset_time = rate_status.get('reset_time', None) limit = rate_status.get('remaining_hits', None) if reset_time: reset = datetime.datetime(*rfc822.parsedate(reset_time)[:7]) delta = ((reset + datetime.timedelta(hours=1)) - datetime.datetime.utcnow()...
'Return a string in key=value&key=value form Values of None are not included in the output string. Args: parameters: A dict of (key, value) tuples, where value is encoded as specified by self._encoding Returns: A URL-encoded string in "key=value&key=value" form'
def _EncodeParameters(self, parameters):
if (parameters is None): return None else: return urllib.urlencode(dict([(k, self._Encode(v)) for (k, v) in parameters.items() if (v is not None)]))
'Return a string in key=value&key=value form Values are assumed to be encoded in the format specified by self._encoding, and are subsequently URL encoded. Args: post_data: A dict of (key, value) tuples, where value is encoded as specified by self._encoding Returns: A URL-encoded string in "key=value&key=value" form'
def _EncodePostData(self, post_data):
if (post_data is None): return None else: return urllib.urlencode(dict([(k, self._Encode(v)) for (k, v) in post_data.items()]))
'Try and parse the JSON returned from Twitter and return an empty dictionary if there is any error. This is a purely defensive check because during some Twitter network outages it will return an HTML failwhale page.'
def _ParseAndCheckTwitter(self, json):
try: data = simplejson.loads(json) self._CheckForTwitterError(data) except ValueError: if ('<title>Twitter / Over capacity</title>' in json): raise TwitterError('Capacity Error') if ('<title>Twitter / Error</title>' in json): raise Twitte...
'Raises a TwitterError if twitter returns an error message. Args: data: A python dict created from the Twitter json response Raises: TwitterError wrapping the twitter error message if one exists.'
def _CheckForTwitterError(self, data):
if ('error' in data): raise TwitterError(data['error']) if ('errors' in data): raise TwitterError(data['errors'])
'Fetch a URL, optionally caching for a specified time. Args: url: The URL to retrieve post_data: A dict of (str, unicode) key/value pairs. If set, POST will be used. parameters: A dict whose key/value pairs should encoded and added to the query string. [Optional] no_cache: If true, overrides the cache on the current re...
def _FetchUrl(self, url, post_data=None, parameters=None, no_cache=None, use_gzip_compression=None):
extra_params = {} if self._default_params: extra_params.update(self._default_params) if parameters: extra_params.update(parameters) if post_data: http_method = 'POST' else: http_method = 'GET' if self._debugHTTP: _debug = 1 else: _debug = 0 ...
'Attempt to find the username in a cross-platform fashion.'
def _GetUsername(self):
try: return (os.getenv('USER') or os.getenv('LOGNAME') or os.getenv('USERNAME') or os.getlogin() or 'nobody') except (AttributeError, IOError, OSError) as e: return 'nobody'
'compile the given regexp, cache the reg, and call match_reg().'
def match(self, regexp, flags=None):
try: reg = _regexp_cache[(regexp, flags)] except KeyError: if flags: reg = re.compile(regexp, flags) else: reg = re.compile(regexp) _regexp_cache[(regexp, flags)] = reg return self.match_reg(reg)
'match the given regular expression object to the current text position. if a match occurs, update the current text and line position.'
def match_reg(self, reg):
mp = self.match_position match = reg.match(self.text, self.match_position) if match: (start, end) = match.span() if (end == start): self.match_position = (end + 1) else: self.match_position = end self.matched_lineno = self.lineno lines = re.fin...
'given string/unicode or bytes/string, determine encoding from magic encoding comment, return body as unicode or raw if decode_raw=False'
def decode_raw_stream(self, text, decode_raw, known_encoding, filename):
if isinstance(text, compat.text_type): m = self._coding_re.match(text) encoding = ((m and m.group(1)) or known_encoding or 'ascii') return (encoding, text) if text.startswith(codecs.BOM_UTF8): text = text[len(codecs.BOM_UTF8):] parsed_encoding = 'utf-8' m = self._...
'matches the multiline version of a comment'
def match_comment(self):
match = self.match('<%doc>(.*?)</%doc>', re.S) if match: self.append_node(parsetree.Comment, match.group(1)) return True else: return False
'Traverse a template structure for module-level directives and generate the start of module-level code.'
def write_toplevel(self):
inherit = [] namespaces = {} module_code = [] self.compiler.pagetag = None class FindTopLevel(object, ): def visitInheritTag(s, node): inherit.append(node) def visitNamespaceTag(s, node): namespaces[node.name] = node def visitPageTag(s, node): ...
'write a top-level render callable. this could be the main render() method or that of a top-level def.'
def write_render_callable(self, node, name, args, buffered, filtered, cached):
if self.in_def: decorator = node.decorator if decorator: self.printer.writeline(('@runtime._decorate_toplevel(%s)' % decorator)) self.printer.start_source(node.lineno) self.printer.writelines(('def %s(%s):' % (name, ','.join(args))), '__M_caller = context.caller_stack._p...
'write module-level template code, i.e. that which is enclosed in <%! %> tags in the template.'
def write_module_code(self, module_code):
for n in module_code: self.printer.start_source(n.lineno) self.printer.write_indented_block(n.text)
'write the module-level inheritance-determination callable.'
def write_inherit(self, node):
self.printer.writelines('def _mako_inherit(template, context):', '_mako_generate_namespaces(context)', ('return runtime._inherit_from(context, %s, _template_uri)' % node.parsed_attributes['file']), None)
'write the module-level namespace-generating callable.'
def write_namespaces(self, namespaces):
self.printer.writelines('def _mako_get_namespace(context, name):', 'try:', 'return context.namespaces[(__name__, name)]', 'except KeyError:', '_mako_generate_namespaces(context)', 'return context.namespaces[(__name__, name)]', None, None) self.printer.writeline('def _mako_generate_namesp...
'write variable declarations at the top of a function. the variable declarations are in the form of callable definitions for defs and/or name lookup within the function\'s context argument. the names declared are based on the names that are referenced in the function body, which don\'t otherwise have any explicit assig...
def write_variable_declares(self, identifiers, toplevel=False, limit=None):
comp_idents = dict([(c.funcname, c) for c in identifiers.defs]) to_write = set() to_write = to_write.union(identifiers.undeclared) to_write = to_write.union([c.funcname for c in identifiers.closuredefs.values()]) to_write = to_write.difference(identifiers.argument_declared) to_write = to_write.d...
'write a locally-available callable referencing a top-level def'
def write_def_decl(self, node, identifiers):
funcname = node.funcname namedecls = node.get_argument_expressions() nameargs = node.get_argument_expressions(as_call=True) if ((not self.in_def) and ((len(self.identifiers.locally_assigned) > 0) or (len(self.identifiers.argument_declared) > 0))): nameargs.insert(0, 'context._locals(__M_locals)'...
'write a locally-available def callable inside an enclosing def.'
def write_inline_def(self, node, identifiers, nested):
namedecls = node.get_argument_expressions() decorator = node.decorator if decorator: self.printer.writeline(('@runtime._decorate_inline(context, %s)' % decorator)) self.printer.writeline(('def %s(%s):' % (node.funcname, ','.join(namedecls)))) filtered = (len(node.filter_args.args) > 0)...
'write the end section of a rendering function, either outermost or inline. this takes into account if the rendering function was filtered, buffered, etc. and closes the corresponding try: block if any, and writes code to retrieve captured content, apply filters, send proper return value.'
def write_def_finish(self, node, buffered, filtered, cached, callstack=True):
if ((not buffered) and (not cached) and (not filtered)): self.printer.writeline("return ''") if callstack: self.printer.writelines('finally:', 'context.caller_stack._pop_frame()', None) if (buffered or filtered or cached): if (buffered or cached): self.printer....
'write a post-function decorator to replace a rendering callable with a cached version of itself.'
def write_cache_decorator(self, node_or_pagetag, name, args, buffered, identifiers, inline=False, toplevel=False):
self.printer.writeline(('__M_%s = %s' % (name, name))) cachekey = node_or_pagetag.parsed_attributes.get('cache_key', repr(name)) cache_args = {} if (self.compiler.pagetag is not None): cache_args.update(((pa[6:], self.compiler.pagetag.parsed_attributes[pa]) for pa in self.compiler.pagetag....
'write a filter-applying expression based on the filters present in the given filter names, adjusting for the global \'default\' filter aliases as needed.'
def create_filter_callable(self, args, target, is_expression):
def locate_encode(name): if re.match('decode\\..+', name): return ('filters.' + name) elif self.compiler.disable_unicode: return filters.NON_UNICODE_ESCAPES.get(name, name) else: return filters.DEFAULT_ESCAPES.get(name, name) if ('n' not in args): ...
'create a new Identifiers for a new Node, with this Identifiers as the parent.'
def branch(self, node, **kwargs):
return _Identifiers(self.compiler, node, self, **kwargs)
'update the state of this Identifiers with the undeclared and declared identifiers of the given node.'
def check_declared(self, node):
for ident in node.undeclared_identifiers(): if ((ident != 'context') and (ident not in self.declared.union(self.locally_declared))): self.undeclared.add(ident) for ident in node.declared_identifiers(): self.locally_declared.add(ident)
'return true if the given keyword is a ternary keyword for this ControlLine'
def is_ternary(self, keyword):
return (keyword in {'if': set(['else', 'elif']), 'try': set(['except', 'finally']), 'for': set(['else'])}.get(self.keyword, []))
'construct a new Tag instance. this constructor not called directly, and is only called by subclasses. :param keyword: the tag keyword :param attributes: raw dictionary of attribute key/value pairs :param expressions: a set of identifiers that are legal attributes, which can also contain embedded expressions :param non...
def __init__(self, keyword, attributes, expressions, nonexpressions, required, **kwargs):
super(Tag, self).__init__(**kwargs) self.keyword = keyword self.attributes = attributes self._parse_attributes(expressions, nonexpressions) missing = [r for r in required if (r not in self.parsed_attributes)] if len(missing): raise exceptions.CompileException(('Missing attribute(s): ...
'Return the argument declarations of this FunctionDecl as a printable list. By default the return value is appropriate for writing in a ``def``; set `as_call` to true to build arguments to be passed to the function instead (assuming locals with the same names as the arguments exist).'
def get_argument_expressions(self, as_call=False):
namedecls = [] argnames = self.argnames[::(-1)] kwargnames = self.kwargnames[::(-1)] defaults = self.defaults[::(-1)] kwdefaults = self.kwdefaults[::(-1)] if self.kwargs: namedecls.append(('**' + kwargnames.pop(0))) for name in kwargnames: if as_call: namedecls.ap...
'produce a \'union\' of this dict and another (at the key level). values in the second dict take precedence over that of the first'
def union(self, other):
x = SetLikeDict(**self) x.update(other) return x
'Find a unicode representation of self.error'
def _init_message(self):
try: self.message = compat.text_type(self.error) except UnicodeError: try: self.message = str(self.error) except UnicodeEncodeError: self.message = self.error.args[0] if (not isinstance(self.message, compat.text_type)): self.message = compat.text_type(...
'Return a list of 4-tuple traceback records (i.e. normal python format) with template-corresponding lines remapped to the originating template.'
@property def traceback(self):
return list(self._get_reformatted_records(self.records))
'Return the same data as traceback, except in reverse order.'
@property def reverse_traceback(self):
return list(self._get_reformatted_records(self.reverse_records))
'format a traceback from sys.exc_info() into 7-item tuples, containing the regular four traceback tuple items, plus the original template filename, the line number adjusted relative to the template source, and code line from that line number of the template.'
def _init(self, trcback):
import mako.template mods = {} rawrecords = traceback.extract_tb(trcback) new_trcback = [] for (filename, lineno, function, line) in rawrecords: if (not line): line = '' try: (line_map, template_lines) = mods[filename] except KeyError: try:...
'Return the template source code for this :class:`.Template`.'
@property def source(self):
return _get_module_info_from_callable(self.callable_).source
'Return the module source code for this :class:`.Template`.'
@property def code(self):
return _get_module_info_from_callable(self.callable_).code
'Render the output of this template as a string. If the template specifies an output encoding, the string will be encoded accordingly, else the output is raw (raw output uses `cStringIO` and can\'t handle multibyte characters). A :class:`.Context` object is created corresponding to the given data. Arguments that are ex...
def render(self, *args, **data):
return runtime._render(self, self.callable_, args, data)
'Render the output of this template as a unicode object.'
def render_unicode(self, *args, **data):
return runtime._render(self, self.callable_, args, data, as_unicode=True)
'Render this :class:`.Template` with the given context. The data is written to the context\'s buffer.'
def render_context(self, context, *args, **kwargs):
if (getattr(context, '_with_template', None) is None): context._set_with_template(self) runtime._render_context(self, self.callable_, context, *args, **kwargs)
'Return a def of this template as a :class:`.DefTemplate`.'
def get_def(self, name):
return DefTemplate(self, getattr(self.module, ('render_%s' % name)))
'Return the :class:`.TemplateLookup` associated with this :class:`.Context`.'
@property def lookup(self):
return self._with_template.lookup
'Return the dictionary of top level keyword arguments associated with this :class:`.Context`. This dictionary only includes the top-level arguments passed to :meth:`.Template.render`. It does not include names produced within the template execution such as local variable names or special names such as ``self``, ``next...
@property def kwargs(self):
return self._kwargs.copy()
'Push a ``caller`` callable onto the callstack for this :class:`.Context`.'
def push_caller(self, caller):
self.caller_stack.append(caller)
'Pop a ``caller`` callable onto the callstack for this :class:`.Context`.'
def pop_caller(self):
del self.caller_stack[(-1)]
'Return a list of all names established in this :class:`.Context`.'
def keys(self):
return list(self._data.keys())
'push a capturing buffer onto this Context and return the new writer function.'
def _push_writer(self):
buf = util.FastEncodingBuffer() self._buffer_stack.append(buf) return buf.write
'pop the most recent capturing buffer from this Context and return the current writer after the pop.'
def _pop_buffer_and_writer(self):
buf = self._buffer_stack.pop() return (buf, self._buffer_stack[(-1)].write)
'push a capturing buffer onto this Context.'
def _push_buffer(self):
self._push_writer()
'pop the most recent capturing buffer from this Context.'
def _pop_buffer(self):
return self._buffer_stack.pop()
'Return a value from this :class:`.Context`.'
def get(self, key, default=None):
return self._data.get(key, compat_builtins.__dict__.get(key, default))
'Write a string to this :class:`.Context` object\'s underlying output buffer.'
def write(self, string):
self._buffer_stack[(-1)].write(string)
'Return the current writer function.'
def writer(self):
return self._buffer_stack[(-1)].write
'Create a new :class:`.Context` with a copy of this :class:`.Context`\'s current state, updated with the given dictionary. The :attr:`.Context.kwargs` collection remains unaffected.'
def _locals(self, d):
if (not d): return self c = self._copy() c._data.update(d) return c
'create a new copy of this :class:`.Context`. with tokens related to inheritance state removed.'
def _clean_inheritance_tokens(self):
c = self._copy() x = c._data x.pop('self', None) x.pop('parent', None) x.pop('next', None) return c
'Cycle through values as the loop progresses.'
def cycle(self, *values):
if (not values): raise ValueError('You must provide values to cycle through') return values[(self.index % len(values))]
'Access module level attributes by name. This accessor allows templates to supply "scalar" attributes which are particularly handy in inheritance relationships. .. seealso:: :ref:`inheritance_attr` :ref:`namespace_attr_for_includes`'
@util.memoized_property def attr(self):
return _NSAttr(self)
'Return a :class:`.Namespace` corresponding to the given ``uri``. If the given ``uri`` is a relative URI (i.e. it does not contain a leading slash ``/``), the ``uri`` is adjusted to be relative to the ``uri`` of the namespace itself. This method is therefore mostly useful off of the built-in ``local`` namespace, descri...
def get_namespace(self, uri):
key = (self, uri) if (key in self.context.namespaces): return self.context.namespaces[key] else: ns = TemplateNamespace(uri, self.context._copy(), templateuri=uri, calling_uri=self._templateuri) self.context.namespaces[key] = ns return ns