tornado 表单验证 套接字 长连接

manage

import tornado.web
import tornado.ioloop
from tornado_jinja2 import Jinja2Loader

from app.views import RegisterHandler, LoginHandler, HomeHandler, \
    ManyChatHandler, ChatHandler


# 配置 jinjia2 的模板语法
jinjia2loader = Jinja2Loader('templates')


def make_app():
    return tornado.web.Application(handlers=[
        (r'/register/', RegisterHandler),
        (r'/login/', LoginHandler),
        (r'/home/', HomeHandler),
        (r'/many_chat/', ManyChatHandler),
        (r'/chat/', ChatHandler),

    ],
        template_path='templates',
        static_path='static',
        cookie_secret='adsffsadfagaioewra',
        template_loader=jinjia2loader,
    )


if __name__ == '__main__':
    app = make_app()
    app.listen(8000)
    tornado.ioloop.IOLoop.current().start()

views

import tornado.web
import tornado.websocket


from app.forms import UserRegisterForm


class RegisterHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):

        self.render('register.html')

    def post(self, *args, **kwargs):
        # 使用表单做校验,校验注册的参数长度,是否为空。
        form = UserRegisterForm()
        if form.is_valid(self):
            print(form.clean_data)
            print(form.errors)
            self.write('校验成功')
        else:
            print(form.errors)
            self.write('校验失败')


class LoginHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        self.render('login.html')

    def post(self, *args, **kwargs):
        form = UserRegisterForm()
        if form.is_valid(self):
            users = ['coco123', 'caozhihua']
            if form.clean_data['account'] in users:
                # 演示模拟登录
                self.set_secure_cookie('account',
                                       form.clean_data['account'], expires_days=1)
                self.redirect('/home/')
                return
        self.render('login.html', errors=form.errors)


class HomeHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):

        self.render('home.html')


class ManyChatHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        self.render('chat.html')


class ChatHandler(tornado.websocket.WebSocketHandler):

    online_user = []

    # 建立连接时会默认调用的方法
    def open(self, *args, **kwargs):

        # 将进入聊天室的用户保存起来
        self.online_user.append(self)
        # write_message(信息), 用于将写入的信息返回给前端,前端通过on_message接收
        account = self.get_secure_cookie('account').decode('utf8')
        for user in self.online_user:
            user.write_message('系统提示:%s已登录系统' % account)

    # 前端调用send(内容),后端调用on_message方法,用于接收前端传递的数
    def on_message(self, message):

        # 将一个用户发送的消息广播给进入聊天室的用户
        for user in self.online_user:
            if user != self:
                # 给其他用户广播某个用户发送的消息
                account = self.get_secure_cookie('account').decode('utf8')
                user.write_message('{}说:{}'.format(account, message))

    # 退出连接时,主动调用
    def on_close(self):
        # 将退出聊天的用户移除online_user
        self.online_user.remove(self)
        for user in self.online_user:
            account = self.get_secure_cookie('account').decode('utf8')
            user.write_message('系统提示:{}已退出系统'.format(account))

froms

import re

class UserRegisterForm():

    def __init__(self):
        # 定义校验字段的规则
        self.account = '[0-9a-zA-Z]{5,10}'
        self.password = '[0-9]{5,10}'
        self.password2 = '[0-9]{5,10}'
        self.errors = {}
        self.clean_data = {}

    def is_valid(self, request):
        # 校验字段
        flag = True
        print(self.__dict__)
        for key, value in self.__dict__.items():

            html_value = request.get_argument(key, None)
            if html_value:
                # 正则匹配
                if not re.match(value,html_value):
                    # 表示字段不符合规则
                    self.errors[key] = '{}字段校验错误'.format(key)
                    flag = False
                self.clean_data[key] = html_value
        return flag

你可能感兴趣的:(tornado 表单验证 套接字 长连接)