Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from datetime import date
- import tornado.escape
- import tornado.ioloop
- import tornado.web
- import mysql.connector
- import json
- class UseDatabase:
- def __init__(self, configuration):
- """ Initialisation code which executes the context manager
- is CREATED. """
- self.host = configuration['DB_HOST']
- self.user = configuration['DB_USER']
- self.passwd = configuration['DB_PASSWD']
- self.db = configuration['DB']
- def __enter__(self):
- """ Set-up code which executes BEFORE the body of the
- with statement. """
- self.conn = mysql.connector.connect(host=self.host,
- user=self.user,
- password=self.passwd,
- database=self.db,)
- self.cursor = self.conn.cursor()
- return(self.cursor)
- def __exit__(self, exc_type, exv_value, exc_traceback):
- """ Tear-down code with executes AFTER the body of the
- with statement.
- The three extra parameters to __exit__() contain information
- related to any exception which may have occurred while running
- the body of the with statement. """
- self.cursor.close()
- self.conn.commit()
- self.conn.close()
- config = {'DB_HOST' : 'localhost','DB_USER' : 'root' , 'DB_PASSWD' : '******', 'DB' : 'db'}
- class VersionHandler(tornado.web.RequestHandler):
- def get(self):
- response = { 'version': '3.5.1',
- 'last_build': date.today().isoformat() }
- self.write(response)
- class SignIn(tornado.web.RequestHandler):
- def get(self):
- username = self.get_argument('name')
- with UseDatabase(config) as cursor:
- SQL = '''select * from users where username = "%s" Limit 1'''% (username)
- cursor.execute(SQL)
- userData = cursor.fetchone()
- message = {}
- message["userData"] = userData
- json.dumps(message)
- self.write(message)
- def post(self):
- username = self.get_argument('name')
- password = self.get_argument('password')
- with UseDatabase(config) as cursor:
- SQL = '''INSERT INTO users (username , password) VALUES ( "%s" , "%s")'''% (username,password)
- cursor.execute(SQL)
- response = "{ 'create user with name : '" + username + " and password : " + password + "}"
- self.write(response)
- application = tornado.web.Application([
- (r"/signin", SignIn),
- (r"/version", VersionHandler)
- ])
- if __name__ == "__main__":
- application.listen(443)
- tornado.ioloop.IOLoop.instance().start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement