服务器端,监听服务器上某个文件夹中是否有新的文件产生,若有,就发送出去,server.py,
# -*- coding: utf-8 -*-
# !/usr/bin/python3
#服务器端监听服务器上某个文件夹中是否有新增图片,第一次用while循环
import base64
import os
import requests
def fileListener(filepath,url):
before = dict([(f, None) for f in os.listdir (filepath)])
while True:
after = dict([(f, None) for f in os.listdir (filepath)])
added = [f for f in after if not f in before]
if added:
for k in added:
if k.endswith(".jpg"):
addition_path = os.path.join(filepath,k)
with open(addition_path, 'rb') as f:
base64_data = base64.b64encode(f.read())
s = base64_data.decode()
requests.post(url, s)
print ("find file" + addition_path)
print("Added: ", ", ".join(added))
before = after
continue
if __name__ == '__main__':
img_folder='/home/jerry/shared/py_poject_wang/helmet_detect/helmet_detect_20_04_29/images_out'
url = 'http://127.0.0.1:9005/'
fileListener(img_folder,url)
缺陷,上面的监听文件用的是while循环,容易造成机器一直在这个程序中出不来,不能干其他事情,修改成用一个线程
# -*- coding: utf-8 -*-
# !/usr/bin/python3
#服务器端监听服务器上某个文件夹中是否有新增图片,第一次用while循环
import base64
import os
import requests
import threading
import time
def fileListener(filepath,url):
global pic_before
while True:
pic_temp = dict([(f, None) for f in os.listdir (filepath)])
added = [f for f in pic_temp if not f in pic_before]
if added:
for k in added:
if k.endswith(".jpg"):
addition_path = os.path.join(filepath,k)
with open(addition_path, 'rb') as f:
base64_data = base64.b64encode(f.read())
s = base64_data.decode()
requests.post(url, s)
pic_before = pic_temp
time.sleep(1)#每隔1秒查询1次
def main():
img_folder = '/home/jerry/shared/py_poject_wang/helmet_detect/helmet_detect_20_04_29/images_out'
url = 'http://127.0.0.1:9005/'
global pic_before
pic_before = dict([(f, None) for f in os.listdir(img_folder)]) # filepath中的所有文件
thread = threading.Thread(target=fileListener,
args=(img_folder, url)
)
thread.start()
if __name__ == '__main__':
main()
客户端,通过服务器接收新文件,并存储到客户端client.py
# -*- coding: utf-8 -*-
# !/usr/bin/python3
#客户端,将每次监听到的新文件保存下来
from flask import Flask, request
import base64
import os
import shutil
import time
image_save_path='./no_helmet_persons'#没有带安全帽的人的存放路径
app = Flask(__name__)
def mkr(path,delete_old=False):
if os.path.exists(path):
if delete_old:
shutil.rmtree(path)
os.mkdir(path)
else:
os.mkdir(path)
@app.route("/", methods=['POST', 'GET'])
def hello():
global person_num
result_dict = request.get_data()
filename=image_save_path+'/'+str(time.time())+'.jpg' #以存储时间命名
with open(filename, 'wb') as f:
f.write(base64.b64decode(result_dict))
return "OK"
if __name__ == "__main__":
mkr(image_save_path, delete_old=True)
app.run(host="127.0.0.1", port="9005") # 注意端口号与技能运行时配置中的保持一致