《Introduction to Tornado》笔记02-从请求中获取信息+写HTTP响应+命令行形式运行程序

app01.py

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from tornado.escape import json_encode

from tornado.options import define, options

define("port", default=9002, help="run on the gevent port", type=int)
define("host",default="127.0.0.1",help="xxx",type=str)

class IndexHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): greeting = self.get_argument("greeting", "DEFAULT") self.write(greeting + ",friendly user!") self.write(json_encode({ "name": "wanghw", "age": 18, })) if __name__ == '__main__': #  解析命令 # 在终端输入下面命令启动程序: python app01.py --port=8000 --host=127.0.0.1 tornado.options.parse_command_line() app = tornado.web.Application( handlers=[ (r'/index', IndexHandler), ], debug=True, ) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()

app02.py

import textwrap

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from tornado.options import define, options

define("port", default=9100, help="run on the gevent port", type=int)


class ReverseHandler(tornado.web.RequestHandler):
    # 到 /reverse/string 的 GET请求将会返回 URL 路径中指定字符串的反转形式
    # 如果正则表达式中有一系列额外的括号,匹配的字符串将被按照在正则表达式中出现的顺序作为额外的参数传递进来
    def get(self, input):
        self.write(input[::-1])


class WrapHandler(tornado.web.RequestHandler):
    # 到 /reverse/string 的 GET请求将会返回 URL 路径中指定字符串的反转形式
    def post(self):
        # get_argument方法也可以接收post请求参数对应的数据
        text = self.get_argument("text")
        width = self.get_argument('width', 5)
        # 将所给的长字符串切成每5(默认)个字符一行的格式
        self.write(textwrap.fill(text, int(width)))


if __name__ == '__main__':
    # 解析命令
    #  python app02.py --port=8000
    tornado.options.parse_command_line()

    app = tornado.web.Application(
        handlers=[
            (r"/reverse/(\w+)",ReverseHandler),
            (r"/wrap",WrapHandler),
        ],
        debug=True
    )

    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)

    tornado.ioloop.IOLoop.instance().start()

~~~

posted on 2019-10-30 16:11  江湖乄夜雨  阅读(155)  评论(0编辑  收藏  举报