tornado 入门 - 展示静态页面

*安装

pip install tornado


*展示静态页面步骤

 启动一个http server

处理http请求

定义URL映射

处理错误请求

模块化页面内容


例子

import tornado.httpserver
import tornado.ioloop
import tornado.web
import os
# class IndexHandler(tornado.web.RequestHandler):
#     def get(self):
#         greeting = self.get_argument('greeting', 'Hello')
#         self.write(greeting + ', friendly valex!')

class HomeHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        #msg = 'hello from home'
        #self.write(msg)
        self.render('login.html', error ='')
class OtherHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        #self.redirect('/')
        #可以给出自定义错误
        raise tornado.web.HTTPError(status_code=416, log_message='Testing',reason='unkown request')
class FormHandler(tornado.web.RequestHandler):
    def post(self):
        raise tornado.web.HTTPError(status_code=416, log_message='testing', reason = 'Sumbmit is not supported yet')


class CustomApp(tornado.web.Application):
    def __init__(self):
        handles = [
            (r'/', HomeHandler),
            (r'/login', HomeHandler),
            (r'/auth/login', FormHandler),
            # (r'/.*', tornado.web.RedirectHandler,{'url':'/'}),
            (r'/.*', OtherHandler),
        ]
        settings = {
            #取得本文件所在的目录与templates组合一个路径
            'template_path':os.path.join(os.path.dirname(__file__), 'templates'),
            'static_path':os.path.join(os.path.dirname(__file__), 'static'),
            'blog_title': "tornado blog",
        }
        super(CustomApp, self).__init__(handles, **settings)


if __name__ == '__main__':
    # 实例化一个httpserver对象
    #app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
    app = CustomApp()
    http_server = tornado.httpserver.HTTPServer(app)
    # 监听8888 套接字端口
    http_server.listen(8888)
    # 启动事件循环
    tornado.ioloop.IOLoop.instance().start()

templates/base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{escape(handler.settings["blog_title"])}}</title>
</head>
<body>
{% block body %}
{% end %}
</body>
</html>

templates/login.html

{% extends "base.html" %}
{% block body %}
{% if error %}
<span style="...">Error:{{ error}} </span><p></p>
{% end %}

<form action="/auth/login" method="post">
    email:<input name = 'email' type="text"><br>
    <p></p>
    name:<input name = 'password' type="password"><br>
    <p></p>
    {% module xsrf_form_html() %}
    <input type="submit">

</form>
{% end %}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值