项目 01 项目简介和基本页面

项目 01 项目简介和基本页面

  app.py

import os.path

import tornado.ioloop 
import tornado.options
import tornado.web
from tornado.options import define,options  #导入包

from handlers import main  #导入handlers目录下的main.py


define('port',default='8000',help='Listening port',type=int) #定义如何接收传进来的东西

class Application(tornado.web.Application):#引入Application类,重写方法,这样做的好处在于可以自定义,添加另一些功能
    def __init__(self):
        handlers = [
            ('/',main.IndexHandler), #定义main路由
            ('/explore', main.ExploreHandler), #定义explore路由
            ('/post/(?P<post_id>[0-9]+)', main.PostHandler),#定义post的路由,利用了正则捕获
        ]  #额外指定handlers
        settings = dict(
            debug = True, #自动保存并调用
            template_path = 'templates', #模板文件目录
            static_path = 'static' #静态文件目录
        ) #额外指定settings

        super(Application,self).__init__(handlers,**settings) #用super方法将父类的init方法重新执行一遍,然后将handlers和settings传进去,完成初始化

application = Application() #Application的实例化

if __name__ == '__main__': #增加main判断
    tornado.options.parse_command_line()
    application.listen(options.port)#监听路径
    print("Server start on port {}".format(str(options.port))) #提示跑的时候所在的端口
    tornado.ioloop.IOLoop.current().start()#执行ioloop

 用python pakpackage创建handlers目录,在该目录放方所有的handler文件

  handlers/main.py

import tornado.web #导入包

class IndexHandler(tornado.web.RequestHandler): #index路由
    """
    Home page for user,photo feeds 主页----用户,照片提要
    """
    def get(self,*arg,**kwargs):#重写get
        self.render('index.html') #打开index.html网页


class ExploreHandler(tornado.web.RequestHandler): #explore路由
    """
    Explore page,photo of other users 浏览页面和其他用户的照片
    """
    def get(self,*arg,**kwargs):
        self.render('explore.html')#打开explore.html

class PostHandler(tornado.web.RequestHandler):#post路由
    """
    Single photo page and maybe  单独的照片页
    """
    def get(self,*arg,**kwargs):
        self.render('post.html',post_id = kwargs['post_id']) #根据正则输入的内容,接收到kwargs(关键字),打开相应的图片

  创建一个模板包templates

  templates/base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}Tornado Title {% end %}</title>#自定义标题
</head>
<body>
{% block content %} base content {% end %} #自定义body

</body>
</html>

  templates/index.html

{% extends 'base.html' %} #继承base.html

{% block title %} index page {% end %} #重写title

{% block content %} index content {% end %} #重写body

  templates/explore.html

{% extends 'base.html' %}

{% block title %} explore page {% end %}

{% block content %} explore content {% end %}

  templates/post.html

{% extends 'base.html' %}

{% block title %} post page {% end %}

{% block content %} post of {{ post_id }} content {% end %}#获取post_id并write到网页
原文地址:https://www.cnblogs.com/xuchengcheng1215/p/9123397.html