Tornado 简单入门教程(一)——Demo1

本文是Tornado框架的入门教程,通过构建一个简单的博客系统,介绍如何初始化项目、设置Handlers和settings、数据库连接及服务器处理请求。适合已有web开发基础的读者,旨在快速掌握Tornado的使用。
摘要由CSDN通过智能技术生成

前面的话

Demo1是一个简单的博客系统(=。=什么网站都叫系统)。我们从这个简单的系统入手,去了解P+T+M网站的内部逻辑,并记住一些“规则”,方便我们进一步自己开发。

“规则”这个词特意打上了双引号,目的是想借此声明一点:本教程内不会将各语句背后的原理逐一讲明(事实上我也讲不清楚哈哈)。我的着重点将在“怎样快速学会使用这个‘框架’去搭建我们想要的网站”,即“怎样快速上手一个工具”。由于本人在技术上研究不深入不细致,所以用词或者内容上难免有不规范或错误之处,能理解的就自行理解哈。当然愿意斧正的欢迎指出。

对了,本教程默认读者是有web开发基础的,明白“渲染”、“get请求”、“post请求”等分别是什么意思。

讲解模式

基本的是:

  • 列出项目目录结构
  • 展示源码,通过部分源码注释(红色字)讲解
  • 列表项目
  • 根据网站逻辑结合“代码回顾”进行讲解

希望大家复制源码(记得把红字注释删除)根据项目目录结构创建项目,或者直接将附件中的代码包拷到你的项目目录,跟着讲解一步一步试验。

OK,开始。

Demo1项目目录结构

demo1
    demo.py
    -static
        -css
            style.css
        -img
            bg.jpg
            logo.png
    -templates
        index.html
        blog.html

源码

demo.py

#!/usr/bin/env python

# -*- coding: utf-8 -*-
#用于规定字符编码,想要中文正常最好就加上这句

import os.path
import tornado.auth
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
#巴拉巴拉import一大堆tornado的东西,反正都有用,原封不动即可

import pymongo
#这里是导入MongoDB

define(“port”, default=8002, help=”run on the given port”, type=int)
#定义监听的端口,随便挑个喜欢的数字吧

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
        (r”/”, MainHandler),
        (r”/blog”, BlogHandler),
        ]

    settings = dict(
    template_path=os.path.join(os.path.dirname(__file__), “templates”),
    static_path=os.path.join(os.path.dirname(__file__), “static”),
    debug=True,
    )

    conn = pymongo.Connection(“localhost”, 12345)
    self.db = conn[“demo”]
    tornado.web.Application.__init__(self, handlers, **settings)

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render(“index.html”,)

    def post(self):
        import time
        title = self.get_argument(‘title’, None)
        content = self.get_argument(‘content’, None)
        blog = dict()
        if title and content:
            blog[‘title’] = title
            blog[‘content’] = content
            blog[‘date’] = int(time.time())
            coll = self.application.db.blog
            coll.insert(blog)
            self.redirect(‘/blog’)
        self.redirect(‘/’)

class BlogHandler(tornado.web.RequestHandler):
    def get(self):
        coll = self.application.db.blog
        blog = coll.find_one()
        if blog:
            self.render(“blog.html”,
            page_title = blog[‘title’],
            blog = blog,
            )
        else:
            self.redirect(‘/’)

def main():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == “__main__”:
    main()

index.html

<!DOCTYPE html>
<html lang=”zh-CN”>    
    <head>        
    <meta ch
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值