03 Oct 2011

web.py and nginx!

Tags: nginx, python, bash, webpy

I have worked with web.py before, but I have never really used it to create anything useful, lately though, I have been working on some small projects like the ones you can find under projects.

web.py is so nice and simple, so instead of implementing my small side-projects inside django, I can just make them completely independent.

It is really simple to setup and start using, and when you're done it's easy as pie to get working with a fastcgi parser and nginx too.
There is a neat little guide here for that: Webpy + Nginx with FastCGI

Now, to manage my projects (start/stop, and deploy new ones) I have just today created a small bash script to make this easier for me, which looks as follows:

spawn.sh
 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/bin/bash

projects=(
  /home/ole/Projects/webpy/i.ole.im      9002
  /home/ole/Projects/webpy/whois         9003
)

# Start the services
start(){

  for (( i=0; i<${#projects[@]}; i++ ))
  do
    spawn-fcgi -d ${projects[$i]} -f ${projects[$i]}/main.py -a 127.0.0.1 -p ${projects[$i+1]}
    i=$i+1
  done
}

# Stop the services
stop(){
  for (( i=0; i<${#projects[@]}; i++ ))
  do
    CPID=$(pgrep -f "python ${projects[$i]}/main.py") # current process id
    if [ "$CPID" != "" ]
      then
      kill $CPID
    fi
    i=$i+1
  done
}

# Main program
case "$1" in
  start)
    start
    echo "Started services"
    ;;
  stop)
    stop
    echo "Stopped services"
    ;;
  restart|reload)
    stop
    start
    echo "Restarted services"
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|reload}"
    exit 1
esac
exit 0

In all my projects I use main.py as the "main file", so I don't need to define this, I just put in the projects folder, and the port it should run on, and then I can control the projects, start/restart and stop them, easily.