Merge branch 'master' of git@github.com:ryanmcgrath/twython

This commit is contained in:
Ryan McGrath 2010-10-14 10:11:31 -04:00
commit 3f0d64fb3b
4 changed files with 87 additions and 31 deletions

1
.gitignore vendored
View file

@ -2,3 +2,4 @@
build build
dist dist
twython.egg-info twython.egg-info
*.swp

3
MANIFEST.in Normal file
View file

@ -0,0 +1,3 @@
include LICENSE README.markdown
recursive-include examples *
recursive-exclude examples *.pyc

View file

@ -1,46 +1,42 @@
#!/usr/bin/python #!/usr/bin/python
import sys, os import sys, os
from setuptools import setup
from setuptools import find_packages
__author__ = 'Ryan McGrath <ryan@venodesigns.net>' __author__ = 'Ryan McGrath <ryan@venodesigns.net>'
__version__ = '1.2' __version__ = '1.2'
# Distutils version
METADATA = dict( setup(
name = "twython",
# Basic package information.
name = 'twython',
version = __version__, version = __version__,
py_modules = ['setup', 'twython/__init__', 'twython/core', 'twython/twyauth', 'twython/streaming', 'twython/oauth'], packages = find_packages(),
# Packaging options.
include_package_data = True,
# Package dependencies.
install_requires = ['simplejson'],
# Metadata for PyPI.
author = 'Ryan McGrath', author = 'Ryan McGrath',
author_email = 'ryan@venodesigns.net', author_email = 'ryan@venodesigns.net',
description = 'An easy (and up to date) way to access Twitter data with Python.',
long_description = open("README.markdown").read(),
license = 'MIT License', license = 'MIT License',
url = 'http://github.com/ryanmcgrath/twython/tree/master', url = 'http://github.com/ryanmcgrath/twython/tree/master',
keywords = 'twitter search api tweet twython', keywords = 'twitter search api tweet twython',
) description = 'An easy (and up to date) way to access Twitter data with Python.',
long_description = open('README.markdown').read(),
# Setuptools version
SETUPTOOLS_METADATA = dict(
install_requires = ['setuptools', 'simplejson'],
include_package_data = True,
classifiers = [ classifiers = [
'Development Status :: 4 - Beta', 'Development Status :: 4 - Beta',
'Intended Audience :: Developers', 'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License', 'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Communications :: Chat', 'Topic :: Communications :: Chat',
'Topic :: Internet', 'Topic :: Internet'
] ]
) )
def Main():
try:
import setuptools
METADATA.update(SETUPTOOLS_METADATA)
setuptools.setup(**METADATA)
except ImportError:
import distutils.core
distutils.core.setup(**METADATA)
if __name__ == '__main__':
Main()

View file

