flask之聊天室

1,数据库数据库连接池

DBUtils- Python数据库连接池

创建数据库连接池:

 1 import time
 2 import pymysql
 3 import threading
 4 from DBUtils.PooledDB import PooledDB, SharedDBConnection
 5 POOL = PooledDB(
 6     creator=pymysql,  # 使用链接数据库的模块
 7     maxconnections=6,  # 连接池允许的最大连接数,0和None表示不限制连接数
 8     mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
 9     maxcached=5,  # 链接池中最多闲置的链接,0和None不限制
10     maxshared=3,  # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
11     blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
12     maxusage=None,  # 一个链接最多被重复使用的次数,None表示无限制
13     setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
14     ping=0,
15     # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
16     host='127.0.0.1',
17     port=3306,
18     user='root',
19     password='123',
20     database='pooldb',
21     charset='utf8'
22 )

 

 
View Code

使用数据库连接池:

 

 1 def func():
 2     # 检测当前正在运行连接数的是否小于最大链接数,如果不小于则:等待或报raise TooManyConnections异常
 3     # 否则
 4     # 则优先去初始化时创建的链接中获取链接 SteadyDBConnection。
 5     # 然后将SteadyDBConnection对象封装到PooledDedicatedDBConnection中并返回。
 6     # 如果最开始创建的链接没有链接,则去创建一个SteadyDBConnection对象,再封装到PooledDedicatedDBConnection中并返回。
 7     # 一旦关闭链接后,连接就返回到连接池让后续线程继续使用。
 8     conn = POOL.connection()
 9 
10     cursor = conn.cursor()
11     cursor.execute('select * from tb1')
12     result = cursor.fetchall()
13     conn.close()

 

 
View Code

 

二,websocke 协议

1,http:

 

轮训:

客服端一直发送请求,服务端一直收请求,直到服务端给客户端响应

优点:响应及时

缺点:消耗两端资源,非常严重,占用大量带宽

 

长轮训:

客户端发起请求,服务受到请求,内部进行轮训等待

优点:响应及时,节省资源,不会一直发送请求和响应

缺点:服务器资源消耗

 

 2websocket

 web +socket

 新的协议:该收收,该发发,该干什么干什么,响应及时,节省资源,内部实现还是轮训

 通过websocket协议进行连接

 连接成功之后,可以自由收发信息

 

简单通讯

 

在网页上

 

多人聊天

Ws.html

 

Websocket_flask.py

 

单聊和群聊 带标识

群聊

Ws.html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body>

你是谁:<input type="text" id="username">

<button id="create_ws" onclick="go_to()">创建ws连接</button>

<div style="width: 400px; height: 300px;" id="chat_window">

 

</div>

<div>

    <input type="text" id="send_msg">

    <button id="btn_send">发送消息</button>

</div>

</body>

<script type="application/javascript">

    var ws_url = "ws://192.168.12.111:9527/ws/";

    var ws = null;

 

    function go_to() {

        var username = document.getElementById("username");

        ws = new WebSocket(ws_url + username.value);

 

        ws.onmessage = function (serv_msg) {

            msg = JSON.parse(serv_msg.data);

            create_chat("y",msg);

        };

    }

 

    function create_chat(self, content) {

        if (self == "w") {

            self = "right";

            var spantag = document.createElement("span");

            spantag.innerText = content.send_msg;

            var spantag1 = document.createElement("span");

            spantag1.innerText = ":我";

        } else {

            self = "left";

            var spantag = document.createElement("span");

            spantag.innerText = content.send_user + ":";

            var spantag1 = document.createElement("span");

            spantag1.innerText = content.send_msg;

        }

 

        var divtag = document.createElement("div");

        divtag.style = "text-align:" + self;

 

        divtag.appendChild(spantag);

        divtag.appendChild(spantag1);

        var chat_window = document.getElementById("chat_window");

        chat_window.appendChild(divtag);

    }

 

    document.getElementById("btn_send").addEventListener("click", function () {

        var send_msg = document.getElementById("send_msg");

        ws.send(send_msg.value);

        var s_msg = {send_msg:send_msg.value};

        create_chat("w", s_msg);

        send_msg.value = "";

    })

 

</script>

</html>
View Code

Websocket_flask.py

from flask import Flask, request, render_template

from geventwebsocket.websocket import WebSocket

from geventwebsocket.websocket import WebSocketError

from geventwebsocket.handler import WebSocketHandler

from gevent.pywsgi import WSGIServer

 

import json

 

app = Flask(__name__)

 

 

@app.route("/index")

def index():

    return render_template("ws.html")

 

 

user_socket_list = []

