1.index模板:
<html>
<head lang="en">
<meta charset="UTF-8">
<title>kkk</title>
</head>
<body>
你好:{{ ken }},欢迎光临!
<form action="" method="PUT">
<input type="text" name="message">
<input type="submit" value="Submit">
<input type="reset" value="reset">
</form>
</body>
</html>
2.web_run.py
#coding=utf-8
__author__ = 'Administrator'
import tornado.autoreload
import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.escape
import tornado.options
import tornado.template
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class myapp(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler),
(r".*", redirect_Handler), #匹配所以的404,not fount重定向
]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=True,
)
tornado.web.Application.__init__(self, handlers, **settings)
class redirect_Handler(tornado.web.RequestHandler):
def get(self):
self.redirect('/test')
class MainHandler(tornado.web.RequestHandler):
def get(self):
text = self.get_argument("message", "来宾")
#self.write('<html><body><form action="/" method="post">'
# '<input type="text" name="message">'
# '<input type="submit" value="Submit">'
# '</form></body></html>')
self.render('index.html', ken=text)
def post(self):
#可以识别post方法
#self.set_header("Content-Type", "text/plain")
text = self.get_argument("message")
if text == "": text = "来宾"
self.render('index.html', ken=text)
print("Post: " + text)
def put(self):
text = self.get_argument("message")
if text == "": text = "None"
self.write("{'Put':'%s'}"% text)
def delete(self):
self.write("delete: " + self.get_argument("message", "None"))
class WrapHandler(tornado.web.RequestHandler):
def post(self):
text = self.get_argument('text')
width = self.get_argument('width', 40)
self.write(textwrap.fill(text, int(width)))
class temHandler(tornado.web.RequestHandler):
def get(self,args):
ken = args
self.render('index.html', ken=ken)
def post(self):
#self.render('index.html')
text = self.get_argument('message')
self.write(text)
#myapp = tornado.web.Application([
# (r"/", MainHandler),
# (r"/wrap", WrapHandler),
# (r"/tem/([0-9a-z]+)", temHandler)
#],
#template_path=os.path.join(os.path.dirname(__file__), "templates")
#)
if __name__ == "__main__":
#myapp.listen(80)
#tornado.ioloop.IOLoop.instance().start()
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(myapp())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
3.测试:
Administrator@USER-20150313KE ~
$ curl -XPUT http://127.0.0.1:8000/?message=
{'Put':'None'}
$ curl -XPUT http://127.0.0.1:8000/?message=kkk
{'Put':'kkk'}
$ curl -XDELETE http://127.0.0.1:8000/?message=kkk
delete: kkk
$ curl -XDELETE http://127.0.0.1:8000/?message=
delete:
#命令行可以识别put和delete方法,网页里确无法识别,仅能post和get,,,郁闷中
5.默认运行端口:8000
也可以设置:python web_run.py --port=8080