python全栈开发Python 运维我的Python自学之路

Tornado框架01-入门总概

2017-03-10  本文已影响282人  凉茶半盏

我们首先来谈谈web框架. web框架的本质其实就是socket服务端再加上业务逻辑处理, 比如像是Tornado这样的框架. 有一些框架则只包含业务逻辑处理, 例如Django, bottle, flask这些框架, 它们的使用需要依赖包含socket的第三方模块(即 wsgiref)来运行
在python中常见的web框架构建模式有以下两种:

以上两种只是命名不同, 所遵循的的思想也只是大同小异

在使用Tornado框架前, 我们先使用wsgiref再加上自己写的业务逻辑自定义一个web框架

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from wsgiref.simple_server import make_server


def index():
    return "This is index "


def news():
    return "welcome to news "


URLS = {
    '/index': index,
    '/news': news,
}


def RunServer(rq, rp):
    rp('200 OK', [('Content-Type', 'text/html')])
    url = rq['PATH_INFO']
    if url in URLS.keys():
        ret = URLS[url]()
    else:
        ret = '404'
    return ret


if __name__ == '__main__':
    http = make_server('', 8000, RunServer)
    http.serve_forever()

接下来我们使用Tornado实现一个简陋的任务表功能demo

目录结构

**commons.css文件内容: **

.body {
    margin: 0;
    background-color: cornflowerblue;
}

**index.html文件内容: **

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>S1</title>
    <link rel="stylesheet" href="../static/commons.css">
</head>
<body>
<form method="post">
    <input type="text" name="name">
    <input type="submit" value="提交">
</form>
<h1>内容展示</h1>
<ul>
    {% for item in contents %}
        <li>{{item}}</li>
    {% end %}
</ul>
</body>
</html>

**index.py文件内容: **

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tornado.web, tornado.ioloop


class MyHandle(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        self.render("index.html", contents=CONTENTS_LIST)

    def post(self, *args, **kwargs):
        CONTENTS_LIST.append(self.get_argument('name'))
        self.render('index.html', contents=CONTENTS_LIST)


if __name__ == '__main__':
    CONTENTS_LIST = []
    settings = {
        'template_path': 'template',
        'static_path': 'static',
        'static_url_prefix': 'static/',
    }

    application = tornado.web.Application([
        (r"/index", MyHandle)
    ], **settings)
    application.listen(80)
    tornado.ioloop.IOLoop.instance().start()
客户端第一次访问 第一次输入提交

application = tornado.web.Application([
(r"/index", MyHandle)
], **settings)

根据浏览器的url确定其对应的处理类并生成该类的对象
-  `application.listen(80)` 设置服务端的监听端口
- `tornado.ioloop.IOLoop.instance().start()` 阻塞服务端进程, 等待客户端的访问
- 客户端第一次访问调用的是`MyHandle`类中的`get(self, *args, **kwargs)`方法, 服务端向客户端返回`index.html`文件
- 客户端浏览器接受到`index.html`文件之后, 在输入框中输入内容并提交之后会调用`post(self, *args, **kwargs)`, 并将输入的内容追加到
- `self.get_argument('name')` 获取指定参数的内容
`CONTENTS_LIST`中, 服务端返回`index.html`, 返回过程中`Toranado`
会将`CONTENTS_LIST` 的内容渲染到`index.html`之后才会发给客户端浏览器

**python中的模板引擎本质上是将`html`文件转换成一段`python`函数字符串, 再通过`compile`和`exec`将该函数执行, 以此来进行模板渲染**

*现在我们介绍一下模板引擎的使用: *


![项目目录](https://img.haomeiwen.com/i4241702/f0b7d9c757a0d228.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

**`uimethod.py`文件如下: **
```python
#!/usr/bin/env python
# -*- coding:utf-8 -*-

def test_uimethod(self):
    return "uimethod"

**uimodule.py文件如下: **

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from tornado.web import UIModule

class MyClass(UIModule):
    def render(self, *args, **kwargs):
        return "uimodule"

**index.py文件如下: **

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tornado.web, tornado.ioloop
import uimethod as ut
import uimodule as ud


class MyHandle(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        self.render("index.html", ag="this is ag", contents=CONTENTS_LIST)

    def post(self, *args, **kwargs):
        CONTENTS_LIST.append(self.get_argument('name'))
        self.render('index.html', contents=CONTENTS_LIST)


if __name__ == '__main__':
    CONTENTS_LIST = []
    settings = {
        'template_path': 'template',
        'static_path': 'static',
        'static_url_prefix': 'static/',
        'ui_methods': ut,
        'ui_modules': ud
    }

    application = tornado.web.Application([
        (r"/index", MyHandle)
    ], **settings)
    application.listen(80)
    tornado.ioloop.IOLoop.instance().start()

**index.html文件如下: **

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>S1</title>
    <link rel="stylesheet" href='{{static_url("commons.css")}}'>
</head>
<body>
<h1>{{ag}}</h1>
<h1>{{test_uimethod()}}</h1>
<h1>{%module MyClass()%}</h1>
<form method="post">
    <input type="text" name="name">
    <input type="submit" value="提交">
</form>
<h1>内容展示</h1>
<ul>
    {% for item in contents %}
    <li>{{item}}</li>
    {% end %}
</ul>
<hr>
</body>
</html>

*我们看看客户端访问的结果: *

访问结果

考虑到篇幅太长不容易阅读, 笔者这里将关于Tornado框架的cookie知识, 自定义session的使用 路由系统,以及模板引擎高级部分放在后期文章分篇共享

上一篇 下一篇

猜你喜欢

热点阅读