SAE Tornado 应用连接并使用 Mysql

今天因为要提供几个开放的接口给我毕设相关的平台调用,所以又开始折腾之前在SAE上搭的Tornado应用。

之前记录过一个 如何在 SAE 上使用 Tornado,这次续上,关于在SAE里使用Tornado框架时基本的MySQL操作。因为自己刚才找了很久资料才用起来,也怪自己之前没在Tornado里面用过MySQL,所以为其他同学以后少走弯路来一个整理贴。


首先在应用控制台初始化共享型MySQL

  • 点击管理MySQL可以进入管理后台,标准的PHPMyAdmin

根据 SAE官方文档 底部介绍,你可以通过以下方法获得连接数据库所需的参数。

import sae.const

sae.const.MYSQL_DB      # 数据库名
sae.const.MYSQL_USER    # 用户名
sae.const.MYSQL_PASS    # 密码
sae.const.MYSQL_HOST    # 主库域名(可读写)
sae.const.MYSQL_PORT    # 端口,类型为,请根据框架要求自行转换为int
sae.const.MYSQL_HOST_S  # 从库域名(只读)

注意:需要将sae.const.MYSQL_PORT转成int型

SAE Python内置了MySQLdb模块,用法如下:

1 导入sae常量和MySQLdb模块:

import sae.const
import MySQLdb

2 连接数据库:

db=MySQLdb.connect(host=sae.const.MYSQL_HOST,port=int(sae.const.MYSQL_PORT ),user=sae.const.MYSQL_USER ,passwd=sae.const.MYSQL_PASS ,db=sae.const.MYSQL_DB)

3 获取cursor对象,用于执行命令:

cursor = db.cursor() #默认类型,返回结果如:(u'ccc', 33L)
cursor = db.cursor(cursorclass=MySQLdb.cursors.DictCursor) #返回字典形式,如:{'name': u'ccc', 'created': 33L}

4 执行SQL语句:

cursor.execute(“select * from table_name where what = ‘what’”) #模拟数据: [{‘name’: ’chengkang’, ‘gender’: ‘male’},{‘name’: ’xiaoli’, ‘gender’: ’female’}]

5 输出返回结果:

result = cursor.fetchone()
if result is None:
        print “None”
else:
        print “%s”%result #{‘name’: ’chengkang’, ‘gender’: ‘male’}
        print result[‘name’] #chengkang
        result = cursor.fetchall()
        for row in result:
                print “%s”%row #{‘name’: ’chengkang’, ‘gender’: ‘male’}
                    for col in row:
                        print “%s”%col #chengkangmale     

以上是最基本的使用。反正我暂时就用到这些:)。一些细节的问题之后再来吧。

参考了这个博客


下面附上我自己试验时候的代码,可能会有一些参考价值。


class TestHandler(tornado.web.RequestHandler):
    def get(self):
        premise = self.get_argument('premise', "no_data")
        consequence = self.get_argument('consequence', "no_data")
        
        try:
            import sae.const
            import MySQLdb
            try:
                db=MySQLdb.connect(host=sae.const.MYSQL_HOST,port=int(sae.const.MYSQL_PORT ),user=sae.const.MYSQL_USER ,passwd=sae.const.MYSQL_PASS ,db=sae.const.MYSQL_DB)
                cursor = db.cursor(cursorclass=MySQLdb.cursors.DictCursor)
                #cursor = db.cursor()
                try:
                    cursor.execute("SELECT * FROM immediate_consequences")
                    one = cursor.fetchall()
                    #cursor.execute("SELECT * FROM immediate_consequences WHERE premise='"+premise+"' and consequence='"+consequence+"'")
                    #one = cursor.fetchone()
                    a = ""
                    #for row in cursor.fetchall():
                    #   for item in row:
                    #      a += item
                    if one is None:
                        self.write("Not in the database")
                    else:
                        #self.write(one['premise']+one['consequence'])
                        for item in one:
                            self.write("Yes%s"%item)
                    #self.write(a.fetchone())
                    #self.write("premise:",one['premise']," and consequence:",one['consequence'])
                except:
                    self.write(“wtf”)
                cursor.close()
            except:
                self.write("database connection error")
        except:
            self.write("Hello Tornado")

以上。

你可能感兴趣的:(tornado,sina-app-engine,mysql)