tornado

Tornado 简单示例


案例1

import tornado.web
import tornado.ioloop


class IndexHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        return self.write('hello world')



app = tornado.web.Application([
    (r'/', IndexHandler),
])


app.listen(8089)

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

输入 网址 http://127.0.0.1:8089/


案例2

import tornado.web
import tornado.ioloop

class IndexHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        return self.render(template_name='templates/login.html')

    def post(self, *args, **kwargs):
        username = self.get_body_argument('username')
        return self.write(username)


app = tornado.web.Application([
    (r'/', IndexHandler),
    (r'/login/', IndexHandler),
])

app.listen(8888)

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

templates/login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/login/", method="post">
    <p>
        用户名 <input type="text" name="username">
    </p>

    <p>
        密码 <input type="text" name="pwd">
    </p>
        <input type="submit" value="登录">
    </p>
</form>
</body>
</html>

访问http://127.0.0.1:8089/




案例3 单文件上传

import tornado.web
import tornado.ioloop
import os


class UploadHandler(tornado.web.RequestHandler):

    @staticmethod
    def makeuploadfiles(fileinfo: list):
        filedict = fileinfo[0]
        filename, filedata = filedict.get('filename'), filedict.get('body')
        content_type = filedict.get('content_type')

        filepath = os.path.join(os.getcwd(), 'files', filename)
        filedirpath = os.path.dirname(filepath)

        return filepath, filedirpath, filedata, content_type


    def get(self, *args, **kwargs):
        return self.render('templates/upload.html')

    def post(self, *args, **kwargs):
        fileinfo = self.request.files['fileinfo']
        if len(fileinfo) == 1:
            filepath, filedirpath, filedata,content_type = self.makeuploadfiles(fileinfo)

            if not os.path.exists(filedirpath):
                os.makedirs(filedirpath)

            with open(filepath, 'wb') as fw:
                fw.write(filedata)

            self.set_header(name='Content-Type', value=content_type)
            self.write(filedata)




app = tornado.web.Application([
    (r'/upload/',UploadHandler)
])


app.listen(8888)
tornado.ioloop.IOLoop().instance().start()

templates/upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload/", method="post", enctype="multipart/form-data">
    <input type="file" name="fileinfo">
    <input type="submit" value="上传">
</form>
</body>
</html>
posted @ 2020-03-31 21:29  cjw1219  阅读(154)  评论(0编辑  收藏  举报