rdkit and flask

Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions.
I interested in flask to build web app. with RDKit.
I’m reading document and some books about flask.
Today I wrote some code to handle sdf.
At first, I made app folder.

 iwatobipen$ tree
.
├── myapp.py
├── requirements.txt
├── static
│   └── tmp_img
├── templates
│   └── base.html
└── tmp
    └── 

myapp.py will,,,,

1) User attached sdf will be stored the tmp holder.
2) Read SDF and save png image of each molecule to static/tmp_img.
3) Then return image and smiles to user.

myapp.py

import os
from flask import Flask
from flask import request, redirect, url_for
from werkzeug import secure_filename
from flask import render_template

from rdkit import Chem
from rdkit.Chem import Draw

app = Flask(__name__)

FILE_FOLDER='./tmp'

@app.route('/upload/', methods=['GET','POST'])
def upload_file():
    if request.method == 'POST':
        filestrage = request.files['file']
        filename = secure_filename(filestrage.filename)
        dest = os.path.join(FILE_FOLDER, filename)
        filestrage.save( dest )
        smiles = [Chem.MolToSmiles(mol) for mol in Chem.SDMolSupplier("./tmp/%s"%filename)]
        mols = [ mol for mol in Chem.SDMolSupplier("./tmp/%s"%filename)  ]
        for i in range( len(mols) ):
            Draw.MolToImageFile(mols[i], "./static/tmp_img/%s.png"%i)
        files = ["/static/tmp_img/%s.png"%i for i in range( len( mols )) ]
        res = dict(zip(smiles,files))

        return render_template("base.html",res=res)
        #return redirect(url_for('upload_file'))
    return '''
           <!doctype html>
           <title>Up loader</title>
           <h1>Up load new File</h1>
           <form action="" method=post enctype=multipart/form-data>
               <p><input type=file name=file>
                  <input type=submit value=Upload></p>
            </form>
            '''
if __name__ == '__main__':
    app.run(debug=True)

And use template
base.html

<!doctype html>
<html>
<head>
	
	<title>test site</title>
	<h1>test1</h1>
</head>
<body>
	<table border="1">
		<th>smiles</th>
		{% for key,val in res.items()  %}
		<tr><td>{{ key }}</td><td><img src={{ val }}  width="500" height="500" alt={{ key }} /></td></tr>
		{% endfor  %}
	</table>
</body>
<a href="http://127.0.0.1:5000/upload">back_to_uploader</a>
</html>

Maybe work, but a little bit slow response… ;-(
I will build some apps for medicinal chemist.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s