Tips: 本文创建于2016年8月19日,已超过 2 年,内容或图片可能已经失效!

tornado 操作数据库

基本操作举例

main.py

#!/usr/bin/evn python  
# coding:utf-8  
from tornado import httpserver, ioloop, web  
from tornado.options import define, options  
import torndb  
import tornado.options  
from handlers import HANDLERS, TEMPLATE_PATH  
  
define("port",default=9000, help="run on the given server", type=int)  
define("mysql_host", default="192.168.126.128:3306", help="db host")  
define("mysql_database", default="pydb", help="db name")  
define("mysql_user", default="lhh", help="dbuser")  
define("mysql_password", default="liuhonghe", help="dbpasswd")  
  
class Application(web.Application):  
    def __init__(self):  
        handlers = HANDLERS  
        settings = dict(  
            template_path = TEMPLATE_PATH,  
            xsrf_cookies  = False, #防止跨站攻击  
            # print base64.b64encode(uuid.uuid4().bytes+uuid.uuid4().bytes)  
            cookie_secret = "z0PsF2IhRIa/auHqcaaCrEDwJU7y70vbhXLcehnvu/s=",  
        )  
        web.Application.__init__(self, handlers, **settings)  
        self.db = torndb.Connection(  
            host = options.mysql_host, database = options.mysql_database,  
            user = options.mysql_user, password = options.mysql_password  
        )  
if __name__ == "__main__":  
    tornado.options.parse_command_line()  
    http_server = httpserver.HTTPServer(Application())  
    http_server.listen(options.port)  
    ioloop.IOLoop.instance().start()  

handlers

#!/usr/bin/env python  
# coding=utf-8  
from views import *  
import os.path  
  
TEMPLATE_PATH = os.path.join(os.path.dirname(__file__),"templates")  
  
HANDLERS = [(r'/',IndexHandler),(r'/poem',PoemPageHandler)]  
  
HANDLERS += [(r'/show',ShowHandler)] 

views.py

#!/usr/bin/env python  
# coding=utf-8  
import tornado.web  
import tornado.gen  
  
class BaseHandler(tornado.web.RequestHandler):  
    @property  
    def db(self):  
        return self.application.db  
  
    def get_one_poem(self, ids):  
        return self.db.get("select * from authors where id=%d",int(ids))  
  
    def get_all(self):  
        return self.db.query("select * from authors")  
  
class IndexHandler(BaseHandler):  
    def get(self):  
        self.render('index.html')  
  
class PoemPageHandler(BaseHandler):  
    def post(self):  
        noun1 = self.get_argument("noun1")  
        noun2 = self.get_argument("noun2")  
        noun3 = self.get_argument("noun3")  
        verb = self.get_argument('verb')  
  
        self.db.execute('insert into authors (email,name) values(%s,%s)', noun1,noun2)  
        ret = self.db.get('select * from authors where email=%s',noun1)  
        self.render('poem.html',roads=noun1,wood=noun2,mode=verb,difference=noun3,id=ret['id'])  
class ShowHandler(BaseHandler):  
    def get(self):  
        ids = self.get_argument('id',1)  
        ret = self.get_one_poem(ids)  
        if not ret:  
            raise tornado.web.HTTPError(404)  
        self.render('show.html',title=ret['email'],update=ret['name'])  

templates/index.html

<!DOCTYPE html>  
<html>  
 <head><title>index</title></head>  
 <body>  
  <form method="post" action="/content">  
   <p>N1<br /><input type="text" name="n1"></p>  
   <p>N2<br /><input type="text" name="n2"></p>  
   <p>N3<br /><input type="text" name="n3"></p>  
   <p>N4<br /><input type="text" name="n4"></p>  
   <input type="submit">  
  </form>  
 </body>  
</html> 

templates/poem.html

<!DOCTYPE html>  
<html>  
    <head><title>Peom PRO</title></head>  
    <body>  
        <h1><a href="/show?id={{id}}">Your peom</a></h1>  
    <p> Two {{roads}} driverged in a {{wood}}, and I-<br />  
    I took the one less travelled by, <br />  
        And that has {{mode}} all the {{difference}}.  
    </p>  
    </body>  
</html>

templates/show.html

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>show</title>  
</head>  
<body>  
<h1>Your poem</h1>  
<p>{{title}}</p>  
<p>{{update}}</p>  
</body>  
</html>