简单使用tornado服务器,建立hello world页面及tornado简单页面,并配置template和static文件路径,url分发

首先安装tornado:我用的最新版5.1.1

cmd 输入命令 pip install tornado

建立hello world页面及tornado简单页面,并配置template和static文件路径,url分发:

这里要注意:py文件名不能用tornado,import时会报错!

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

#自己扩展url指向的类,调用其对应方法post/get
class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")
    def post(self, *args, **kwargs):
        self.write("post request")

#配置文件
settings={
    "template_path":"template",
    "static_path":"static",
    #static文件设置别名
    "static_url_prefix":"/ray/",
}

#尾部**settings为加载配置文件
def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
        (r"/index.html", IndexHandler),
    ],**settings)

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <h1>这是个一个主页</h1>
    <form action="/index.html" method="post">
        <p> username:<input type = "text"></p>
        <p> password:<input type = "password"></p>
        <p> <input type = "submit" value="提交"></p>
    </form>
    <img src="/ray/123.jpg" />
    <!--<img src="/static/123.jpg" />-->
</body>
</html>

浏览器效果:

猜你喜欢

转载自blog.csdn.net/java_raylu/article/details/84193803