Tuesday, January 17, 2012

Web Services in Python (Part 2) - Serving Static Files

The last Python web server wasn't that great - it only gives you a hello world. If you're smart, you may have already figured out how to do Comet with it with very little code - we'll go over that in the next post. But.. the server doesn't even serve JavaScript files yet!

Well, don't panic. In the land of Python, everything is just a few lines of code away.

I'll assume you already have the systems libraries from my last blog post installed from this point on. If you haven't.. here's the list of things you need to install into your Linux system.
# apt-get install libevent-2.0 libevent-dev python-dev python-virtualenv
So that's 1 line of code to set up the environment - if you haven't done it already.

Next, we'll setup the sandbox for the web server - it's not absolutely needed but it's good practice to sandbox web applications with virtualenv in Python. We'll also enter the sandbox to work inside it.
$ virtualenv myapp
$ cd myapp
$ . bin/activate
3 lines of code to initialize and enter the virtualenv sandbox - not absolutely required, but good for library hygiene.

Next, we'll install a few things to our sandbox.
$ pip install gevent gunicorn pyramid
If you've got the system libraries installed correctly, it should be fully automatic - it won't even ask you a single Y/N question.

Finally, we conjure up a web server and start it.
$ pcreate -s starter myapp
$ python myapp/setup.py install
$ gunicorn_paster -w8 -kgevent --keep-alive 60 myapp/production.ini
And... and... RUMBLE... It's alive!!! (gunicorn_paster listens on 0.0.0.0:6543 by default)


Look Ma! Zero lines of Python! And it's working already!

Looking under the hood - inside the myapp/myapp/static directory of the sandbox...

martin_kou@asgard:~/Development/pyramid/myapp$ ls -al myapp/static/
total 84K
drwxrwxr-x 2 martin_kou martin_kou 4.0K 2012-01-17 00:25 .
drwxrwxr-x 4 martin_kou martin_kou 4.0K 2012-01-17 00:28 ..
-rw-rw-r-- 1 martin_kou martin_kou 1.4K 2012-01-17 00:25 favicon.ico
-rw-rw-r-- 1 martin_kou martin_kou  333 2012-01-17 00:25 footerbg.png
-rw-rw-r-- 1 martin_kou martin_kou  203 2012-01-17 00:25 headerbg.png
-rw-rw-r-- 1 martin_kou martin_kou  758 2012-01-17 00:25 ie6.css
-rw-rw-r-- 1 martin_kou martin_kou 2.8K 2012-01-17 00:25 middlebg.png
-rw-rw-r-- 1 martin_kou martin_kou 4.3K 2012-01-17 00:25 pylons.css
-rw-rw-r-- 1 martin_kou martin_kou  33K 2012-01-17 00:25 pyramid.png
-rw-rw-r-- 1 martin_kou martin_kou 6.9K 2012-01-17 00:25 pyramid-small.png
-rw-rw-r-- 1 martin_kou martin_kou   49 2012-01-17 00:25 transparent.gif
.. and that's where you can put up your favorite JavaScript, CSS and HTML files. Have fun!

No comments: