How To: Install and Use Twython (Python Wrapper for Twitter API)

As promised in my previous post, here is a brief howto on getting started with twython. The main advantage of Twython over several other python (or any other language) wrappers for Twitter API is that it works even when you are behind your organizations proxy.

Download Twython

You can download latest version of twython from twython page on github. You can either clone using git (if you have git installed) or can click the download button.

Install Twython

Once you are done with extracting the downloaded tar file. Change directory to twython and run these command as root.

1
2
3
4
5
6
[root@fedora ~]$ git clone git://github.com/ryanmcgrath/twython.git
[root@fedora ~]$ cd twython/dist
[root@fedora dist]$ tar -xvzf twython-0.8.tar.gz
[root@fedora dist]$ cd twython-0.8/
[root@fedora dist]$ python setup.py build
[root@fedora dist]$ python setup.py install

Use Twython from Python Interpreter

Below is a direct copy paste lines from my interpreter. See how things are working (learning by doing).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
[saini@bordeaux ~]$ python
Python 2.6 (r26:66714, Mar 17 2009, 11:44:21) 
[GCC 4.4.0 20090313 (Red Hat 4.4.0-0.26)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> # first of all, import twython module
>>> import twython
>>> # Authenticate your twitter account with your twitter username
... # and password with twitter.setup method.
>>> client = twython.setup('Basic','myusername','mypassword')
>>> client.authenticated
True
>>> #Lets update our current status on twitter with some cool message.
>>> client.updateStatus('Testing #twython. The coolest #TwitterAPI :)')
>>> # Now go and check your current status on twitter. Surprised!!!
>>> # Get your or anyone's followers
>>> client.getFollowersIDs(screen_name='gofedora')
>>> # Output truncated.
>>> # Get help for any function.
>>> print client.createFriendship.__doc__
createFriendship(id = None, user_id = None, screen_name = None, follow = "false")
 
	Allows the authenticating users to follow the user specified in the ID parameter.
	Returns the befriended user in the requested format when successful. Returns a
	string describing the failure condition when unsuccessful. If you are already
	friends with the user an HTTP 403 will be returned.
 
	Parameters:
		** Note: One of the following is required. (id, user_id, screen_name)
		id - Required. The ID or screen name of the user to befriend.
		user_id - Required. Specfies the ID of the user to befriend. Helpful for disambiguating when a valid user ID is also a valid screen name. 
		screen_name - Required. Specfies the screen name of the user to befriend. Helpful for disambiguating when a valid screen name is also a user ID. 
		follow - Optional. Enable notifications for the target user in addition to becoming friends. 
>>>

So now you are ready to do wonders with twython. Write your own code and blog/brag about it 🙂

 

I Love Twitter, I Love Python = I Love Twython

I was really late to join Twitter. As soon as I joined Twitter, I started exploring various aspects of Twitter and hence the Twitter API. While searching for a wrapper for Twitter API in python, I came across python-twitter which was good and tweepy which was ok and I finally found twython. Twython is awesome and more importantly upto date with Twitter API.

While I was using twython, I found one fact very irritating. It didn’t have docstrings. And I had to go to Twitter API Wiki for description of every single function 🙁 I talked to Ryan (Twython developer, who works all day long at his day job with webs.com and develops twython when everybody sleeps 😛 ) about the same and offered to write docstrings for twython.

I spent a few hours and sent a patch with docstrings for all the functions. Now twython has complete documentation. Also Ryan is trying his best to implement wrappers for the newly introduced functions in Twitter API. So, currently Twython is THE best wrapper available in python for Twitter API.

PS : Next post will be “How to use twython”.

 

How To: Boot Fedora Faster

Note: These tricks apply to any Linux based OS. But I have tested them only on Fedora, so can’t say whether they’ll work on other Linux(s).

My current Fedora installation is now almost one and a half years old. Yes. I am still using Fedora 7 😀 I have Fedora 10 on my other machine. Coming to the agenda, my Fedora installation has grown beyond control and I have services from named, squid, drbl, privoxy, vsftpd, vbox*, smb and what not on a personal desktop. These services really force my system startup to slow down to more than two minutes. While shutting down, its very easy to just cut the power supply but while booting up I can’t help and it frustrates me. And what frustrates me further that I have 4GB DDR2 RAM and AMD64 X2 5600+ (2.8GHz x 2) and booting time is still more than two minutes.

Agenda

  • Boot Fedora faster using whatever techniques possible.

Remove the services from normal order and delay their execution to a later stage. So, services like network, squid, privoxy, named, vsftpd, smb etc. doesn’t make sense unless I am not logged in and using them. Let us start them after we have login screen.

Turn off all the services by using the command

[root@bordeaux ~]# chkconfig service_name off

where service_name is the service you want to turn off.

Now create a file /etc/startup.sh. Enter a line like this

[root@bordeaux ~]# service service_name start

for every service that you have turned off in the Step 1.1 and you want it to be running after your machine starts up. Now, your startup.sh file should look like this

service network start &
service sshd start &
modprobe it87 &
modprobe k8temp &
/usr/bin/iptraf -s eth0 -B &
/usr/bin/iptraf -s lo -B &
service squid start &
service privoxy start &
service httpd start &
service mysqld start &
service named start &
service smb start &
service vboxdrv start &
service vboxnet start &
service vsftpd start &

Add the following line to /etc/rc.local file

/bin/bash /etc/startup.sh &

Done!!! Notice the &s in both files. They are for execution in background so that a process can block boot process. You’ll observe a drop of 10-20 seconds in system startup time.

Problem with Hack #1 : The execution is not really parallel. It executes like a process in the background. So we can’t get the real advantage of parallel execution.

Hack #2 solves this problem. Now we don’t put processes in background. We use daemon forking to fork a separate daemon process which will start all the services for us in parallel. Here we’ll get the real advantage and startup time will decrease further.

This step is totally similar to Step 1.1. So skipping it.

This step is also similar to Step 1.2. The /etc/startup.sh file should look like this.

service network start
service xinetd start
service crond start
service anacron start
service atd start
service sshd start
service rpcbind start
service rpcgssd start
service rpcimapd start
modprobe it87
modprobe k8temp
/usr/bin/iptraf -s eth0 -B
/usr/bin/iptraf -s lo -B
service nasd start
service squid start
service privoxy start
service httpd start
service iptables start
service lm_sensors start
service mysqld start
service named start
service nfs start
service nfslock start
service smb start
service vboxdrv start
service vboxnet start
service vsftpd start
service autofs start
service smartd start

Notice the absence of &s in the file.

Download the attached startup.py file attached at the end of this post or copy paste the following code to /etc/startup.py file.

#!/usr/bin/env python
# (C) Copyright 2008 Kulbir Saini
# License : GPL
import os
import sys
def fork_daemon(f):
    """This function forks a daemon."""
    # Perform double fork
    r = ''
    if os.fork(): # Parent
        # Wait for the child so that it doesn't defunct
        os.wait()
        # Return a function
        return  lambda *x, **kw: r
    # Otherwise, we are the child
    # Perform second fork
    os.setsid()
    os.umask(077)
    os.chdir('/')
    if os.fork():
        os._exit(0)
    def wrapper(*args, **kwargs):
        """Wrapper function to be returned from generator.
        Executes the function bound to the generator and then
        exits the process"""
        f(*args, **kwargs)
        os._exit(0)
    return wrapper
 
def start_services(startup_file):
    command = '/bin/bash ' + startup_file + ' > /dev/null 2> /dev/null '
    os.system(command)
    return
 
if __name__ == '__main__':
    forkd = fork_daemon(start_services)
    forkd(sys.argv[1])
    print 'Executing ', sys.argv[1], '[  OK  ]'

Add the following line to your /etc/rc.local file.

/usr/bin/python /etc/startup.py /etc/startup.sh

Thats it. Done!!! Now you’ll experience a boost of about 25-30 seconds of decrease in boot time.

Stats of my machine

With all services started in normal order : 2minutes.
With Hack #1 : 1minute 42 seconds.
With Hack #2 : 1minute.

Warning : These hacks may break your system and can make it unusable. Use at your own risk.

 

How To: Write Custom Redirector or Rewritor Plugin For Squid in Python

Mission

To write a custom Python program which can act as a plugin for Squid to redirect a given URL to another URL. This is useful when already existing redirector plugins for Squid doesn’t suit your needs or you want everything of your own.

Use Cases

  1. When you want to redirect URLs using a database like mysql or postgresql.
  2. When you want to redirect based on mappings stored in simple text files.
  3. When you want to build a redirector which can learn by itself using AI techniques 😛

How to proceed

From Squid FAQ,

The redirector program must read URLs (one per line) on standard input, and write rewritten URLs or blank lines on standard output. Note that the redirector program can not use buffered I/O. Squid writes additional information after the URL which a redirector can use to make a decision.

The format of the line read from the standard input by the program is as follows.

1
2
3
URL ip-address/fqdn ident method
# for example
http://saini.co.in 172.17.8.175/saini.co.in - GET -

The implementation sounds very simple and it is indeed very simple to implement. The only thing that should be taken care of is the unbuffered I/O. You should immediately flush the output to standard output once decision is taken.

For this howto, we assume we have a method called ‘modify_url()‘ which returns either a blank line or a modified URL to which the client should be redirected.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/usr/bin/env python
 
import sys
def modify_url(line):
    list = line.split(' ')
    # first element of the list is the URL
    old_url = list[0]
    new_url = '\n'
    # take the decision and modify the url if needed
    # do remember that the new_url should contain a '\n' at the end.
    if old_url.endswith('.avi'):
        new_url = 'http://fedora.co.in/errors/accessDenied.html' + new_url
    return new_url
 
while True:
    # the format of the line read from stdin is
    # URL ip-address/fqdn ident method
    # for example
    # http://saini.co.in 172.17.8.175/saini.co.in - GET -
    line = sys.stdin.readline().strip()
    # new_url is a simple URL only
    # for example
    # http://fedora.co.in
    new_url = modify_url(line)
    sys.stdout.write(new_url)
    sys.stdout.flush()

Save the above file somewhere. We save this example file in /etc/squid/custom_redirect.py. Now, we have the function for redirecting clients. We need to configure squid to use custom_redirect.py . Below is the squid configuration for telling squid to use the above program as redirector.

1
2
3
4
5
6
# Add these lines to /etc/squid/squid.conf file.
# /usr/bin/python should be replaced by the path to python executable if you installed it somewhere else.
redirect_program /usr/bin/python /etc/squid/custom_redirect.py
# Number of instances of the above program that should run concurrently.
# 5 is good enough but you should go for 10 at least. Anything below 5 would not work properly.
redirect_children 5

Now, start/reload/restart squid. That’s all we need to write and use a custom redirector plugin for squid.

 

How To: Write Custom Basic Authentication Plugin for Squid in Python

Mission

To write a Python program which can be used to authenticate for Squid proxy server. This is useful when you don’t want to configure complex systems like LDAP, ntlm etc.

Use Cases

  1. When you want to authenticate clients using mysql database.
  2. When you want to authenticate clients using flat files or /etc/passwd file or some custom service on your network.

How to proceed

From auth_param section in squid.conf file:

Specify the command for the external authenticator. Such a program reads a line containing "username password" and replies "OK" or "ERR" in an endless loop. "ERR" responses may optionally be followed by a error description available as %m in the returned error page.

By default, the basic authentication scheme is not used unless a program is specified.

That clearly states that our python program should read a line from standard input (stdin) and write the appropriate response to the standard output (stdout). But there are some issues with I/O. The output should be unbuffered and should be flushed to standard output immediately after the response is known.

So, lets see a small program where we authenticate using a function ‘matchpassword()‘. This function returns True when username, password pair matches and returns False when they mismatch.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/python
 
import sys
import socket
"""USAGE:The function returns True if the user and passwd match False otherwise"""
def matchpasswd(login,passwd):
    # Write your own function definition. 
    # Use mysql, files, /etc/passwd or some service or whatever you want
    pass
 
while True:
    # read a line from stdin
    line = sys.stdin.readline()
    # remove '\n' from line
    line = line.strip()
    # extract username and password from line
    username = line[:line.find(' ')]
    password = line[line.find(' ')+1:]
 
    if matchpasswd(username, password):
        sys.stdout.write('OK\n')
    else:
        sys.stdout.write('ERR\n')
    # Flush the output to stdout.
    sys.stdout.flush()

Save the above file somewhere. We save this example file in /etc/squid/custom_auth.py .Now, we have the function for authenticating clients. We need to configure squid to use custom_auth.py . Below is the squid configuration for telling squid to use the above program as basic authenticator.

1
2
3
4
5
6
7
8
9
10
11
# you need to specify /usr/bin/python if your file is not executable and needs an interpreter to be invoked.
# Replace /usr/bin/python with /usr/bin/php , if you write auth program in php.
auth_param basic program /usr/bin/python /etc/squid/custom_auth.py
# how many instances of the above program should run concurrently
auth_param basic children 5
# display some message to clients when they are asked for username, password
auth_param basic realm Please enter your proxy server username and password
# for how much time the authentication should be valid
auth_param basic credentialsttl 2 hours
# whether username, password should be case sensitive or not
auth_param basic casesensitive on

Now, to force clients to authenticate, configure the acls as follow. Below we assume, you want to force all clients on your lan to authenticate for using proxy server.

1
2
3
4
5
6
# acl to force proxy authentication
acl authenticated proxy_auth REQUIRED
# acl to define IPs from your lan
acl lan src 192.168.0.0/16
# acl to force clients on your lan to authenticate
http_access allow lan authenticated

Now, reload/restart squid. That’s all we need to write and use a custom authentication plugin for squid.

Limitation

Username can’t contain spaces. Otherwise program will not be able to parse/extract username, password from standard input.