举例说明get和post该方法的用途:
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。
然后打开浏览器,输入http://ip:8888就看到页面输出Hello, world了。
# 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()
<head>
<title>{ {title}}</title>
</head>
<body>
<form name='input' action='/' method='post'>
talk:
<input type='text' name='talk'/>
<input type='submit' value='send'/>
</form>
<ul>
{%for i in items%}
<li>{ {escape(i)}}</li>
{%end%}
</ul>
</body>
</html>
# mysql -u root
假设提示找不到mysql文件,请尝试使用绝对路径,如本文演示样例为:
# /usr/local/mysql/bin/mysql -u root
命令成功运行后将进入到mysql命令提示符下:
1. 设置从本地主机登录的root帐号password:
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 | |
+---------+-----------+------+-----+---------+-------+
python tornado_serv.py
Traceback (most recent call last):
File "tornado_serv.py", line 6, in <module>
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 <module>
import torndb
File "/usr/local/python2.7.3/lib/python2.7/site-packages/torndb.py", line 33, in <module>
import MySQLdb.constants
ImportError: No module named MySQLdb.constants
解决:
安装MySQL-python-1.2.3
# wget http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz/download
# 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,
以自己机器的为准.
假设没有找到,则表示你的server没有安装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 <module>
import torndb
File "/usr/local/python2.7.3/lib/python2.7/site-packages/torndb.py", line 33, in <module>
import MySQLdb.constants
File "build/bdist.linux-x86_64/egg/MySQLdb/__init__.py", line 19, in <module>
File "build/bdist.linux-x86_64/egg/_mysql.py", line 7, in <module>
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)")
解决:
是由于数据库没有设置并创建表;
依据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
一、演示样例用的GET方法:
import tornado.ioloopimport 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。
然后打开浏览器,输入http://ip:8888就看到页面输出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的内容例如以下:
<html><head>
<title>{ {title}}</title>
</head>
<body>
<form name='input' action='/' method='post'>
talk:
<input type='text' name='talk'/>
<input type='submit' value='send'/>
</form>
<ul>
{%for i in items%}
<li>{ {escape(i)}}</li>
{%end%}
</ul>
</body>
</html>
三、数据库操作
以root帐号连接到mysqlserver:# mysql -u root
假设提示找不到mysql文件,请尝试使用绝对路径,如本文演示样例为:
# /usr/local/mysql/bin/mysql -u root
命令成功运行后将进入到mysql命令提示符下:
1. 设置从本地主机登录的root帐号password:
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 <module>
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 <module>
import torndb
File "/usr/local/python2.7.3/lib/python2.7/site-packages/torndb.py", line 33, in <module>
import MySQLdb.constants
ImportError: No module named MySQLdb.constants
解决:
安装MySQL-python-1.2.3
# wget http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz/download
# 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,
以自己机器的为准.
假设没有找到,则表示你的server没有安装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 <module>
import torndb
File "/usr/local/python2.7.3/lib/python2.7/site-packages/torndb.py", line 33, in <module>
import MySQLdb.constants
File "build/bdist.linux-x86_64/egg/MySQLdb/__init__.py", line 19, in <module>
File "build/bdist.linux-x86_64/egg/_mysql.py", line 7, in <module>
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)")
解决:
是由于数据库没有设置并创建表;
五、页面測试
浏览器打开 "http://ip:8888" 的时候,发出 "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
版权声明:本文博客原创文章。博客,未经同意,不得转载。