您的位置:首页 > 运维架构 > 网站架构

实战用tornado写一个最简单最暴力的网站

2019-06-13 16:38 2311 查看

讲道理,用惯了Flask感觉还是不熟悉Djongo,所以先来看一下Tornado(滑稽),记住这是一个最简单的最暴力的网页,毫无细节。

环境
Win10 
Python 3.6
Pycharm
Tornado

首先,你需要一个计划
首先无论编写什么程序,无论我们再怎么不正式,起码都要有个计划书,而我的计划比较简单就:

[code]**开发个人日记**
    -- 新建日记
        --保存在数据库
            --信息:
                    1.日期
                    2.天气
                    3.心情
                    4.内容
                    --扩展//未开发
                    5.信纸
                    6.类别
                    7.bgm
    -- 查询日记
        --查询
            --时间
            --心情
            --天气


所以现在制定下来了我们的大纲,该怎么实现呢?

[code][Input]: If i need Python基础 and web前端基础 and 服务器编程基础?
[Output]: Yes…
[Output]: But,it is so f**king EZ.

从HelloWorld开始
你好世界,多么简单的操作:
打开我们的Pycharm,新建一个工程,我们叫他HelloWorld(因为暴力,工程名就不改了)
新建一个app.py

然后我们需要导入我们的tornado库,但是我们不是什么都需要暂且这样:

[code]from tornado import web,ioloop,httpserver


这个时候我们是不是一筹莫展

一筹莫展 [ yī chóu mò zhǎn ]
筹:筹划、计谋;展:施展。一点计策也施展不出,一点办法也想不出来。 筹:筹划、计谋;展:施展。一点计策也施展不出,一点办法也想不出来。筹:筹划、计谋;展:施展。一点计策也施展不出,一点办法也想不出来。
出处 出 处出处
清⋅孔尚任《桃花扇》:“下官史可法;日日经略中原;究竟一筹莫展。” 清·孔尚任《桃花扇》:“下官史可法;日日经略中原;究竟一筹莫展。”清⋅孔尚任《桃花扇》:“下官史可法;日日经略中原;究竟一筹莫展。”
例句 例 句例句
1.面对这道复杂的数学题,他~,不知该从何做起。 1. 面对这道复杂的数学题,他~,不知该从何做起。1.面对这道复杂的数学题,他~,不知该从何做起。在学习中有迷茫不知如何学习的朋友小编推荐一个学Python的学习q u n 315 -346-  913可以来了解一起进步一起学习!免费分享视频资料

当我们不知道干嘛的时候就是英语灵感的时候了,我们要写的是什么?网页应用,对!那他的英文呢?web Application,那我们何不试一下,tornado的开发人员会不会让我们直接明白该怎么用呢?

[code]web.Application

然后利用我们的Pycharm和超链接知识:按住Ctrl 点击 Application,Wow,新大陆(我也是学Kotlin时候才发现的…):

[code]class Application(ReversibleRouter):

    """A collection of request handlers that make up a web application.

    Instances of this class are callable and can be passed directly to

    HTTPServer to serve the application::

        application = web.Application([

            (r"/", MainPageHandler),

        ])

        http_server = httpserver.HTTPServer(application)

        http_server.listen(8080)

        ioloop.IOLoop.current().start()

    The constructor for this class takes in a list of `~.routing.Rule`

    objects or tuples of values corresponding to the arguments of

    `~.routing.Rule` constructor: ``(matcher, target, [target_kwargs], [name])``,

    the values in square brackets being optional. The default matcher is

    `~.routing.PathMatches`, so ``(regexp, target)`` tuples can also be used

    instead of ``(PathMatches(regexp), target)``.

    A common routing target is a `RequestHandler` subclass, but you can also

    use lists of rules as a target, which create a nested routing configuration::

        application = web.Application([

            (HostMatches("example.com"), [

                (r"/", MainPageHandler),

                (r"/feed", FeedHandler),

            ]),

        ])

    In addition to this you can use nested `~.routing.Router` instances,

    `~.httputil.HTTPMessageDelegate` subclasses and callables as routing targets

    (see `~.routing` module docs for more information).

    When we receive requests, we iterate over the list in order and

    instantiate an instance of the first request class whose regexp

    matches the request path. The request class can be specified as

    either a class object or a (fully-qualified) name.

    A dictionary may be passed as the third element (``target_kwargs``)

    of the tuple, which will be used as keyword arguments to the handler's

    constructor and `~RequestHandler.initialize` method. This pattern

    is used for the `StaticFileHandler` in this example (note that a

    `StaticFileHandler` can be installed automatically with the

    static_path setting described below)::

        application = web.Application([

            (r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),

        ])

    We support virtual hosts with the `add_handlers` method, which takes in

    a host regular expression as the first argument::

        application.add_handlers(r"www\.myhost\.com", [

            (r"/article/([0-9]+)", ArticleHandler),

        ])

    If there's no match for the current request's host, then ``default_host``

    parameter value is matched against host regular expressions.

    You can serve static files by sending the ``static_path`` setting

    as a keyword argument. We will serve those files from the

    ``/static/`` URI (this is configurable with the

    ``static_url_prefix`` setting), and we will serve ``/favicon.ico``

    and ``/robots.txt`` from the same directory.  A custom subclass of

    `StaticFileHandler` can be specified with the

    ``static_handler_class`` setting.

    .. versionchanged:: 4.5

       Integration with the new `tornado.routing` module.

    """

