记录使用flask+socket+mongodb页面P标签的刷新

1.flask的学习

     随便百度个flask入门教程熟悉一下flask的启动,路由等

2.mondodb的学习

      同1

3.socket的学习

    同1。

4.碰到的问题

   4.1socket阻塞

      使用   from threading import Thread

   4.2socket和flask启动端口/IP冲突

     app设置  threaded=True

   4.3socket多连接

   放后面代码

   4.4.index页面在一个窗口跳转

   window.location.href="http://127.0.0.1:5000/dat";

6.代码目录

   杠掉的是不需要的文件(data.html)也不需要

7.上代码

7.1runserver

from flask import Flask,render_template,request,url_for
import json
from mymongodb import MongodbHandler
from sock import Connect
from threading import Thread

app=Flask(__name__)
TEMPLATES_AUTO_RELOAD = True
SEND_FILE_MAX_AGE_DEFAULT = 0


mymo = MongodbHandler()
#sokcet
def connet():
    c=Connect()
    thread = Thread(target=c.accept_client)
    thread.setDaemon(True)
    thread.start()

# 主页面
@app.route('/', methods=['GET'])
def home():

    return render_template('file.html')

@app.route('/dat', methods=['GET'])
def dat():
    return render_template('data.html')

@app.route('/upload',methods=['GET'])
def upload():
    c = mymo.selec("temprature")
    d = mymo.selec("humidity")
    z = c.copy()
    z.update(d)
    print(json.dumps(z))
    return json.dumps(z)

if __name__ == '__main__':
    connet()
    app.run(threaded=True,debug=True)

 

7.2sock

import socket
from threading import Thread
from mymongodb import MongodbHandler
SocketHost='0.0.0.0'
SocketPort=1234


class Connect():
    g_conn_pool = {}  # 连接池
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)   #定义socket类型,网络通信,TCP
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((SocketHost,SocketPort))   #套接字绑定的IP与端口
    s.listen(10)#开始TCP监听,监听1个请求
    m = MongodbHandler()
    print("ssss")
    def accept_client(self):
        while True:
            client, info = Connect.s.accept()  # 阻塞,等待客户端连接
            # 给每个客户端创建一个独立的线程进行管理
            thread = Thread(target=Connect.recive, args=(self,client, info))
            # 设置成守护线程
            thread.setDaemon(True)
            thread.start()

    def recive(self,client, info):
            #conn,addr=client.accept()   #接受TCP连接,并返回新的套接字与IP地址
            print('Connectedby by ',info)    #输出客户端的IP地址
            quitip=info
            while 1:
                try:
                    data=client.recv(2048)    #把接收的数据实例化
                    data1=data.decode('utf-8')
                    data1=eval(data1)
                    print(type(data1))
                    print(data1)
                    Connect.m.insert_t( data1['name'],data1['value'])
                except Exception as e:
                    print(e)
                    print("quit")
                    print(quitip)
                    client.close()
                    break

 

7.3mymongodb

import pymongo
import random
'''
类名称: 	MongodbHandler
功能:		实现和mongodb数据库连接
函数:   		__init__()、insert_t()、selec()
函数实现功能: 分别实现初始化、插入一条数据、查询一条数据
特殊说明:	selec返回的是输入数据库的集合的表中的数据的value值
'''

class MongodbHandler():
	"""docstring for MongodbHandler"""
	myclient = pymongo.MongoClient("mongodb://localhost:27017/")
	mydb = myclient["test"]
	myco1 = mydb["temprature"]
	myco2 = mydb["humidity"]
	mydict1 = { "tname": "temprature", "tvalue": "0","tcounter":0 }
	mydict2 = { "hname": "humidity", "hvalue": "0","hcounter":0 }

	def __init__(self):			#如果没有创建数据库就将注释取消,然后运行一次之后重新加注释
		pass
		#MongodbHandler.myco1.insert_one(MongodbHandler.mydict1)#初始化一个初始值0
		#MongodbHandler.myco2.insert_one(MongodbHandler.mydict2)#初始化一个初始值0

	def insert_t(self,name,value):

		if name=="temprature":
			newvalues = MongodbHandler.selec(self,name)
			newvalues['tcounter']=random.randint(0,9)
			newvalues['tvalue']=value
			MongodbHandler.myco1.insert_one(newvalues)
		if name== "humidity":
			newvalues = MongodbHandler.selec(self,name)
			newvalues['hcounter']=random.randint(0,9)
			newvalues['hvalue']=value
			MongodbHandler.myco2.insert_one(newvalues)

	def selec(self,name):
		if name=="temprature":
			x = MongodbHandler.myco1.find().sort("_id", 1)
			for c in x:
				ai=c
			del ai['_id']
			return ai
		if name=="humidity":
			x = MongodbHandler.myco2.find().sort("_id", 1)
			for c in x:
				ai=c
			del ai['_id']
			return ai
		else :
			return None

 

最后添加测试文件

import socket
import time
import random
import json
'''
本文件实现的是模拟esp8266的AT指令接入互联网的功能
''' 
p = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
p.connect(('127.0.0.1', 1234))
 
while 1:
    
    msg ={'name':'temprature','value':14}
    msg['value']=random.randint(0,20)
    msg2 = {'name':'humidity','value':14}
    msg2['value']=random.randint(0,20)
    p.send(json.dumps(msg).encode('utf-8'))
    time.sleep(1)
    p.send(json.dumps(msg2).encode('utf-8'))

p.close()
		

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值