@ -10,15 +10,20 @@
Questions, comments? ryan@venodesigns.net Questions, comments? ryan@venodesigns.net
""" """
import httplib, urllib, urllib2, mimetypes, mimetools
import httplib
import urllib
import urllib2
import mimetypes
import mimetools
from urlparse import urlparse from urlparse import urlparse
from urllib2 import HTTPError from urllib2 import HTTPError
__author__ = "Ryan McGrath <ryan@venodesigns.net>" __author__ = "Ryan McGrath <ryan@venodesigns.net>"
__version__ = "1.1" __version__ = "1.1"
"""Twython - Easy Twitter utilities in Python"""
try: try:
import simplejson import simplejson
@ -31,6 +36,7 @@ except ImportError:
except: except:
raise Exception("Twython requires the simplejson library (or Python 2.6) to work. http://www.undefined.org/python/") raise Exception("Twython requires the simplejson library (or Python 2.6) to work. http://www.undefined.org/python/")
class TwythonError(Exception): class TwythonError(Exception):
def __init__(self, msg, error_code=None): def __init__(self, msg, error_code=None):
self.msg = msg self.msg = msg
@ -39,20 +45,25 @@ class TwythonError(Exception):
def __str__(self): def __str__(self):
return repr(self.msg) return repr(self.msg)
class APILimit(TwythonError): class APILimit(TwythonError):
def __init__(self, msg): def __init__(self, msg):
self.msg = msg self.msg = msg
def __str__(self): def __str__(self):
return repr(self.msg) return repr(self.msg)
class AuthError(TwythonError): class AuthError(TwythonError):
def __init__(self, msg): def __init__(self, msg):
self.msg = msg self.msg = msg
def __str__(self): def __str__(self):
return repr(self.msg) return repr(self.msg)
class setup: class setup:
def __init__(self, username = None, password = None, headers = None, proxy = None, version = 1):
def __init__(self, username=None, password=None, headers=None, proxy=None,
version=1):
"""setup(username = None, password = None, proxy = None, headers = None) """setup(username = None, password = None, proxy = None, headers = None)
Instantiates an instance of Twython. Takes optional parameters for authentication and such (see below). Instantiates an instance of Twython. Takes optional parameters for authentication and such (see below).
@ -1360,6 +1371,51 @@ class setup:
except HTTPError, e: except HTTPError, e:
raise TwythonError("getSearchTimeline() failed with a %s error code." % `e.code`, e.code) raise TwythonError("getSearchTimeline() failed with a %s error code." % `e.code`, e.code)
def searchTwitterGen(self, search_query, **kwargs):
"""searchTwitterGen(search_query, **kwargs)
Returns a generator of tweets that match a specified query.
Parameters:
callback - Optional. Only available for JSON format. If supplied, the response will use the JSONP format with a callback of the given name.
lang - Optional. Restricts tweets to the given language, given by an ISO 639-1 code.
locale - Optional. Language of the query you're sending (only ja is currently effective). Intended for language-specific clients; default should work in most cases.
rpp - Optional. The number of tweets to return per page, up to a max of 100.
page - Optional. The page number (starting at 1) to return, up to a max of roughly 1500 results (based on rpp * page. Note: there are pagination limits.)
since_id - Optional. Returns tweets with status ids greater than the given id.
geocode - Optional. Returns tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Twitter profile. The parameter value is specified by "latitide,longitude,radius", where radius units must be specified as either "mi" (miles) or "km" (kilometers). Note that you cannot use the near operator via the API to geocode arbitrary locations; however you can use this geocode parameter to search near geocodes directly.
show_user - Optional. When true, prepends "<user>:" to the beginning of the tweet. This is useful for readers that do not display Atom's author field. The default is false.
Usage Notes:
Queries are limited 140 URL encoded characters.
Some users may be absent from search results.
The since_id parameter will be removed from the next_page element as it is not supported for pagination. If since_id is removed a warning will be added to alert you.
This method will return an HTTP 404 error if since_id is used and is too old to be in the search index.
Applications must have a meaningful and unique User Agent when using this method.
An HTTP Referrer is expected but not required. Search traffic that does not include a User Agent will be rate limited to fewer API calls per hour than
applications including a User Agent string. You can set your custom UA headers by passing it as a respective argument to the setup() method.
"""
searchURL = self.constructApiURL("http://search.twitter.com/search.json", kwargs) + "&" + urllib.urlencode({"q": self.unicode2utf8(search_query)})
try:
data = simplejson.load(self.opener.open(searchURL))
except HTTPError, e:
raise TwythonError("searchTwitterGen() failed with a %s error code." % `e.code`, e.code)
if not data['results']:
raise StopIteration
for tweet in data['results']:
yield tweet
if 'page' not in kwargs:
kwargs['page'] = 2
else:
kwargs['page'] += 1
for tweet in self.searchTwitterGen(search_query, **kwargs):
yield tweet
def getCurrentTrends(self, excludeHashTags = False, version = None): def getCurrentTrends(self, excludeHashTags = False, version = None):
"""getCurrentTrends(excludeHashTags = False, version = None) """getCurrentTrends(excludeHashTags = False, version = None)
@ -1645,20 +1701,20 @@ class setup:
raise AuthError("It seems the list you're trying to access is private/protected, and you don't have access. Are you authenticated and allowed?") raise AuthError("It seems the list you're trying to access is private/protected, and you don't have access. Are you authenticated and allowed?")
raise TwythonError("getSpecificList() failed with a %d error code." % e.code, e.code) raise TwythonError("getSpecificList() failed with a %d error code." % e.code, e.code)
def addListMember(self, list_id, version = None): def addListMember(self, list_id, id, version = None):
""" addListMember(self, list_id, id, version) """ addListMember(self, list_id, id, version)
Adds a new Member (the passed in id) to the specified list. Adds a new Member (the passed in id) to the specified list.
Parameters: Parameters:
list_id - Required. The slug of the list to add the new member to. list_id - Required. The slug of the list to add the new member to.
id - Required. The ID of the user that's being added to the list. id - Required. The ID or slug of the user that's being added to the list.
version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc. version (number) - Optional. API version to request. Entire Twython class defaults to 1, but you can override on a function-by-function or class basis - (version=2), etc.
""" """
version = version or self.apiVersion version = version or self.apiVersion
if self.authenticated is True: if self.authenticated is True:
try: try:
return simplejson.load(self.opener.open("http://api.twitter.com/%d/%s/%s/members.json" % (version, self.username, list_id), "id=%s" % `id`)) return simplejson.load(self.opener.open("http://api.twitter.com/%d/%s/%s/members.json" % (version, self.username, list_id), "id=%s" % (id)))
except HTTPError, e: except HTTPError, e:
raise TwythonError("addListMember() failed with a %d error code." % e.code, e.code) raise TwythonError("addListMember() failed with a %d error code." % e.code, e.code)
else: else: