服务端代码

我们需要做以下几个步骤:

  1. 导入所需的库。
  2. 设置 Flask 应用程序。
  3. 创建一个路由来处理 GET 请求。
  4. 在路由中执行上述代码逻辑,并返回时间字符串。

下面是封装后的 Flask 应用程序代码:

from flask import Flask, jsonify
import gitlab
import datetime

app = Flask(__name__)

# GitLab URL
GITLAB_URL = "https://your-gitlab-instance.com"
# GitLab 个人访问令牌
GITLAB_TOKEN = "your-personal-access-token"
# GitLab 项目路径
PROJECT_PATH = "user/ntp-time-sync"
# 文件名
FILE_NAME = "time.txt"
# 分支名称
BRANCH_NAME = "main"

@app.route('/get-time', methods=['GET'])
def get_time():
    # 创建 GitLab API 客户端
    gl = gitlab.Gitlab(GITLAB_URL, private_token=GITLAB_TOKEN)
    gl.auth()

    # 获取项目
    project = gl.projects.get(PROJECT_PATH)

    # 获取当前系统时间
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    # 创建或更新文件
    try:
        # 尝试获取现有文件
        file = project.files.get(file_path=FILE_NAME, ref=BRANCH_NAME)
    except gitlab.exceptions.GitlabGetError as e:
        # 如果文件不存在,则创建新文件
        file = project.files.create(
            {
                "file_path": FILE_NAME,
                "branch": BRANCH_NAME,
                "content": current_time,
                "commit_message": "Add time.txt",
            }
        )
    else:
        # 如果文件存在,则更新文件内容
        file.content = current_time
        file.save(branch=BRANCH_NAME, commit_message="Update time.txt")

    # 返回时间字符串
    return jsonify({"time": current_time})

if __name__ == '__main__':
    app.run(debug=True)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
解释:
  • Flask 应用初始化:我们首先导入 Flask 并创建一个 Flask 实例。
  • 路由定义:我们定义了一个路由 /get-time,它响应 GET 请求。
  • 处理请求:在 get_time 函数中,我们执行了原始代码中的逻辑,包括连接到 GitLab、获取当前时间、创建或更新文件等操作。
  • 返回响应:最后,我们使用 jsonify 来返回一个 JSON 格式的响应,其中包含时间字符串。
注意事项:
  • 你需要将 GITLAB_URLGITLAB_TOKEN 替换为你自己的 GitLab 实例 URL 和个人访问令牌。
  • 确保你已经安装了 Flask 和 python-gitlab 库。可以通过 pip 安装它们:
pip install Flask python-gitlab
  • 1.
启动和测试应用:
  1. 将上面的代码保存到一个文件中,例如 app.py
  2. 在终端运行 python app.py
  3. 访问 http://localhost:5000/get-time 来测试你的服务。

客户端代码

接下来编写一个 Python 程序来调用 http://localhost:5000/get-time 获取时间,并将时间配置到 Windows 的系统时间,下面是完整步骤:

  1. 发送 HTTP GET 请求:使用 requests 库来发送 HTTP GET 请求。
  2. 解析响应:从响应中解析出时间字符串。
  3. 设置 Windows 系统时间:使用 subprocess 库来调用 Windows 的 wmic 命令行工具来设置系统时间。

下面是完整的 Python 程序示例:

import requests
import subprocess
import datetime

def get_time_from_server():
    # 发送 GET 请求
    response = requests.get("http://localhost:5000/get-time")
    if response.status_code == 200:
        # 解析 JSON 响应
        data = response.json()
        time_str = data.get("time")
        if time_str:
            return time_str
    return None

def set_windows_system_time(time_str):
    # 将时间字符串转换为 datetime 对象
    dt = datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
    # 格式化为 Windows 所需的格式
    wmic_time_format = dt.strftime("%Y-%m-%d %H:%M:%S.000")
    # 使用 wmic 命令设置系统时间
    subprocess.run(["wmic", "os", "set", f"localdatetime='{wmic_time_format}'"], check=True)

def main():
    # 获取时间
    time_str = get_time_from_server()
    if time_str:
        # 设置系统时间
        set_windows_system_time(time_str)
        print("System time updated successfully.")
    else:
        print("Failed to get time from server.")

if __name__ == "__main__":
    main()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
解释:
  • get_time_from_server 函数:发送 GET 请求到 http://localhost:5000/get-time 并解析响应中的时间字符串。
  • set_windows_system_time 函数:接收时间字符串,格式化为 Windows 所需的格式,并使用 wmic 命令设置系统时间。
  • main 函数:调用上述两个函数并处理流程。
注意事项:
  • 你需要确保 requests 库已经安装。如果没有安装,可以通过 pip 安装:
pip install requests
  • 1.
  • 运行此脚本需要管理员权限,因为更改系统时间通常需要管理员权限。
  • 使用 wmic 命令来设置系统时间可能需要在 Windows 终端中以管理员权限运行此脚本。
运行脚本
  1. 保存上述代码到一个 .py 文件,例如 set_system_time.py
  2. 在命令提示符或 PowerShell 中以管理员权限运行该脚本:
python set_system_time.py
  • 1.
总结

这个脚本将会调用 http://localhost:5000/get-time 获取时间,并将时间设置为 Windows 的系统时间。