妈耶~这么长,但是我们会发现有模板,我们就喜欢模板对吗?

[code]application = web.Application([
            (r"/", MainPageHandler),
        ])
        http_server = httpserver.HTTPServer(application)
        http_server.listen(8080)
        ioloop.IOLoop.current().start()


怎么用呢?
我们需要定义一个类(MainPageHandler)

[code]class MainPageHandler(web.RequestHandler):
    def get(self, *args, **kwargs):



为什么要这么写呢?看看RequestHandler的注释我们就明白了

[code]"""Base class for HTTP request handlers.
    Subclasses must define at least one of the methods defined in the
    "Entry points" section below.
"""
SUPPORTED_METHODS = ("GET", "HEAD", "POST", "DELETE", "PATCH", "PUT",
                         "OPTIONS")



然而我们需要的是get数据,那么我们就应该用get方法。(web基础知识)


然后我们需要给他写一个Hello,World让他显示出来,怎么写呢?print肯定不行,我们只需要:

[code]class MainPageHandler(web.RequestHandler):
    def post(self, *args, **kwargs):
    


 

[code][Input]: 接下来呢?这就完了?
[Input]: 给人写信,怎么可能没有地址,没有邮局呢(前提是距离长的像互联网一般)
[Input]: 所以我们要干啥呢?
[Output]: 找人帮忙:

处理、路由、前台
首先我们定义的类(MainPageHandler):就是我们的助手之一,助手a,负责拿到内容

[code]class MainPageHandler(web.RequestHandler):
    def get(self, *args, **kwargs):
    


接下来我们需要一个地址,由助手b来跑腿,告诉地址:

[code]application = web.Application([
            (r"/", MainPageHandler),
        ])


 

[code][Input]: 那我们还需要什么呢?
[Output]: 前台,没有助手前台,怎么发送信(这个前台包括邮筒)

前台小助手c:

[code]def main():
    http_server = httpserver.HTTPServer(application)
    http_server.listen(8080)
    ioloop.IOLoop.current().start()
[code][Input]: 看起来是完了,但是我们写在哪里呢,信纸呢 ?
[Output]: 当然是我们的前端页面

暴力:在当前目录下面新建一个HTML网页:我们叫他index.html,写出下面的html代码:

[code]<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>Hello,World</h1>
</body>
</html>

然后我们请寄东西的小助手a,来把信取去:

[code]class MainPageHandler(web.RequestHandler):
    def get(self, *args, **kwargs):
        self.render("index.html")


接下来是助手b登场,告诉应该从哪里

[code]application = web.Application([
            (r"/", MainPageHandler),
        ])


接下来就是我们的前台了,

[code]def main():
    http_server = httpserver.HTTPServer(application)
    http_server.listen(8080)
    ioloop.IOLoop.current().start()


来来来,看看我们的信:

[code]if __name__ == '__main__':
    main()


开启我们的服务器,就是运行app.py
打开浏览器,去访问 [127.0.0.1:8080](http://127.0.0.1:8080/)

 

以上就是一个简单地网站全过程了,如果想要进一步学习,欢迎进群和小编探讨

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: