最近在部署前端项目时,需要通过堡垒机将前端项目压缩包上传到应用服务器的/tmp目录下,然后进入应用服务器,使用mv命令移动压缩文件到Nginx项目设置目录,最后使用unzip命令解压文件完成项目的部署,仔细分析。大多数操作都是重复动作。手动完成这些操作会大大降低工作效率。本文将介绍如何使用Python监控文件夹,以协助完成服务的部署1.准备工作这里介绍一个Python依赖库“watchdog”,可以用来监控某个文件目录下的文件变化,包括:删除,修改,添加等,每个操作都会回调一个Event函数,我们可以在里面写自定义逻辑来满足自己的需求#安装依赖包pip3installwatchdog项目地址:https://pypi.org/project/watc...2.实战首先我们需要创建监听文件夹目录fromwatchdog.observersimportObserver...#创建监听文件夹目录observer=Observer()...然后,创建2个事件处理对象PS:该对象继承自“FileSystemEventHandler”类。它们分别用于监控“/tmp”目录和“/home/project/frontend”目录。假设事件对象名为obj1,obj2obj1负责监控/tmp目录,重写"new"或者修改事件方法,完成压缩文件的移动操作fromwatchdog.eventsimport*importntpathimportshutilimportzipfiledefget_filename(filepath):"""根据文件夹目录,获取文件名(需加后缀):paramfilepath::return:"""returnntpath.basename(filepath)classFileMoveHandler(FileSystemEventHandler):def__init__(self):FileSystemEventHandler.__init__(self)...#文件创建defon_created(self,event):#新文件夹ifevent.is_directory:ent{#print("directoryev"createdform:.src_path))pass#newfileelse:#print("filecreated:{0}".format(event.src_path))filename=get_filename(event.src_path)#开始4个压缩文件ifpackage片段的操作iffilenameinwatch_tags:self.start(filename)...defon_modify(seld,event):ifevent.is_directory:#Print("DirectorModified:{0}".Src_pathElse:#Print("FileModify:{0}".格式(event.src_path)filename=get_filename(event.src_path)iffilenameinwatch_tags:set)...:"""Fileprocessinglogic:ParamFilename::Return:"""Try:#filenamewithoutsuffixfirst_without_suffix=filename.split(".")#Sourcefilepath(compressedpackagefile)source_file_path=watchamider+filed+fireder.文件路径(压缩包文件)????????????target_file_path?=?target_folder?+?filename????????????#?目标项目文件夹(目标项目)????????????target_project_path?=?target_folder?+?filename_without_suffix????????????#?1、复制文件到目标文件夹????????????print(f"拷贝源目录{source_file_path},目标文件夹:{target_folder}")#deletethecompressedfileunderthetargetfolderifom.path.exists(target_file_path):os.remove(target_file_path)#mobilefiletothedealer.move(source_file_path,target_path_path.Allfoldersinthetargetfolder(iftheyexist)#Ifitdoesnotexist,createanewfolderifos.path.exists(target_project_path):shutil.rmtree(target_project_path,ignore_errors=True)f"file(nameproject_without_suffix}移动成功!")exceptExceptionase:print("Deploymentfailed,errorreason:",str(e.args))obj2负责监控/home/project/frontend目录,同时重写了"newormodified"事件方法完成压缩文件解压动作...defstart(self,filename):#不带后缀的文件名filename_without_suffix=filename.split(".")[0]#目标文件路径(压缩包文件)target_file_path=target_folder+projectfilename((target_project_path)=target_folder+filename_without_suffixr=zipfile.is_ipfile(target_file_path)如果r:fz=zipfile.zipfile(target_file_path,target_file_)else:print('Thisisnotanormalziparchive!')...然后,通过listenerimporttime启动上述两个事件的监听任务...if__name__=="__main__":#待监听文件夹目录watch_folder="/tmp/"#项目目标文件夹直接orytarget_folder="/home/project/frontend/"#监控文件夹名称,即:项目压缩包名称watch_tags=['proj1.zip','proj2.zip','proj3.zip','proj4.zip']#创建监听文件夹目录observer=Observer()#创建两个事件处理对象move_handler=FileMoveHandler()unzip_handler=FileUnzipHandler()#开始监听task#参数有:observer,监控目录,是否监控子目录observer.schedule(move_handler,watch_folder,True)observer.schedule(unzip_handler,target_folder,True)observer.start()try:whileTrue:time.sleep(1)exceptKeyboardInterrupt:observer.stop()observer.join()...最后,我们在服务端传递“nohup”命令,让文件监听器在后台运行#Runinthebackground#Projectfile:watch_folder.py#日志文件:watch_folder.lognohuppython3-uwatch_folder.py>watch_folder.log2>&1查看日志:catwatch_folder.log3.总结通过以上操作,我每次压缩前端zip通过堡垒机上传项目文件到应用服务器的/tmp目录下,t程序会自动执行以下操作,自动完成应用部署。以上就是本次分享的全部内容。觉得文章还不错的话,请关注公众号:Python编程学习圈,每日干货分享,发送“J”还能领取大量学习资料。或者去编程学习网了解更多编程技术知识。
