admin管理员组

文章数量:1558103

Python实现 版本检测 软件在线更新 在线下载(Python simple implementation of software online update and download)

文章由生化环材转载自博客园 @我超怕的 Python实现在线版本检测自动更新,转载请注明出处。

简易版-消息窗口GUI
import tkinter.messagebox
import requests
VERSION_NOW='100'#1.0.0
UPDATE_DOWNLOAD_URL='http://www.url/a.zip' #新版本文件
VERSION_URL='http://www.url/version'#最新版本号

try:
    ver=request.get(VERSION_URL)#获取最新版本号
   #然后自己根据版本号对版本进行对比处理
    #这里省略
    #直接跳到更新代码
    tkinter.messagebox.showwarning(title='提示', message='发现新版本,点击确定开始更新。更新时间跟网速有关,请耐心等待!')
    newFile=requests.get(UPDATE_DOWNLOAD_URL)
        with open("newFile_update.zip","wb") as fp:
            fp.write(newFile.content)
except:
    tkinter.messagebox.showwarning(title='警告', message='更新失败,请检查网络!')
tkinter.messagebox.showwarning(title='提示', message='新版本软件下载完成!请在当前软件目录查看(文件名:newFile_update.zip)并使用新版本。') 
完整版-无GUI

客户端

import requests
import os

c_version = '1.5.3' 
def get_new_app(version_new):
    url = 'http://1.2.3.4/new/app'
    try:
        resp = requests.get(url)
        resp.encoding = 'UTF-8'
        if resp.status_code == 200:
            with open('程序名{}.py'.format(version_new), "wb") as file: 
                file.write(resp.content)
            return True
        else:
            print('【版本更新】服务器连接失败')
            return False
    except Exception as e:
        print('【版本更新】网络错误'+str(e))
        return False
    
# 检查客户端版本
def check_update():
    try:
        url = 'http://1.2.3.4/version'
        resp = requests.get(url)
        resp.encoding = 'UTF-8'
        if resp.status_code != 200:
            print('【版本检测】服务器连接失败')
            return False
        if resp.text == c_version:
            print('【版本检测】客户端版本正常')
            return True
        
        print('【版本检测】客户端版本过低,正在自动下载最新版:{}'.format(resp.text))
        if get_new_app(resp.text):
            print('【版本检测】最新版下载成功,文件名为程序名V{},请使用最新版本!'.format(resp.text))   
             #删除旧版本 
            if os.path.isfile('程序名V{}.py'.format(c_version)):
                os.remove('程序名V{}.py'.format(c_version))
        return False
    except Exception as e:
        print('【版本检测】网络错误')
        return False
 
# 开始运行
def run():
    # 检查客户端版本
    if not check_update():
        input()
        return
    print('程序运行结束')
    input()

服务端

from flask import Flask,request,send_file


n_version = '1.5.3'
app = Flask(__name__)

# 版本查询
@app.route('/version',methods=['GET'])
def freeze_vaersion():
    return n_version

# 获取最新文件
@app.route('/new/app',methods=['GET'])
def freeze_new_app():
    # 新版本文件路径
    file_path="D:/xxx/新版本程序名V{}.py".format(n_version)
    return send_file(file_path)


if __name__ == '__main__':
    app.run(host='0.0.0.0',port=80,debug=False)

本文标签: 在线版本Python