user_socket_dict = {}

 

 

@app.route("/ws/<username>")

def ws(username):

    user_socket = request.environ.get("wsgi.websocket")  # type:WebSocket

    if not user_socket:

        return "请使用WebSocket方式连接"

    user_socket_dict[username] = user_socket

    print(user_socket_dict)

    while True:

        try:

            user_msg = user_socket.receive()

            for user_name, u_socket in user_socket_dict.items():

                who_send_msg = {

                    "send_user": username,

                    "send_msg": user_msg

                }

                if user_socket == u_socket:

                    continue

                u_socket.send(json.dumps(who_send_msg))

        except WebSocketError as e:

            user_socket_dict.pop(username)

            print(user_socket_dict)

            print(e)

 

 

if __name__ == '__main__':

    # app.run("0.0.0.0",9527,debug=True)

    http_serv = WSGIServer(("0.0.0.0", 9527), app, handler_class=WebSocketHandler)

    http_serv.serve_forever()
View Code

单聊

Websocket_flask.py

from flask import Flask, request, render_template

from geventwebsocket.websocket import WebSocket

from geventwebsocket.websocket import WebSocketError

from geventwebsocket.handler import WebSocketHandler

from gevent.pywsgi import WSGIServer

 

import json

 

app = Flask(__name__)

 

 

@app.route("/index")

def index():

    return render_template("ws.html")

 

 

user_socket_list = []

user_socket_dict = {}

 

 

@app.route("/ws/<username>")

def ws(username):

    user_socket = request.environ.get("wsgi.websocket")  # type:WebSocket

    if not user_socket:

        return "请使用WebSocket方式连接"

 

    user_socket_dict[username] = user_socket

    print(user_socket_dict)

    while True:

        try:

            user_msg = user_socket.receive()

            user_msg = json.loads(user_msg)

            to_user_socket = user_socket_dict.get(user_msg.get("to_user"))

            send_msg = {

                "send_msg":user_msg.get("send_msg"),

                "send_user":username

            }

 

            to_user_socket.send(json.dumps(send_msg))

        except WebSocketError as e:

            user_socket_dict.pop(username)

            print(user_socket_dict)

            print(e)

 

 

 

if __name__ == '__main__':

    # app.run("0.0.0.0",9527,debug=True)

    http_serv = WSGIServer(("0.0.0.0", 9527), app, handler_class=WebSocketHandler)

    http_serv.serve_forever()
View Code

Ws.html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body>

你是谁:<input type="text" id="username">

给谁发:<input type="text" id="to_user">

<button id="create_ws" onclick="go_to()">创建ws连接</button>

<div style="width: 400px; height: 300px;" id="chat_window">

 

</div>

<div>

    <input type="text" id="send_msg">

    <button id="btn_send">发送消息</button>

</div>

</body>

<script type="application/javascript">

    var ws_url = "ws://192.168.12.111:9527/ws/";

    var ws = null;

    //    ws.onopen = function () {

    //        ws.send("你好!")

    //    };

    function go_to() {

        var username = document.getElementById("username");

        ws = new WebSocket(ws_url + username.value);

 

        ws.onmessage = function (serv_msg) {

            msg = JSON.parse(serv_msg.data);

            create_chat("y",msg);

        };

    }

 

 

    function create_chat(self, content) {

        if (self == "w") {

            self = "right";

            var spantag = document.createElement("span");

            spantag.innerText = content.send_msg;

            var spantag1 = document.createElement("span");

            spantag1.innerText = ":我";

        } else {

            self = "left";

            var spantag = document.createElement("span");

            spantag.innerText = content.send_user + ":";

            var spantag1 = document.createElement("span");

            spantag1.innerText = content.send_msg;

        }

 

        var divtag = document.createElement("div");

        divtag.style = "text-align:" + self;

 

        divtag.appendChild(spantag);

        divtag.appendChild(spantag1);

        var chat_window = document.getElementById("chat_window");

        chat_window.appendChild(divtag);

    }

 

    document.getElementById("btn_send").addEventListener("click", function () {

        var send_msg = document.getElementById("send_msg");

        var to_user = document.getElementById("to_user");

        send_msg_json = {

            send_msg:send_msg.value,

            to_user :to_user.value

        };

        ws.send(JSON.stringify(send_msg_json));

 

        var s_msg = {send_msg:send_msg.value};

        create_chat("w", s_msg);

        send_msg.value = "";

    })

 

</script>

</html>
View Code

 

补充flask---send_file   ,  jsonify(标准格式的字符串)

 

 

posted @ 2018-08-22 15:33  嘿,  阅读(407)  评论(0编辑  收藏  举报