Top Banner

of 20

Www Ibm Com Developerworks Opensource Library Os Social Twit

Apr 05, 2018

Download

Documents

Elie Obeid
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    1/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    Sign in (or register)English

    Technica l topics Eva lua tion software Community Events Search developerWorks

    Cesar Otero, Consultant, Freelance Consultant

    Summary: Learn how to create a Twitter-enabled Web 2.0-style application us ing Django,jQuery, and the python-twitter wrapper that you can easily use and plug in to your ownDjango project. With this application, you'll be able to s ee recent tweets, post updates, andshow your friends and followers.

    Tags for this article: django,jquery, twitter

    Tag this! Update My dW interests (Log in | What's this?)

    Date: 03 Dec 2009 (Published 24 Nov 2009)

    Level: Intermediate

    Also available in: Russian Japanese Portuguese

    Activity: 22977 views

    Comments: 0 (

    View |Add comment - Sign in)

    Average rating (7 votes)

    Rate this article

    developerWorks Open source Technical library

    These days, it seems li ke Twitter is ubiquitous. Politicians, actors, parents you name i t are using the social networkingmedium . Clients are not only demanding Web applications that are Twitter-enabled but that also have a slick Web 2.0 look tothem, which is only achieved through Ajax. Enter Django and jQuery.

    Figure 1. Twitter panel displaying recent tweets

    Table of contents

    Dependencies

    The python-twitter library

    Adding jQuery to the mix

    Creating your Django project

    Build a Twitter Web applicationWriting for Web 2.0 with Django and jQuery

    http://www.ibm.com/developerworks/http://www.ibm.com/developerworks/opensource/http://www.ibm.com/developerworks/views/opensource/library.jsphttp://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdfhttp://www.ibm.com/developerworks/dwwi/DWAuthRouter?m=loginpage&lang=en&d=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fopensource%2Flibrary%2Fos-social-twitter%2Findex.htmlhttp://www.ibm.com/developerWorks/http://www.ibm.com/developerworks/topics/http://www.ibm.com/developerworks/downloads/http://www.ibm.com/developerworks/community/http://www.ibm.com/developerworks/events/http://launchtagwindow%28%27/developerworks/mydeveloperworks/bookmarks/html?tag=django%27)http://launchtagwindow%28%27/developerworks/mydeveloperworks/bookmarks/html?tag=jquery%27)http://launchtagwindow%28%27/developerworks/mydeveloperworks/bookmarks/html?tag=twitter%27)http://www.ibm.com/developerworks/opensource/library/os-social-twitter/index.htmlhttps://www.ibm.com/developerworks/dwwi/DWAuthRouter?m=loginpage&d=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fopensource%2Flibrary%2Fos-social-twitter%2Findex.htmlhttp://www.ibm.com/developerworks/ru/library/os-social-twitter/http://www.ibm.com/developerworks/jp/opensource/library/os-social-twitter/http://www.ibm.com/developerworks/br/opensource/library/os-social-twitter/http://www.ibm.com/developerworks/http://www.ibm.com/developerworks/opensource/http://www.ibm.com/developerworks/views/opensource/library.jsp
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    2/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    Frequently used acronyms

    Ajax:Asynchronous JavaScript + XML

    API: Application programm ing interface

    CSS: Cascading s tyle sheet

    FAQ: Frequently asked questions

    HTML: Hypertext Markup Language

    HTTP: Hypertext Transfer Protocol

    REST:Representational State Transfer

    UI:User interface

    Dependencies

    I highly recommend going through the Django tutorial beforecommencing work on this. You will als o need a solid JavaScriptfoundation. It goes without saying that you will need a Twitter accountand mus t know the lingo, such as what a tweetis. Your arsenalshould contain Python, Django, jQuery, and the python-twitterwrapper. See Resources for links.

    You will also need the sqli te3 database, included with Python, forcontaining the session data; the Twitter infrastructure will s ave

    everything else. But, as an improvement on this application, you

    could certainly integrate a more sophis ticated database structure tokeep statistics, copies of tweets, or what's on your Twitter account onyour own s erver, for example. This article also as sumes that you'reworking on Linux.

    I tested the sample application with Python V2.5.2. Python is installed by default on mos t Linux machines; if you don't havePython installed, s ee Resources for information on downloading and installing the language.

    Twitter's data is exposed to the public through two APIs: the search API and the RESTful API. (The Twitter FAQ mentions futureplans for a single API.) A REST Web service is a Web service implemented in HTTP that follows REST principals (seeResources for more information).

    Crafting your URLs

    The views

    The templates

    Conclusion

    Download

    Resources

    About the author

    Comments

    Next steps from IBM

    Take advantage of open, flexible and

    New IBM approaches for delivering

    Web 2.0 applications.

    Try: Creating Web 2.0 Social

    Network applications is a snapw ith Rational Application

    Developer.

    Article: This article Explains how touse A jax and JSF together in

    Rational Application Developer.

    Tutorial: Develop a Facebook app

    using PHP, Java and RationalApplication Developer - a full

    featured Eclipse based IDE.

    Demo: This demo show s how touse Rational Application Developer

    w ith the new Java EE 5 Java

    Persistence API (JPA) framew ork.

    Buy: Rational ApplicationDeveloper

    Tags

    Search all tags

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdfhttp://www.ibm.com/developerworks/downloads/r/rad/http://www-128.ibm.com/developerworks/rational/library/06/1205_kats_rad2/http://www.ibm.com/developerworks/edu/r-dw-r-face.htmlhttp://www.ibm.com/developerworks/offers/lp/demos/summary/r-radjpa.htmlhttp://www.ibm.com/software/dre/h2b/buildh2bpage.wss?synkey=E348426A11522S79
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    3/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    Installing the python-twitter wrapper

    The final component you need is python-twitter, which is "a python wrapper around the Twitter API and the twitter data m odel,"according to the project site. There are s everal libraries for interfacing with Twitter's services in many languages anything fromRuby to Eiffel. Currently, there are five libraries for interfacing Python with Twitter: Python-twitter by DeWitt Clinton, python-twyt byAndrew Price, twitty-twis ter by Dustin Sallings, twython by Ryan McGrath, and Tweepy by Josh Roesslein.

    The python-twitter library requires the dependency sim plejson (see Resources). After you download s implejs on, install it byissuing the commands shown in Listing 1.

    Listing 1. Commands for installing simplejson

    tar -zxvf simplejson-2.0.9.tar.gzcd simplejson-2.0.9sudo python setup.py buildsudo python setup.py install

    If you prefer to use the egg package, you can use the comm and sudo easy_install simplejson-2.0.9-py2.5-

    win32.egg.

    Now, you can install python-twitter. After you download the package, execute the commands shown in Lis ting 2.

    Listing 2. Commands for installing python-twitter

    tar -zxvf python-twitter-0.6.tar.gzcd python-twitter-0.6sudo python setup.py buildsudo python setup.py install

    Installing Django

    Next on the ins tallation list is Django, a powerful Python Web framework. The sample application in this article was written withV1.1.1. The ins tallation is just as easy as s implejs on and python-twitter. After downloading the package, enter the commandsshown in Lis ting 3 in any terminal.

    Listing 3. Commands for installing Django

    tar -zxvf Django-1.1.1.tar.gzcd Django-1.1.1sudo python setup.py buildsudo python setup.py install

    My article tags

    More Less

    ajax and android apache

    application_a...

    application_...

    architecture architecture_-...

    atom business_proce...

    business_proce... cloud

    cloud_computi... components

    configuration_... css_(cascading...

    databases_and... db2

    design development dojo

    dom_(document_... eclipse

    editing formatting f rameworks

    general_progr... html html5

    integration interoperabili... java

    java_technol.. . javascriptjquery jsf json

    json_(javascri... linux mashups

    messaging mobile

    mobile_and_emb... mobility

    multimedia namespaces

    open_source parsing

    patterns performance php

    php_(hypertex... programming

    python rest rss_(really_si...

    ruby schemas security

    services soa soa_(service-...

    soap_(simple_... spring

    standards standards_and_...

    tips web web_2.0

    web_authoring

    w eb_developmen...

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdf
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    4/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    Verify that Django is on your path by trying the command $ django-admin --version. If everything went as planned, you're

    ready to start coding.

    Back to top

    The python-twitter library

    Now that you have ins talled python-twitter, you can explore its capabilities. To access the library, use the comm and import

    twitter. The twitter module provides wrappers for the Twitter data model and the API. There are three data model classes :

    twitter.Status, twitter.User, and twitter.DirectMessage. All API calls return an object of one of these classes . Toaccess the API, make an instance oftwitter.Api() (notice that the first letter is capitalized). Creating an ins tance without any

    arguments to the constructor is valid, but you're limited to m ethod calls that don't require a login. To have login access , use thefollowing code:

    import twitterapi = twitter.Api(username='yourUserName', password='yourPassword')

    With an ins tantiated Api object, you can get your followers, people you are following, and s tatuses (tweets); pos t your current

    status; etc. For example, to get a l ist of a us er's statuses , call statuses = api.GetUserTimeline(), which returns a list of

    twitter.Status objects. To create another list with the text (strings) of your tweets, you could use lis t comprehension:

    >>>print [s.text for s in statuses].

    Table 1 lists classes and m ethods you will be using in your Web application. For the full documentation, use the pydocs $

    pydoc twitter.Api, for example or visit the python-twitter docs page (see Resources).

    Table 1. Some useful python-twitter API methods

    Method name Returns Description

    GetUserTimeline() List oftwitter.Status objects Get all tw eets for a user

    GetFriends() List oftwitter.User objects Get a list of follow ers

    PostUpdate() A single twitter.Status Post a tw eet

    Back to top

    Adding jQuery to the mix

    To be more specific, you're not just using the jQuery core but also the jQuery UI, which provides widgets, themes , and animation.Head over to the ThemeRoller page, and in the left pane, click the Gallery tab. Choose a theme you like (I used Cupertino for the

    _ w r

    w sdl_(web_serv...

    xhtml_(extensi... xml

    xpath_(xml_pat...

    xquery_(xml_qu... xslt

    xslt_(xsl_tran...

    View as cloud | list

    Dig deeper into Open source ondeveloperWorks

    Overview

    New to Open source

    Projects

    Technical library (articles,tutorials, and more)

    Forums

    Events

    Newsletter

    Discover knowledge paths

    Skill-building guides for open

    source, Linux, c loud, Java,business analytics, and more.

    Special offers

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdfhttp://jqueryui.com/themerollerhttp://www.ibm.com/developerworks/opensource/http://www.ibm.com/developerworks/opensource/newto/http://www.ibm.com/developerworks/opensource/find/projects/http://www.ibm.com/developerworks/opensource/library/http://www.ibm.com/developerworks/forums/dw_osforums.jsphttp://www.ibm.com/developerworks/opensource/find/events/http://www.ibm.com/developerworks/newsletter/http://www.ibm.com/developerworks/training/knowledgepath/index.htmlhttp://www.ibm.com/developerworks/demos/
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    5/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    sam ple application), then click Download below the theme name. Doing so l inks to the actual download page; choose thecurrent (stable) version, which at the time of this writing was 1.7.2 for jQuery V1.3+.

    There is no installation process ; just extract the ThemeRoller file and place the correct directories/files in the right place. You'realso welcome to create your own theme if you wish, but for the sake of brevity, I used one of the pre-rolled themes .

    Back to top

    Creating your Django project

    Next, you need to create a new Django project. Use the comm and django-admin startproject pytweetproj where

    pytweetprojis the name us ed for the project throughout this article. Feel free to use another name, but be careful to use thatname consistently throughout your project. Change to the pytweetproj directory. To start the Django Web server, at the commandline, type python manage.py runserver, open a Web browser, and navigate to http://127.0.0.1:8000. You should get a page

    that says,"It worked!" If at any time you want to stop or restart the server, press Ctrl+C to kill the process . Don't use thedevelopment server for production. When you've finished development on your project, move it over to a secure production server,such as Apache.

    While in the root project directory, create a s ubdirectory called resources, which will contain your CSS file, JavaScript files, andany other media. From wherever you extracted the previously downloaded ThemeRoller file, move or copy the css and jsdirectories (extracted from the ThemeRoller ZIP file), as well as the jQuery core to the resources directories.

    With your preferred text editor, open the settings.py file and change it to match the s ettings provided in Lis ting 4.

    Listing 4. Django settings

    # Django settings for pytweetproj project.import osAPPLICATION_DIR = os.path.dirname( globals()[ '__file__' ] )

    DEBUG = TrueTEMPLATE_DEBUG = DEBUG

    ADMINS = ()

    MANAGERS = ADMINS

    # we'll use sqlite3 for cachingDATABASE_ENGINE = 'sqlite3'DATABASE_NAME = 'session.db'DATABASE_USER = ''DATABASE_PASSWORD = ''DATABASE_HOST = ''DATABASE_PORT = ''

    TIME_ZONE = 'America/Chicago'LANGUAGE_CODE = 'en-us'

    Trial software offers

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdfhttp://www.ibm.com/developerworks/aboutdw/dwa/?ca=dti-dwarphttps://www.ibm.com/developerworks/cloud/index.html?ca=dti-cloudzonehttp://www.ibm.com/developerworks/downloads/?ca=dti-tilemoreoffers
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    6/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    SITE_ID = 1

    # if you won't be using internationalization, better to keep# it false for speedUSE_I18N = False

    MEDIA_ROOT = os.path.join( APPLICATION_DIR, 'resources' )MEDIA_URL = 'http://localhost:8000/resources/'ADMIN_MEDIA_PREFIX = '/media/'

    # Make this unique, and don't share it with anybody.SECRET_KEY = '=y^moj$+yfgwy2kc7^oexnl-f6(b#rkvvhq6c-ckks9_c#$35'

    # List of callables that know how to import templates from various sources.TEMPLATE_LOADERS = (

    'django.template.loaders.filesystem.load_template_source','django.template.loaders.app_directories.load_template_source',

    # 'django.template.loaders.eggs.load_template_source',)

    MIDDLEWARE_CLASSES = ('django.middleware.common.CommonMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware',

    )

    ROOT_URLCONF = 'pytweetproj.urls'

    TEMPLATE_DIRS = (os.path.join( APPLICATION_DIR, 'templates' ),

    )

    INSTALLED_APPS = ('django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.sites',

    'twitterPanel',)

    # added for sessionsSESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'

    To get the path of the current working directory in an operating s ystem-independent m anner, use os.path.dirname(

    globals()[ '__file__' ] ) to set the application directory. You use the same method to s et the path to the resources

    directory, as well as the TEMPLATE_DIR. It's also necessary to set the MEDIA_URL to http://localhost:8000/resources/.

    You will be using sqlite3, a database included in Python. You will also need to set the DATABASE_ENGINE, DATABASE_NAME,

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdf
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    7/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    Regular expressions

    According to Wikipedia, regu lar express ions "provide a

    concise and flexible means for identifying strings of textof interest, such as particular characters, words, orpatterns of characters." If you don't have any experiencewith regular express ions, I highly recommend

    Mastering Regular Expressionsby Jeffrey Friedl orTextProcessing in Python by David Mertz. The Regular

    Expression HOWTO found at the Python documentationpage is also an excellent starting point.

    and the ROOT_URLCONF variables. Notice that INSTALLED_APPS contains a value called twitterPanel, which is n't created

    yet: You'll create that Django application next. Invoke the command python manage.py syncdb to create the sess ion

    database.

    To create the twitterPanel application, use django-admin startapp twitterPanel and type cd to change into the newly

    created module directory: twitterPanel. In the twitterPanel directory, create another directory called templates, which will containthe Django templates.

    Back to top

    Crafting your URLs

    With your favorite text editor, open the file url.py in the root of your project and change the code to match Listing 5. This file mapsURLs to callback functions.

    Listing 5. Root URL settings

    from django.conf.urls.defaults import *from django.conf import settings

    urlpatterns = patterns('',( r'^resources/(?P.*)$',

    'django.views.static.serve',{ 'document_root': settings.MEDIA_ROOT } ),( r'^twitterPanel/', include( 'twitterPanel.urls' ) ),

    )

    The first mapping in urlpatterns defines a m atch for statically

    served resources or media for example, im age files. Because youare us ing the Django development s erver, to serve your static

    content, you use the django.views.static.serve() view. The

    second mapping includes the URL patterns found in the

    twitterPanel application. Open the url.py file found under

    twitterPanel (don't confuse that url.py with the one in root) and add

    the code in Listing 6.

    Listing 6. Twitter panel URLs

    from django.conf.urls.defaults import *from twitterPanel.views import *

    urlpatterns = patterns( '',

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdf
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    8/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    url( r'^$', index, name = 'twitterPanel_index' ),url( r'^panel/$', panel, name = 'twitterPanel_panel' ),url( r'^update/$', update, name = 'twitterPanel_update' ),

    )

    Back to top

    The views

    You will create just three views: index, panel, and update. Notice that you will not add views to the root project only to the

    Twitter Panel appl ication. Open the view.py file found in the twitterPanel directory and add the imports in Lis ting 7 to the top of thefile.

    Listing 7. Twitter panel view imports

    from django.shortcuts import render_to_responsefrom django.template.context import RequestContextimport twitter

    The render_to_response() method is a Django s hortcut for rendering a template with a specific context and returns an

    HttpResponse object. The RequestContext is a Django context with a few differences from the regulardjango.template.Context. Specifically, it accepts an HttpRequest object, and it automatically populates the context with

    variables found in the TEMPLATE_CONTEXT_PROCESSORS setting.

    The first view method, index(), should look like Listing 8.

    Listing 8. The index view

    def index(request):template = 'index.html'userName = request.POST.get( 'userTxt' )

    password = request.POST.get( 'passwordTxt' )

    if userName is not None and password is not None:try:

    api = twitter.Api( username = userName, password = password)# just grab the first 5 tweetsstatuses = api.GetUserTimeline()[0:5]# limit to just the first 120following = api.GetFriends()[0:120]

    except NameError, e:print "unable to login"

    else:

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdf
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    9/20

    df d mi b PRO i Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    statuses = {}following = False

    # place values in sessionrequest.session['statuses'] = statusesrequest.session['following'] = followingrequest.session['userName'] = userNamerequest.session['password'] = password

    data = {

    'statuses' : statuses,'following' : following,

    }

    return render_to_response(template, data,context_instance = RequestContext(request))

    The template, index.html, hasn't been written yet. For the moment, just remember that you have two HTML elements: a text box forentering the user name and a pass word input. The data is s ent to the view through the POST method. If a user name and

    pass word are entered, you ins tantiate a twitter.Api object and retrieve the first five tweets of the logged-in us er, as well as the

    first 120 people you're following. The statuses, friends, user nam e, and password are all s tored in the sess ion for retrieval laterfrom other parts of the program.

    The second view method, panel(), is much shorter. It's shown in Listing 9.

    Listing 9. The panel view

    def panel(request):template = 'panel.html'data = {

    'statuses' : request.session['statuses'],'following' : request.session['following']

    }return render_to_response(template, data,

    context_instance = RequestContext(request))

    Here, you us e the panel.html template, also nonexistent as of yet. The panel is where all the action will be going on after you're

    logged in in other words, where the tweets are displayed, updates get done, and your friends are displayed. More on that in alittle bit. For the moment, all you're doing here is getting som e data from the session, then doing a render_and_response. In

    contrast, the third view method, update, is a bit m ore complex. See Listing 10.

    Listing 10. The update view

    def update(request):

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdf
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    10/20

    df di b PRO i Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    template = 'panel.html'

    userName = request.session['userName']password = request.session['password']

    try:

    api = twitter.Api( username = request.session['userName'],password = request.session['password'])

    api.PostUpdate(request.POST.get('updateTextArea'))updated = Truestatuses = api.GetUserTimeline()[0:5] # reload the statuses

    except NameError, e:

    print "unable to login"updated = False

    data = {'userName' : request.session['userName'],'password' : request.session['password'],'updated' : updated,'statuses' : statuses

    }return render_to_response(template, data,

    context_instance = RequestContext(request))

    The user name and password are taken from the sess ion, used to instantiate anothertwitter.Api object, then use the apiobject to post an update to the account. The statuses are then reloaded.

    Back to top

    The templates

    Within twitterPanel/templates, create a file called index.html and open it. Fill it with the code in Listing 11.

    Listing 11. The index template

    Sample Python-Twitter Application

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdf
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    11/20

    df di b PRO i A d l ? T t th HTML t PDF API N h t F b k Alb T PDF

    $(function(){// Dialog$('#dialog').dialog({

    autoOpen: false,width: 400,buttons: {

    "Ok": function() {$(this).dialog("close");

    $.post('{% url twitterPanel_index %}', $("#loginForm").serialize());$( '#panel' ).html( '' ).load( '{% url twitterPanel_panel %}' )

    $( '#dialog_link' ).fadeOut(1500);$( '#demoTitle' ).fadeOut(1500);

    },"Cancel": function() {

    $(this).dialog("close");}

    }});

    // Dialog Link$('#dialog_link').click(function(){

    $('#dialog').dialog('open');

    return false;});//hover states on the static widgets$('#dialog_link, ul#icons li').hover(

    function() { $(this).addClass('ui-state-hover'); },function() { $(this).removeClass('ui-state-hover'); }

    );});

    body{ font: 62.5% "Trebuchet MS", sans-serif; margin: 50px;}.demoHeaders { margin-top: 2em; }#dialog_link {padding: .4em 1em .4em 20px;

    text-decoration:none; position: relative;}#dialog_link span.ui-icon {margin: 0 5px 0 0;position: absolute;left: .2em;top: 50%;margin-top: -8px;}

    ul#icons {margin: 0; padding: 0;}ul#icons li {

    margin: 2px; position: relative; padding: 4px 0;cursor: pointer; float: left; list-style: none;}

    ul#icons span.ui-icon {float: left; margin: 0 4px;}

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdf
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    12/20

    df di b PRO i A d l ? T t th HTML t PDF API N h t F b k Alb T PDF

    PyTwitter Demo

    Start Demo

    user

    password

    Figure 2 dis plays the start of the appli cation: a jQuery UI button.

    Figure 2. jQuery UI button

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdf
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    13/20df di b PRO i

    Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    This button calls the Login window shown in Figure 3.

    Figure 3. The Login window

    Let's dissect the code in Listing 11. First, you can tell the browser where the CSS, JavaScript, and jQuery files are found using

    the {{MEDIA_URL}}. When Django renders the template, it subs titutes {{MEDIA_URL}} with the actual path.

    Inside the header, add your own JavaScript. The dollar sign ($) is an alias for a jQuery instance. A jQuery shortcut for

    document.getElementById('name') is $('#name'). For example, you define a jQuery UI element dialog using a tag,

    and then call the .dialog() method to create the jQuery window. Inside, you add two buttons: OK and Cancel. Cancel closes

    the window, whereas OK performs two actions: It closes the window, then pos ts to the s erver. If the data that the index viewreceives is the correct credentials, you get back the tweets and followers data. Then, the window button and title fade out, and the

    Twitter panel fades in.

    The magic line here is $( '#panel' ).html( '' ).load( '{% url twitterPanel_panel %}' ) , which loads the

    external Django template panel .html. The Twitter panel is a jQuery UI accordion widget. Listing 12 shows the code for the paneltemplate. Save the code into panel.html inside w ithin twitterPanel/templates.

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdf
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    14/20df di b PRO iAre you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    Listing 12. The Twitter panel template

    $(function(){

    $("#main").accordion({header: "h3",autoHeight: true

    }).hide().fadeIn(1500);

    $('#updateTextArea').keyup(function(){// text used for non-input elements. Var() is used for input elementsvar tweetLength = $('#updateTextArea').val().length;$('#charCount').text( 140 - tweetLength );

    });

    $('#updateBtn').click(function(){if($('#updateTextArea').val().length {{ s.text }}

    {% endfor %}

    {% else %}No tweets found

    {% endif %}

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdf
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    15/20df di b PRO iAre you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    Update Status

    Update

    140

    Following

    {% if following %}{% for f in following %}

    {% endfor %}

    {% else %}following variable is empty

    {% endif %}

    Figure 4 shows the Twitter panel with the Update Status tab.

    Figure 4. The Twitter panel displaying the Update Status tab

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdf
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    16/20

    Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    You name the accordion widget "main," and this is where all the action is once you're logged in. Inside the accordion, you havethree tabs: My Recent Tweets, Update Status, and Following, as shown in Figure 5.

    Figure 5. The Twitter panel, displaying the Following tab

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdf
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    17/20

    Now that you've looked at the demo, you've probably noticed how much effect the jQuery UI adds to the dynamic feel of the

  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    18/20

    pdfcrowd.comopen in browser PRO version Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    y , y p y jQ y yapplication. Django also m akes it easy to handle the Python back end and templating.

    Other things you could do to improve on the application include adding proper validation to the login process, error windows , or alist of your followers; s ending direct tweets; and searching for tweets. Of course, feel free to use your creativity, as well.

    Back to top

    Download

    Description Name Size Download method

    Sample code os-social-tw itter-pytw eetproj.zip 160KB HTTP

    Information about download methods

    Resources

    Learn

    Learn about RESTful applications.

    Check out the Twitter API documentation to learn everything you need to know about the Twitter API.

    To listen to interesting interviews and discussions for software developers, check out developerWorks podcasts.

    Stay current with developerWorks' Technical events and webcasts.

    Follow developerWorks on Twitter.

    Check out upcoming conferences, trade shows , webcasts, and otherEvents around the world that are of interest to IBMopen source developers.

    Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help youdevelop with open sou rce technologies and use them with IBM's products, as well as ourmost popular articles andtutorials.

    The My developerWorks communi ty is an example of a s uccessful general communi ty that covers a wide variety of topics.

    Watch and learn about IBM and open s ource technologies and product functions with the no-cost developerWorks Ondemand demos.

    Get products and technologies

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdfhttp://www.ibm.com/developerworks/apps/download/index.jsp?contentid=447606&filename=os-social-twitter-pytweetproj.zip&method=http&locale=http://www.ibm.com/developerworks/library/whichmethod.htmlhttp://en.wikipedia.org/wiki/Representational_State_Transferhttps://twitterapi.pbworks.com/Twitter-API-Documentationhttp://www.ibm.com/developerworks/podcast/http://www.ibm.com/developerworks/offers/techbriefings/http://twitter.com/developerworkshttp://www.ibm.com/developerworks/views/opensource/events.jsphttp://www.ibm.com/developerworks/opensourcehttp://www.ibm.com/developerworks/opensource/library/os-top10.htmlhttp://www.ibm.com/developerworks/communityhttp://www.ibm.com/developerworks/offers/lp/demos/
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    19/20

    pdfcrowd.comopen in browser PRO version Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    Submit

    p g

    Download Python, find documentation, and take the Python tutorial. Then download the python-twitterwrapper.

    Download Django,jQuery, and thejQuery UI.

    Be sure to download the simplejson dependency for the python-twitter wrapper.

    Innovate your next open source development project with IBM trial software, available for download or on DVD.

    Download IBM product evaluation versions orexplore the online trials in the IBM SOA Sandbox and get your hands on

    application development tools and m iddleware products from DB2, Lotus, Rational, Tivoli, and WebSphere.

    Discuss

    Participate in developerWorks blogs and get involved in the developerWorks community.

    About the author

    Cesar Otero is a freelance Java and Python consultant. He holds a degree in electrical engineering with a m inorin mathematics.

    Rate this article

    Average rating (7 votes)

    1 star

    2 stars

    3 stars

    4 stars

    5 stars

    Comments

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdfhttp://www.python.org/http://code.google.com/p/python-twitterhttp://www.djangoproject.com/http://jquery.com/http://jqueryui.com/http://cheeseshop.python.org/pypi/simplejsonhttp://www.ibm.com/developerworks/downloads/http://www.ibm.com/developerworks/downloads/http://www.ibm.com/developerworks/downloads/soasandbox/http://www.ibm.com/developerworks/blogs
  • 7/31/2019 Www Ibm Com Developerworks Opensource Library Os Social Twit

    20/20

    pdfcrowd.comopen in browser PRO version Are you a developer? Try out the HTML to PDF API New hot app: Facebook Albums To PDF

    Print this page Share this page Follow developerW orks

    About

    Help

    Contact us

    Submit content

    Feeds and apps

    Newsletters

    Report abuse

    Terms of use

    IBM privacy

    IBM access ibility

    Faculty

    Students

    Business Partners

    Notify me when a comm ent is added 1000 characters left

    Comments

    Add comment:

    Sign in orregisterto leave a comment.

    Note: HTML elements are not supported within comm ents.

    Post

    Be the first to add a comment

    Back to top

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.ibm.com%2fdeveloperworks%2fopensource%2flibrary%2fos-social-twitter%2findex.html&id=ma-120204120537-352e89a1http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.albumstopdf.com/?ref=pdfhttp://www.ibm.com/developerworks/aboutdw/https://www.ibm.com/developerworks/feedbackhttp://www.ibm.com/developerworks/aboutdw/contacts.htmlhttps://www.ibm.com/developerworks/ideashttp://www.ibm.com/developerworks/feeds/https://www.ibm.com/developerworks/newsletter/https://www.ibm.com/developerworks/community/report/https://www.ibm.com/developerworks/community/terms/http://www.ibm.com/privacy/http://www.ibm.com/accessibility/http://www.ibm.com/developerworks/university/academicinitiative/http://www.ibm.com/developerworks/university/students/http://www.ibm.com/isv/http://www.ibm.com/developerworks/dwwi/DWAuthRouter?m=register&lang=en&d=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fopensource%2Flibrary%2Fos-social-twitter%2Findex.html%23icomments