参数:
file_path:待上传文件的地址,远程文件名称也会取该文件名称
target_path:上传到远程仓库内的地址,默认是根目录
owner:用户名,即仓库地址gitee.com/后面的内容
repo_path:远程仓库路径,即第一步提到的路径,即仓库地址最后的内容
access_token:第一步获取的私人令牌
该函数可以实现将本地文件上传至指定的远程仓库,如果该文件已经存在就更新文件
import base64
import os
import requests
def upload_file(file_path, target_path='',owner = "", repo_path = "",access_token = "",message="upload file"):
base_url = "https://gitee.com/api/v5/repos/"
try:
with open(file_path, "rb") as file:
file_content = base64.b64encode(file.read()).decode("utf-8")
filename = os.path.basename(file_path)
target_path = os.path.join(target_path, filename)
data = {
"access_token": access_token,
"message": message,
"content": file_content,
}
api_url = base_url + owner + "/" + repo_path + "/contents/" + target_path
response = requests.post(api_url, data=data)
# 如果文件已存在,尝试使用更新API
if response.status_code == 400:
update_data = {
"access_token": access_token,
"content": file_content,
"sha": "", # 在获取文件内容API中获取,先设置为空字符串
"message": "update file", # 可以自定义
}
# 获取文件的信息,以获取正确的SHA值
get_file_url = (
f"https://gitee.com/api/v5/repos/{owner}/{repo_path}/contents/{target_path}"
)
get_file_response = requests.get(
get_file_url, params={"access_token": access_token}
)
if get_file_response.status_code == 200:
sha_value = get_file_response.json().get("sha", "")
update_data["sha"] = sha_value
# 使用正确的SHA值进行更新
update_url = f"https://gitee.com/api/v5/repos/{owner}/{repo_path}/contents/{target_path}"
response = requests.put(update_url, data=update_data)
# 检查最终的响应状态码
response.raise_for_status()
return response
except Exception as e:
return f"错误:{str(e)}"
# 示例用法
if __name__ == "__main__":
upload_file("D:\\test.txt")
依赖安装:(显示下载进度)
pip install tqdm
代码:
需要assess_token的版本:(20240527更新,可以下载最大100MB的文件)
参数:
remote_path:远程文件在仓库中的地址
save_path:文件保存目录
owner:用户名,即仓库地址gitee.com/后面的内容
repo_path:远程仓库路径,即第一步提到的路径,即仓库地址最后的内容
overwrite:是否覆盖下载,默认不覆盖
access_token:私人令牌
from tqdm import tqdm
import os
import requests
import random
from pathlib import Path
# 保存到D:downloads目录下
def download_file(
name,
save_path="D:\\downloads",
repo_path="",
owner="",
access_token="",
overwrite=False,
):
url = f"https://gitee.com/api/v5/repos/{owner}/{repo_path}/raw/{name}?random={str(random.randint(1, 1000))}"
try:
# 构造文件的完整路径
file_name = os.path.basename(name)
file_path = Path(os.path.join(save_path, file_name))
# 检查远程文件是否存在
head_response = requests.head(
url,
params={
"access_token": access_token,
},
)
if head_response.status_code != 200:
print(f"远程文件丢失,更新失败: {head_response.status_code}")
return False
# 检查本地文件是否已经存在
if not overwrite and file_path.exists():
print(f"文件 '{file_name}' 已存在,将不再下载。")
return True
# 发起HTTP请求
response = requests.get(
url,
stream=True,
params={
"access_token": access_token,
},
)
# 获取文件总大小
total_size = int(response.headers.get("content-length", 0))
# 设置进度条
block_size = 1024 # 1 KB
progress_bar = tqdm(
total=total_size,
unit="B",
unit_scale=True,
unit_divisor=1024,
miniters=1,
desc="Downloading",
)
# 保存文件到桌面
with open(file_path, "wb") as file:
for data in response.iter_content(block_size):
progress_bar.update(len(data))
file.write(data)
# 关闭进度条
progress_bar.close()
print(f"{file_name}已下载到{save_path}")
return True
except Exception as e:
print(f"下载失败: {e}")
return False
# 示例代码
if __name__ == "__main__":
# 可以下载不超过100MB的文件
download_file("360.exe")
直链下载版本,无需access_token,但是只能下10MB以内的文件
参数:
remote_path:远程文件在仓库中的地址
save_path:文件保存目录
owner:用户名,即仓库地址gitee.com/后面的内容
repo_path:远程仓库路径,即第一步提到的路径,即仓库地址最后的内容
overwrite:是否覆盖下载,默认不覆盖
import os
import random
import requests
from tqdm import tqdm
from pathlib import Path
def download_file(
remote_path,
save_path="D:\\downloads",
repo_path="",
owner="",
overwrite=False,
):
url = f"https://gitee.com/{owner}/{repo_path}/raw/master/{remote_path}?random={str(random.randint(1, 1000))}"
try:
file_name = os.path.basename(remote_path)
file_path = Path(os.path.join(save_path, file_name))
head_response = requests.head(url)
if head_response.status_code != 200:
print(f"远程文件丢失,更新失败")
return False
if not overwrite and file_path.exists():
print(f"文件 '{file_name}' 已存在,将不再下载。")
return True
response = requests.get(url, stream=True)
total_size = int(response.headers.get("content-length", 0))
block_size = 1024 # 1 KB
progress_bar = tqdm(
total=total_size,
unit="B",
unit_scale=True,
unit_divisor=1024,
miniters=1,
desc="Downloading",
)
with open(file_path, "wb") as file:
for data in response.iter_content(block_size):
progress_bar.update(len(data))
file.write(data)
progress_bar.close()
print(f"{file_name}已下载到{save_path}")
return True
except Exception as e:
print(f"下载失败: {e}")
return False
# 示例用法
if __name__ == "__main__":
download_file("hello.info")
直接获取远程文本文件的内容
例如可以用来获取公告或文档,方便远程更新
支持转义字符,例如\n \t 等,包括改变文本和背景颜色的转义字符
import os
import random
import requests
from tqdm import tqdm
from pathlib import Path
def get_remote_text(remote_path, repo_path="", owner=""):
url = f"https://gitee.com/{owner}/{repo_path}/raw/master/{remote_path}?random={str(random.randint(1, 1000))}"
try:
response = requests.get(url)
response.raise_for_status()
content = (
response.content.decode("unicode_escape")
.encode("latin1")
.decode("utf-8")
.strip()
)
return content
except requests.exceptions.RequestException as e:
return None
# 示例用法
if __name__ == "__main__":
print(get_remote_text("hello.info"))
本文是基于Python实现的,但是也可以按照文中描述的请求方法在其他语言中应用,实现类似的效果
附:Gitee API 文档链接
Gitee API 文档https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoRawPath