今天由于要提供几个开放的接口给我毕设相关的平台调用,因此又开始折腾以前在SAE
上搭的Tornado
应用。html
以前记录过一个 如何在 SAE 上使用 Tornado,此次续上,关于在SAE
里使用Tornado
框架时基本的MySQL
操做。由于本身刚才找了好久资料才用起来,也怪本身以前没在Tornado
里面用过MySQL
,因此为其余同窗之后少走弯路来一个整理贴。python
首先在应用控制台
初始化共享型MySQL
。mysql
点击管理MySQL
能够进入管理后台,标准的PHPMyAdmin
。web
根据 SAE官方文档 底部介绍,你能够经过如下方法得到链接数据库所需的参数。sql
import sae.const sae.const.MYSQL_DB # 数据库名 sae.const.MYSQL_USER # 用户名 sae.const.MYSQL_PASS # 密码 sae.const.MYSQL_HOST # 主库域名(可读写) sae.const.MYSQL_PORT # 端口,类型为<type 'str'>,请根据框架要求自行转换为int sae.const.MYSQL_HOST_S # 从库域名(只读)
注意:须要将
sae.const.MYSQL_PORT
转成int型
。数据库
SAE Python
内置了MySQLdb模块
,用法以下:框架
1 导入sae
常量和MySQLdb
模块:tornado
import sae.const import MySQLdb
2 链接数据库:fetch
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
对象,用于执行命令:.net
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")
以上。