Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Tornado - SQLite DB
<html>
<title>
SQLite Example
</title>
<body>
<FORM ACTION="/create" METHOD=POST>
Name: <input type="text" name="name">
Marks: <input type="text" name="marks">
<input type="submit" value="Add" name="Submit"/>
</FORM>
</body>
</html>
<html>
<title>
Success
</title>
<body>
Record added successfully!!
<br /><br />
<FORM action="/show" METHOD="GET">
<input type="submit" value="Show Records" name="Submit"/>
</FORM>
</body>
</html>
import tornado.ioloop
import tornado.web
import tornado.database
import sqlite3
def _execute(query):
dbPath = '/home/ubuntu/tornado-2.2/db'
connection = sqlite3.connect(dbPath)
cursorobj = connection.cursor()
try:
cursorobj.execute(query)
result = cursorobj.fetchall()
connection.commit()
except Exception:
raise
connection.close()
return result
class Main(tornado.web.RequestHandler):
def get(self):
self.write("Main")
class AddStudent(tornado.web.RequestHandler):
def get(self):
self.render('sqliteform.html')
def post(self):
marks = int(self.get_argument("marks"))
name = self.get_argument("name")
query = ''' insert into stud (name, marks) values ('%s', %d) ''' %(name, marks);
_execute(query)
self.render('success.html')
class ShowStudents(tornado.web.RequestHandler):
def get(self):
query = ''' select * from stud'''
rows = _execute(query)
self._processresponse(rows)
def _processresponse(self,rows):
self.write("<b>Records</b> <br /><br />")
for row in rows:
self.write(str(row[0]) + " " + str(row[1]) + " " + str(row[2]) +" <br />" )
application = tornado.web.Application([
(r"/", Main),
(r"/create" ,AddStudent),
(r"/show",ShowStudents),
],debug=True)
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment