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




    
    {{escape(handler.settings["blog_title"])}}


{% block body %}
{% end %}


templates/login.html

{% extends "base.html" %}
{% block body %}
{% if error %}
Error:{{ error}} 

{% end %}
email:

name:

{% module xsrf_form_html() %}
{% end %}



你可能感兴趣的:(tornado 入门 - 展示静态页面)