Skip to content

Instantly share code, notes, and snippets.

@mmmunk
Created September 22, 2016 05:57
Embed
What would you like to do?
Demo of web-app using Python, Tornado and MySQL
import time
import tornado.ioloop
import tornado.web
import pymysql
# HTML templates
html_begin = '''<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Order-Web</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
body {font-family: sans-serif; font-size: 100%%;}
form {padding: 1em 0;}
table {border-collapse: collapse;}
table,td,th {border: 1px solid green;}
th {background-color: green; color: white;}
td {padding: 0.2em 0.5em;}
tr:nth-child(even) {background-color: lightgreen;}
</style>
</head>
<body>
<form action="." method="get">
Show orders, from <input name="fromdate" type="date" value="%s">
to <input name="todate" type="date" value="%s">
<button type="submit">Search</button>
</form>\n'''
table_begin = '<table>\n<tr><th>Ordrenummer</th><th>Kundenummer</th><th>Kundenavn</th><th>Dato</th></tr>\n'
table_row = '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n'
table_end = '</table>'
html_end = '</body></html>'
# Page
class PageHandler(tornado.web.RequestHandler):
def get(self):
# Parameters
fromdate = self.get_argument('fromdate', None)
todate = self.get_argument('todate', None)
if not fromdate or not todate:
fromdate = time.strftime('%Y-%m-%d')
todate = fromdate
# HTML begin
self.write(html_begin % (fromdate, todate))
# SQL
connection = pymysql.connect(host='demo-server', port=3306, user='test', passwd='test', db='systemt')
cursor = connection.cursor()
cursor.execute('SELECT Nummer,KundeNr,KundeNavn,Dato FROM ordre WHERE Dato >= "%s" and Dato <= "%s" ORDER BY Dato,Nummer' % (fromdate, todate))
self.write(table_begin)
for row in cursor:
self.write(table_row % (row[0], row[1], row[2], row[3]))
self.write(table_end)
cursor.close()
connection.close()
# HTML end
self.write(html_end)
# Main
application = tornado.web.Application(
[(r'/', PageHandler)]
)
application.listen(8888)
tornado.ioloop.IOLoop.current().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment