Minor Streaming work; not official, just hackery for fun. Fork and patch or look away.
This commit is contained in:
parent
ed14371d38
commit
2122f6528d
10 changed files with 26 additions and 215 deletions
|
|
@ -1,11 +0,0 @@
|
|||
#!/usr/bin/env python
|
||||
from django.core.management import execute_manager
|
||||
try:
|
||||
import settings # Assumed to be in the same directory.
|
||||
except ImportError:
|
||||
import sys
|
||||
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
execute_manager(settings)
|
||||
|
|
@ -1,94 +0,0 @@
|
|||
import os.path
|
||||
|
||||
DEBUG = True
|
||||
TEMPLATE_DEBUG = DEBUG
|
||||
|
||||
ADMINS = (
|
||||
('Ryan McGrath', 'ryan@venodesigns.net'),
|
||||
)
|
||||
|
||||
MANAGERS = ADMINS
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
|
||||
'NAME': os.path.join(os.path.dirname(__file__), 'test.db'), # Or path to database file if using sqlite3.
|
||||
'USER': '', # Not used with sqlite3.
|
||||
'PASSWORD': '', # Not used with sqlite3.
|
||||
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
|
||||
'PORT': '', # Set to empty string for default. Not used with sqlite3.
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
AUTH_PROFILE_MODULE = 'twitter.Profile'
|
||||
|
||||
# Local time zone for this installation. Choices can be found here:
|
||||
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
|
||||
# although not all choices may be available on all operating systems.
|
||||
# On Unix systems, a value of None will cause Django to use the same
|
||||
# timezone as the operating system.
|
||||
# If running in a Windows environment this must be set to the same as your
|
||||
# system time zone.
|
||||
TIME_ZONE = 'America/New_York'
|
||||
|
||||
# Language code for this installation. All choices can be found here:
|
||||
# http://www.i18nguy.com/unicode/language-identifiers.html
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
|
||||
SITE_ID = 1
|
||||
|
||||
# If you set this to False, Django will make some optimizations so as not
|
||||
# to load the internationalization machinery.
|
||||
USE_I18N = True
|
||||
|
||||
# If you set this to False, Django will not format dates, numbers and
|
||||
# calendars according to the current locale
|
||||
USE_L10N = True
|
||||
|
||||
# Absolute path to the directory that holds media.
|
||||
# Example: "/home/media/media.lawrence.com/"
|
||||
MEDIA_ROOT = ''
|
||||
|
||||
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
|
||||
# trailing slash if there is a path component (optional in other cases).
|
||||
# Examples: "http://media.lawrence.com", "http://example.com/media/"
|
||||
MEDIA_URL = ''
|
||||
|
||||
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
|
||||
# trailing slash.
|
||||
# Examples: "http://foo.com/media/", "/media/".
|
||||
ADMIN_MEDIA_PREFIX = '/media/'
|
||||
|
||||
# Make this unique, and don't share it with anybody.
|
||||
SECRET_KEY = '&!_t1t^gmenaid9mkmkuw=4nthj7f)o+!@$#ipfp*s11380t*)'
|
||||
|
||||
# List of callables that know how to import templates from various sources.
|
||||
TEMPLATE_LOADERS = (
|
||||
'django.template.loaders.filesystem.Loader',
|
||||
'django.template.loaders.app_directories.Loader',
|
||||
# 'django.template.loaders.eggs.Loader',
|
||||
)
|
||||
|
||||
MIDDLEWARE_CLASSES = (
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
)
|
||||
|
||||
ROOT_URLCONF = 'twython_testing.urls'
|
||||
|
||||
TEMPLATE_DIRS = (
|
||||
os.path.join(os.path.dirname(__file__), 'templates'),
|
||||
)
|
||||
|
||||
INSTALLED_APPS = (
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.sites',
|
||||
'django.contrib.messages',
|
||||
'twitter',
|
||||
)
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
{% for tweet in tweets %}
|
||||
{{ tweet.text }}
|
||||
{% endfor %}
|
||||
Binary file not shown.
|
|
@ -1,7 +0,0 @@
|
|||
from django.db import models
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
class Profile(models.Model):
|
||||
user = models.ForeignKey(User)
|
||||
oauth_token = models.CharField(max_length = 200)
|
||||
oauth_secret = models.CharField(max_length = 200)
|
||||
|
|
@ -1,73 +0,0 @@
|
|||
from django.contrib.auth import authenticate, login, logout
|
||||
from django.contrib.auth.models import User
|
||||
from django.http import HttpResponse, HttpResponseRedirect
|
||||
from django.shortcuts import render_to_response
|
||||
from django.contrib.auth.decorators import login_required
|
||||
|
||||
from twython import Twython
|
||||
from twitter.models import Profile
|
||||
|
||||
CONSUMER_KEY = "YOUR CONSUMER KEY HERE"
|
||||
CONSUMER_SECRET = "YOUR CONSUMER SECRET HERE"
|
||||
|
||||
def twitter_logout(request):
|
||||
logout(request)
|
||||
return HttpResponseRedirect('/')
|
||||
|
||||
def twitter_begin_auth(request):
|
||||
# Instantiate Twython with the first leg of our trip.
|
||||
twitter = Twython(
|
||||
twitter_token = CONSUMER_KEY,
|
||||
twitter_secret = CONSUMER_SECRET
|
||||
)
|
||||
|
||||
# Request an authorization url to send the user to...
|
||||
auth_props = twitter.get_authentication_tokens()
|
||||
|
||||
# Then send them over there, durh.
|
||||
request.session['request_token'] = auth_props
|
||||
return HttpResponseRedirect(auth_props['auth_url'])
|
||||
|
||||
def twitter_thanks(request):
|
||||
# Now that we've got the magic tokens back from Twitter, we need to exchange
|
||||
# for permanent ones and store them...
|
||||
twitter = Twython(
|
||||
twitter_token = CONSUMER_KEY,
|
||||
twitter_secret = CONSUMER_SECRET,
|
||||
oauth_token = request.session['request_token']['oauth_token'],
|
||||
oauth_token_secret = request.session['request_token']['oauth_token_secret']
|
||||
)
|
||||
|
||||
# Retrieve the tokens we want...
|
||||
authorized_tokens = twitter.get_authorized_tokens()
|
||||
|
||||
# If they already exist, grab them, login and redirect to a page displaying stuff.
|
||||
try:
|
||||
user = User.objects.get(username = authorized_tokens['screen_name'])
|
||||
except User.DoesNotExist:
|
||||
# We mock a creation here; no email, password is just the token, etc.
|
||||
user = User.objects.create_user(authorized_tokens['screen_name'], "fjdsfn@jfndjfn.com", authorized_tokens['oauth_token_secret'])
|
||||
profile = Profile()
|
||||
profile.user = user
|
||||
profile.oauth_token = authorized_tokens['oauth_token']
|
||||
profile.oauth_secret = authorized_tokens['oauth_token_secret']
|
||||
profile.save()
|
||||
|
||||
user = authenticate(
|
||||
username = authorized_tokens['screen_name'],
|
||||
password = authorized_tokens['oauth_token_secret']
|
||||
)
|
||||
login(request, user)
|
||||
return HttpResponseRedirect('/timeline')
|
||||
|
||||
def twitter_timeline(request):
|
||||
user = request.user.get_profile()
|
||||
twitter = Twython(
|
||||
twitter_token = CONSUMER_KEY,
|
||||
twitter_secret = CONSUMER_SECRET,
|
||||
oauth_token = user.oauth_token,
|
||||
oauth_token_secret = user.oauth_secret
|
||||
)
|
||||
my_tweets = twitter.getHomeTimeline()
|
||||
print my_tweets
|
||||
return render_to_response('tweets.html', {'tweets': my_tweets})
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
from django.conf.urls.defaults import *
|
||||
from twitter.views import twitter_begin_auth, twitter_thanks, twitter_logout, twitter_timeline
|
||||
|
||||
urlpatterns = patterns('',
|
||||
(r'^login/?$', twitter_begin_auth),
|
||||
(r'^/logout?$', twitter_logout),
|
||||
(r'^thanks/?$', twitter_thanks), # Where they're redirect to after authorizing
|
||||
(r'^timeline/?$', twitter_timeline),
|
||||
)
|
||||
|
|
@ -1,37 +1,50 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
"""
|
||||
Yes, this is just in __init__ for now, hush.
|
||||
|
||||
The beginnings of Twitter Streaming API support in Twython. Don't expect this to work at all,
|
||||
consider it a stub for now. -- Ryan
|
||||
TwythonStreamer is an implementation of the Streaming API for Twython.
|
||||
Pretty self explanatory by reading the code below. It's worth noting
|
||||
that the end user should, ideally, never import this library, but rather
|
||||
this is exposed via a linking method in Twython's core.
|
||||
|
||||
Questions, comments? ryan@venodesigns.net
|
||||
"""
|
||||
|
||||
import httplib, urllib, urllib2, mimetypes, mimetools, socket, time
|
||||
__author__ = "Ryan McGrath <ryan@venodesigns.net>"
|
||||
__version__ = "1.0.0"
|
||||
|
||||
import urllib
|
||||
import urllib2
|
||||
import urlparse
|
||||
import httplib
|
||||
import httplib2
|
||||
import re
|
||||
|
||||
from urllib2 import HTTPError
|
||||
|
||||
# There are some special setups (like, oh, a Django application) where
|
||||
# simplejson exists behind the scenes anyway. Past Python 2.6, this should
|
||||
# never really cause any problems to begin with.
|
||||
try:
|
||||
import simplejson
|
||||
# Python 2.6 and up
|
||||
import json as simplejson
|
||||
except ImportError:
|
||||
try:
|
||||
import json as simplejson
|
||||
# Python 2.6 and below (2.4/2.5, 2.3 is not guranteed to work with this library to begin with)
|
||||
import simplejson
|
||||
except ImportError:
|
||||
try:
|
||||
# This case gets rarer by the day, but if we need to, we can pull it from Django provided it's there.
|
||||
from django.utils import simplejson
|
||||
except:
|
||||
raise Exception("Twython (Streaming) requires the simplejson library (or Python 2.6) to work. http://www.undefined.org/python/")
|
||||
|
||||
__author__ = "Ryan McGrath <ryan@venodesigns.net>"
|
||||
__version__ = "0.1"
|
||||
# Seriously wtf is wrong with you if you get this Exception.
|
||||
raise Exception("Twython requires the simplejson library (or Python 2.6) to work. http://www.undefined.org/python/")
|
||||
|
||||
class TwythonStreamingError(Exception):
|
||||
def __init__(self, msg):
|
||||
self.msg = msg
|
||||
|
||||
def __str__(self):
|
||||
return repr(self.msg)
|
||||
return "%s" % str(self.msg)
|
||||
|
||||
feeds = {
|
||||
"firehose": "http://stream.twitter.com/firehose.json",
|
||||
|
|
@ -43,10 +56,5 @@ feeds = {
|
|||
"track": "http://stream.twitter.com/track.json",
|
||||
}
|
||||
|
||||
class stream:
|
||||
class Stream(object):
|
||||
def __init__(self, username = None, password = None, feed = "spritzer", user_agent = "Twython Streaming"):
|
||||
self.username = username
|
||||
self.password = password
|
||||
self.feed = feeds[feed]
|
||||
self.user_agent = user_agent
|
||||
self.connection_open = False
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue