例子说明get和post的方法使用:
一、示例用的GET方法:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
运行
# python tornado_example.py,
然后打开浏览器,输入就看到页面输出Hello, world了。
二、GET&POST 代码
1. tornado-serv.py
#!/usr/bin/python
# File : tornado-serv.py
import torndb
import tornado.web
import tornado.ioloop
from tornado.options import define,options,parse_command_line
define('port',default=8888,help='run on the port',type=int)
database=torndb.Connection('localhost','talk',user='root',password='123456')
l=[]
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render('example.html',title='Tornado GET&POST',items=l)
def post(self):
count=1
print(self.request.remote_ip)
talk=self.get_argument('talk')
talk=str(talk)
database.execute('insert into chatting(id,content) values(%d,"%s")'%(count,talk))
l.append(talk)
self.render('example.html',title='Tornado GET&POST',items=l)
def main():
parse_command_line()
app=tornado.web.Application(
[(r'/',MainHandler),
],)
app.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__=='__main__':
main()
2. example.html的内容如下:
{{title}}
{%for i in items%}
- {{escape(i)}}
{%end%}
三、数据库操作
以root帐号连接到mysql服务器:
# mysql -u root
如果提示找不到mysql文件,请尝试使用绝对路径,如本文示例为:
# /usr/local/mysql/bin/mysql -u root
命令成功执行后将进入到mysql命令提示符下:
1. 设置从本地主机登录的root帐号密码:
mysql> set password for root@localhost=password('123456');
2. 创建"talk"数据库
mysql> create database talk;
3. 创建"chatting"表
mysql> use talk;
mysql> create table chatting(id int, content char(128));
4. 查看表
mysql> describe chatting;
+---------+-----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-----------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| content | char(128) | YES | | NULL | |
+---------+-----------+------+-----+---------+-------+
四、出错问题解决
1. 运行 tornado-serv.py时报错:
python tornado_serv.py
Traceback (most recent call last):
File "tornado_serv.py", line 6, in
import torndb
ImportError: No module named torndb
解决:
需要安装 torndb
# pip install torndb
2. 运行 tornado-serv.py时报错:
Traceback (most recent call last):
File "tornado_serv.py", line 6, in
import torndb
File "/usr/local/python2.7.3/lib/python2.7/site-packages/torndb.py", line 33, in
import MySQLdb.constants
ImportError: No module named MySQLdb.constants
解决:
安装MySQL-python-1.2.3
# wget
# tar zxf MySQL-python-1.2.3.tar.gz && cd MySQL-python-1.2.3
# python setup.py build
# python setup.py install
如果在执行python setup.py build时,报EnvironmentError: mysql_config not found的话,
先查找mysql_config的位置,使用
# find / -name mysql_config
我的是在/usr/local/mysql/bin/mysql_config,
然后修改MySQL-python-1.2.3目录下的site.cfg文件,
去掉mysql_config=XXX这行的注释,并改成
mysql_config=/usr/local/mysql/bin/mysql_config,
以自己机器的为准.
如果没有找到,则表示你的服务器没有安装mysql,需要先安装。
再执行下面命令就可以了
python setup.py build
python setup.py install
3. 运行 python tornado_serv.py 时报错:
Traceback (most recent call last):
File "tornado_serv.py", line 6, in
import torndb
File "/usr/local/python2.7.3/lib/python2.7/site-packages/torndb.py", line 33, in
import MySQLdb.constants
File "build/bdist.linux-x86_64/egg/MySQLdb/__init__.py", line 19, in
File "build/bdist.linux-x86_64/egg/_mysql.py", line 7, in
File "build/bdist.linux-x86_64/egg/_mysql.py", line 6, in __bootstrap__
ImportError: libmysqlclient_r.so.15: cannot open shared object file: No such file or directory
解决:
查找动态库 libmysqlclient_r.so
# find / -name libmysqlclient_r.so
/usr/local/mysql/lib/mysql/libmysqlclient_r.so
将包含库的目录 /usr/local/mysql/lib/mysql
添加到库查找路径
# vim /etc/ld.so.conf
最后一行添加:
/usr/local/mysql/lib/mysql
【保存并退出】
# ldconfig
4. python tornado_serv.py
ERROR:root:Cannot connect to MySQL on localhost
Traceback (most recent call last):
File "/usr/local/python2.7.3/lib/python2.7/site-packages/torndb.py", line 96, in __init__
self.reconnect()
File "/usr/local/python2.7.3/lib/python2.7/site-packages/torndb.py", line 113, in reconnect
self._db = MySQLdb.connect(**self._db_args)
File "build/bdist.linux-x86_64/egg/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "build/bdist.linux-x86_64/egg/MySQLdb/connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")
解决:
是因为数据库没有设置并创建表;
五、页面测试
浏览器打开 "" 的时候,发出 "GET"请求,请求根目录"/",
根据tornado.web.Application中参数列表中元组对(r'/',MainHandler),于是找到MainHandler类,
这个类继承了tornado.web.RequestHandler类,但是它里面没有定义get和post方法(具体可以看源码),
所以在MainHandler类中定义。
由于我只在用户第一次访问网站时处理get方法,
所以就是render example.html 就可以了。
之后传递数据全用 "POST" 方法,并把网页上输入的数据存放到数据库中。
浏览器显示如下:
数据库中显示如下:
mysql> select * from chatting;
+------+--------------------------+
| id | content |
+------+--------------------------+
| 1 | hello |
| 1 | who |
| 1 | this is |
| 1 | what are you doing |
| 1 | fet |
| 1 | this is my first version |
+------+--------------------------+
6 rows in set (0.00 sec)
终端显示如下:
[@ltv_13 python_study]# python tornado_serv.py
[I 140719 10:11:17 web:1811] 304 GET / (192.168.9.91) 3.42ms
192.168.9.91
[I 140719 10:11:20 web:1811] 200 POST / (192.168.9.91) 1.13ms
192.168.9.91
[I 140719 10:11:25 web:1811] 200 POST / (192.168.9.91) 0.85ms
192.168.9.91
[I 140719 10:11:35 web:1811] 200 POST / (192.168.9.91) 0.80ms
192.168.9.91
[I 140719 10:11:46 web:1811] 200 POST / (192.168.9.91) 0.82ms
192.168.9.91
[I 140719 10:11:51 web:1811] 200 POST / (192.168.9.91) 0.78ms
192.168.9.91
[I 140719 10:12:09 web:1811] 200 POST / (192.168.9.91) 0.99ms
阅读(27813) | 评论(0) | 转发(0) |