潭州课堂25班:Ph201805201 tornado 项目 第十一课 项目改进和优化(课堂笔记)

使用  Bootstrap 前端框架

可以在 bootCDN 这里找 jquery ,poppe.js 文件

当聊天室发来一第图片链接时,自动保存图片到服务器,并保存相关信息到数据库,系统向该用户发出扑救 信息

class ChatWebsocket(tornado.websocket.WebSocketHandler, AuthBaseHandler):
"""处理 Websocket 连接"""
walters = set() # 去除网络中重复的请求
history = [] # 存放历史信息
history_size = 10 # 消息列表的大小

def open(self):
# print('websocket opened')
ChatWebsocket.walters.add(self)

def on_message(self, message):
p = tornado.escape.json_decode( message ) # 解码成为字典
body = p['body']
if body and ( body.startswith('http://') or body.startswith('https://') ):
client = AsyncHTTPClient()
save_api_url = 'http://47.107.171.155:8000/sa?save_url={}&name={}'.format( body, self.current_user )
IOLoop.current().spawn_callback( client.fetch, save_api_url ) # 不会等待结果
chat = ChatWebsocket.make_chat(
body='图片链接{}正在下载。'.format( body )
)
html = self.render_string('message.html', message = chat) # 渲染 message.html 页面
msg = {
'html':tornado.escape.to_basestring( html ),
'id':chat['id']
}
self.write_message( msg )
else:
chat = ChatWebsocket.make_chat(
p['body'],
self.current_user
)
html = self.render_string('message.html', message = chat) # 渲染 message.html 页面
msg = {
'html':tornado.escape.to_basestring( html ),
'id':chat['id']
}
ChatWebsocket.update_history( msg )
ChatWebsocket.send_update( msg )

@classmethod
def make_chat(cls, body, name='系统信息', img_url='' ):
chat = {
'id' : str(uuid.uuid4()),
'body': body,
'name': name,
'img_url': img_url
}
return chat

@classmethod
def update_history(cls, msg):
"""更新消息列表"""
ChatWebsocket.history.append(msg)
if len(ChatWebsocket.history) > ChatWebsocket.history_size:
ChatWebsocket.history = ChatWebsocket.history[ChatWebsocket.history_size:]

@classmethod
def send_update(cls, msg):
"""发送信息给所有用户"""
for w in ChatWebsocket.walters:
w.write_message(msg)

def on_close(self):
ChatWebsocket.walters.remove(self)

当图片保存成功后,系统要向聊天室的所有人发信息提示,


class AyncSaveHandler(AuthBaseHandler):
"""异步版本保存 URL"""
@coroutine
def get(self, *args, **kwargs):
save_url = self.get_argument('save_url', None)
name = self.get_argument('name', '')
client = AsyncHTTPClient()

# res = requests.get(save_url)
res = yield client.fetch(save_url, request_timeout=20)
uim = UploadImg('a.jpg', self.settings['static_path'])
uim.save_upload(res.body)
uim.save_thumb()

# post = add_post_for(self.current_user, uim.upload_url, uim.thumb_url)
post = add_post_for(name, uim.upload_url, uim.thumb_url)
chat = ChatWebsocket.make_chat(
'用户 ' + name + '{}http://47.107.171.155:8000/post/{}'.format('上传了图片', post.id ),
img_url=uim.thumb_url
)
html = self.render_string( 'message.html', message=chat ) # 渲染 message.html 页面
msg = {
'html': tornado.escape.to_basestring( html ),
'id': chat['id']
}

ChatWebsocket.send_update( msg )

猜你喜欢

转载自www.cnblogs.com/gdwz922/p/10527894.html