Python + Tornado 框架

发布一下 0 0

Python 的 Tornado 框架,属于 Python 的一个 Web 框架,是由 Python 编写的 Web 服务器兼 Web 应用框架。


Step1:Tornado 是什么

Tornado 是一个基于 Python 的 Web 服务框架和异步网络库。

最早开发于 FriendFeed 公司,通过利用非阻塞网络 I/O, Tornado 可以承载成千上万的活动连接, 完美的实现了长连接, WebSockets, 和其他对于每一位用户来说需要长连接的程序。


Step2:Tornado 有什么优势

Tornado 具有什么样的优点,我们为什么要用它?

• 轻量级 Web 框架

• 异步非阻塞 IO 处理方式

• 出色的抗负载能力

• 优异的处理性能,不依赖多进程/多线程,一定程度上解决 C10K 问题

• WSGI全栈替代产品,推荐同时使用其 Web 框架和 HTTP 服务器


Step3:Tornado 如何安装

pip install tornado 【安装最新稳定版】pip install tornado==version 【指定版本安装】


Step4:Tornado 核心内容

4.1 Tornado.Web:Tornado 的基础 Web 框架

• RequestHandler:封装对请求处理的所有信息和处理方法

• get/post/..:封装对应的请求方式

• write():封装响应信息,写响应信息的一个方法


4.2 Tornado.ioloop:核心IO循环模块,封装 Linux 的 Epoll 和 BSD 的 kqueue,Tornado 高性能处理的核心。

• current()返回当前线程的 IOLoop 实例对象

• start()启动 IOLoop 实力对象的 IO 循环,开启监听


4.3 HttpServer 监听端口

• tornado.httpserver.HTTPServer(app)

• httpserver.listen(port)


4.4 HttpServer 实现多进程操作

• tornado.httpserver.HTTPServer(app)

• httpserver.bind(port)

• httpserver.start(0/None/<0/num)


Step5:程序结构及说明

Config.py 配置文件:

import os#参数param={    'port':9992,}#配置setting={    "template_path":os.path.join(os.path.dirname(__file__), "templates"),  # 定义视图页面地址,放 html文件    "static_path":os.path.join(os.path.dirname(__file__), "static"),  # 定义静态模板,放 css,js等文件    # "debug":True,  # 是否为debug模式    "autoescape":None,  # 不设置转义字符    "autoreload":True,    "cookie_secret":"QjyutYf0RBW9DRweq4s+TozDU7esgEUTqQy0M6c5II8=",  #安全cookie    "xsrf_cookies": False,    "login_url": "/login",}


Application.py 路由配置文件:

import tornado.webimport Python_Tornoda.config as configfrom Python_Tornoda.util import mysqldbfrom Python_Tornoda.view.views import MainHandlerfrom Python_Tornoda.view.views import LoginHandlerfrom tornado.web import StaticFileHandlerimport oscurrent_path = os.path.dirname(__file__)class Appliction(tornado.web.Application):    def __init__(self):        handers=[            (r"/index/(?P<page>\d*)", MainHandler),            (r"/login",LoginHandler),            (r'^/(.*?)$', StaticFileHandler,{"path": os.path.join(current_path, "templates"), "default_filename": "main.html"}),        ]        super(Appliction,self).__init__(handers,**config.setting)


Views.py视图函数文件,以“登录”为示例:

from Python_Tornoda.util.bussiness import get_data,execute_sqlfrom Python_Tornoda.util.Pagination import Paginationfrom tornado.web import RequestHandlerimport timepage_num=5 #每页展示的条数#登录后的主页class MainHandler(RequestHandler):    def get(self,page):        sql1 = "select id,pms_name,content,status,mark,create_time from tornado_info order by create_time desc"        itemList = get_data(sql1)        print(page)        if(int(page)>len(itemList)//page_num):            pages=len(itemList)//page_num+1        elif(int(page)<1):            pages=1        else:            pages=int(page)        print("ad")        page_obj = Pagination(pages, len(itemList), page_num)        current_list = itemList[page_obj.start:page_obj.end]        print("00000000000")        print(current_list)        str_pageCtrl = page_obj.pageCtrl('/index/')        self.render('info.html', items=current_list, current_page=page_obj.currentPage, pageCtrl=str_pageCtrl, )class LoginHandler(RegisterHandler):    def set_default_headers(self):        print('-----set_default_headers:默认设置----')        self.set_header('Content-Type', 'application/json')    def initialize(self):        print("-----_initialize 初始化操作-----")        print("-----_初始化数据库连接-----")        print("-----_初始化打开文件-----")    def prepare(self):        print("-----prepare做一些准备工作-----")        print("-----加载配置项-----")    def get(self, *args, **kwargs):        print("----get 请求处理---")        print("----此处需要根据页面是get请求来进行处理---")        username=self.get_query_argument("username")        password=self.get_query_argument("password")        self.set_secure_cookie(username,password)        if(username=="1" and password=="1"):            self.redirect("/index/1")        else:            self.render('main.html')    def post(self,*args,**kwargs):        print("----post 请求处理---")        print("----此处需要根据页面是post请求来进行处理---")        username = self.get_body_argument("username")        password = self.get_body_argument("password")        self.set_secure_cookie(username, password)        if (username == "1" and password == "1"):            self.redirect("/index/1")        else:            self.render('main.html')    def write_error(self, status_code: int, **kwargs):        if(status_code==500):            self.write("the server is wrong")        elif(status_code==404):            self.write("it's not found")        else:            self.write("the other of error")    def on_finish(self):        print("----处理结束,释放资源----")        print("----释放db连接----")        print("----关闭文件句柄----")


Server.py 程序入口文件:

import tornado.ioloopimport tornado.webimport Python_Tornoda.application as appimport Python_Tornoda.config as configif __name__ == '__main__':    print("starting tornado...")    app = app.Appliction()    httpServer = tornado.httpserver.HTTPServer(app)    httpServer.bind(config.param['port'])    httpServer.start(1)    tornado.ioloop.IOLoop.current().start()


Step6:前端代码

Login.html:登录页代码

红框中可以看得到是用什么方式提交/login

Python + Tornado 框架

Index.html: 登录后的主页代码

Python + Tornado 框架


Step7:页面效果

7.1 登录页面展示如下:

Python + Tornado 框架

7.2 登录后主页面展示如下:

Python + Tornado 框架

备注:页面虽然有些简陋,但麻雀虽小,五脏俱全。哈哈~

版权声明:内容来源于互联网和用户投稿 如有侵权请联系删除

本文地址:http://0561fc.cn/69090.html