Render molecule as SVG via Flask.

I posted topics about rdkitjs before.
The library can render molecule as SVG format. It was very useful for me.
But, sometime I write webapp using python. So I want to draw molecule from python.
There are a lots of web framework in python and my favorite is “Flask”. ;-)
So, I tested render molecule as SVG from python using Flask.
At first, I coded that is base app.
Sample code is following.
This web app will render molecule if user access the url ‘localhost:5000/’.

from __future__ import print_function
from flask import Flask
from flask import render_template
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import rdDepictor
from rdkit.Chem.Draw import rdMolDraw2D
from HTMLParser import HTMLParser

def smitosvg( smi, molSize=( 400,200 ) ):
    mol = Chem.MolFromSmiles( smi )
    mc = Chem.Mol( mol.ToBinary() )
    if not mc.GetNumConformers():
        rdDepictor.Compute2DCoords( mc )
    drawer = rdMolDraw2D.MolDraw2DSVG( molSize[0], molSize[1] )
    opts = drawer.drawOptions()
    drawer.DrawMolecule( mc )
    svg = drawer.GetDrawingText()
    svg = svg.replace('svg:','')
    return svg

app = Flask(__name__)
@app.route( '/top/<smi>'  )
def top( smi ):
    return render_template( '/top.html', svg = smitosvg( smi  ), smi =smi  )

if __name__ == '__main__': debug=True )

And I wrote top.html in templates folder.
It’s manner of Flask.

	<title>render smi</title>
	<h1>Render Smiles</h1> 
	{{ svg|safe }} </br>
        This is your query &nbsp&nbsp  {{ smi }}

The argument of “|safe” is important to escape html tag.

OK! Just do it!
Run the app and access sample url.

$ python

Then access “;

I got following image.
Screen Shot 2015-08-16 at 10.22.28 PM

Work fine.
It’s very simple stuff. I’ll make more advanced app ASAP. ;-)


Published by iwatobipen

I'm medicinal chemist in mid size of pharmaceutical company. I love chemoinfo, cording, organic synthesis, my family.

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: