Tuesday, June 19, 2012

Python web programming using web.py

For the first time in a long while, I had the opportunity to have a free day. So what did I do with it? I coded of course.

I started exploring how to do web programming with Python and stumbled on web.py. At first it didn't seem very trivial but the more I tinkered around with the sample codes, the more I got interested.

So I wrote some code that prints the reverse complement of the a DNA sequence.
import web
from web import form
import re

render = web.template.render('templates/')

urls = ('/revcom', 'index')
app = web.application(urls, globals())

myform = form.Form( 
    form.Textbox('Sequence',
                 form.notnull,
                 form.Validator('Must be a G,A,T or C', lambda x: re.match('^[gatcGATC\s]+$', x) )
                 ,size=30)
    )

def revcom(seq):
    from Bio.Seq import Seq
    from Bio.Alphabet import IUPAC

    seq = str(seq).replace(' ', '')
    myseq = Seq(str(seq), IUPAC.unambiguous_dna)
    return str(myseq.reverse_complement())

class index: 
    def GET(self): 
        form = myform()
        return render.formtest(form)

    def POST(self): 
        form = myform() 
        if not form.validates(): 
            return render.formtest(form)
        else:
            return revcom(form['Sequence'].value)

if __name__=="__main__":
    web.internalerror = web.debugerror
    app.run()

Seems to be running OK. I hope I have time to follow on this. 

No comments:

Post a Comment