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 app.py 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 ) print(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 ) drawer.FinishDrawing() 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__': app.run( debug=True )
And I wrote top.html in templates folder.
It’s manner of Flask.
<!DOCTYPE=HTML> <html> <head> <title>render smi</title> </head > <body> <h1>Render Smiles</h1> {{ svg|safe }} </br> This is your query    {{ smi }} </body> </html>
The argument of “|safe” is important to escape html tag.
OK! Just do it!
Run the app and access sample url.
$ python app.py
Then access “http://127.0.0.1:5000/top/Fc1cc(c(F)cc1F)C%5BC@@H%5D(N)CC(=O)N3Cc2nnc(n2CC3)C(F)(F)F”
Work fine.
It’s very simple stuff. I’ll make more advanced app ASAP. ;-)