我正在尝试使用以下代码将 xlsx 文件上传到服务器,但出现 409 错误。我认为这与服务器上存在与我试图发布的同名文件这一事实有关吗?如果文件存在,我基本上只想覆盖它?
import uuid
import requests
import io
import json
import os
import time
from datetime import datetime
import configparser
print("Employee Rate Files")
config = configparser.ConfigParser()
config.read('configUKG_EmployeeRate.ini')
lastRunFilename = config.get('DEFAULT','lastRunFilename')
host = config.get('DEFAULT','host')
remoteLocation = config.get('DEFAULT','remoteLocation')
path = config.get('DEFAULT','path')
token = config.get('DEFAULT','token')
print("(d_EmpRate) LastRunFileName = " + lastRunFilename)
print("(d_EmpRate) Path test = " + path)
enconding_var = "utf-8"
# Cut slashes at the end of paths if they are exist
if path[-1] == '\\':
path = path[:-1]
if remoteLocation[-1] == '\/':
remoteLocation = remoteLocation[:-1]
#Function to compare stored and file last modified time
def compareModificationTime(filePath):
print("bbb " + str(filePath in lastRunTime))
print("filepath " + filePath)
print("last rt " + str(lastRunTime))
print("os get time " + str(os.path.getmtime(filePath)))
print("new dt " + datetime.utcfromtimestamp(os.path.getmtime(filePath)).strftime('%c'))
print("last rt int from file " + str(lastRunTime.get(filePath)))
if (filePath in lastRunTime and os.path.getmtime(filePath)>int(lastRunTime.get(filePath))) or (filePath not in lastRunTime):
print("(d_EmpRate) In compareModificationTime FileName true" + filePath)
return True
else:
print("(d_EmpRate) In compareModificationTime FileName false" + filePath)
os.remove(filePath)
print("(d_EmpRate) Removing file: " + filePath)
return False
# Function to upload file to Droppy via Sisense API
def uploadFile (content, fileName, folderPath):
if folderPath != path:
remotePath = remoteLocation + folderPath.replace(path,'')
else:
remotePath = remoteLocation
url = host +'/app/explore/!/upload?vId=0&rename=0&to=/'+remotePath
boundary = str(uuid.uuid4())
LF = "\r\n";
header = {'Authorization': token, 'Content-Type': 'multipart/form-data; boundary=\"%s\"'%boundary}
bodyLines =[
"--%s"%boundary,
"Content-Disposition: form-data; name=\"filename\"; filename=\"%s\""%fileName,
"Content-Type: application/octet-stream"+LF,
content,
"--%s-"%boundary+LF
]
bodyLines = [x + LF for x in bodyLines]
bodyLines = ''.join(bodyLines)
r = requests.post(url, data=bodyLines, headers=header)
print(remotePath+'/'+fileName, r.status_code, r.reason)
print("(d_EmpRate) File Uploaded!")
print()
# function to upload Files to Sisense via Droppy 11.1.0
def uploadFileOld(filePath, fileName, folderPath):
if folderPath != path:
remotePath = remoteLocation + folderPath.replace(path,'')
else:
remotePath = remoteLocation
url = host +'/app/explore/!/upload?vId=0&rename=0&to=/'+remotePath
payload={}
files = [('', (fileName, open(filePath, 'rb'), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'))]
headers = {
'Authorization': token
}
r = requests.request("POST", url, headers=headers, data=payload, files=files)
print(remotePath+'/'+fileName, r.status_code, r.reason)
print("(d_EmpRate) XLS File Uploaded!")
print()
# function to upload Files to Sisense via File Browser 2.10.0
def uploadFileNew(filePath, fileName, folderPath):
print("in uploadnew")
if folderPath != path:
remotePath = remoteLocation + folderPath.replace(path,'')
print(remotePath)
else:
remotePath = remoteLocation
print(remotePath)
url = host + '/app/explore/api/resources' + remotePath.replace('\\','/') +'/' + fileName
print(url)
payload=open(filePath, 'rb')
xToken = getXtoken()
headers = {
'Authorization': token,
'X-Auth': xToken
}
r = requests.request("POST", url, headers=headers, data=payload)
print("end on uploadFileNew " + remotePath+'/'+fileName, r.status_code, r.reason)
print("(d_EmpRate) File Uploaded!")
print()
# function to get auth tocken for File Browser 2.10.0
def getXtoken ():
url = host + "/app/explore/api/login"
payload={}
headers = {
'Authorization': token
}
response = requests.request("POST", url, headers=headers, data=payload)
return response.text
try:
f = open(lastRunFilename, "r")
timestamp = f.read()
lastRunTime = json.loads(timestamp)
except:
lastRunTime = {}
print("(d_EmpRate) In except uploadFilec {} lastruntine ".format(lastRunTime))
if ( os.path.isdir(path)):
print ("in if")
for root, subdirs, files in os.walk(path):
print ("in for 1")
for entry in os.scandir(root):
print ("in for 2")
print ("in for 2 b " + str(entry.is_file()))
print ("in for 2 b2 " + str(entry.is_file()))
if entry.is_file() and compareModificationTime(entry.path):
print ("Path *** " + entry.path)
print ("Name " + entry.name)
uploadFileNew (entry.path, entry.name, root)
lastRunTime[entry.path] = int(time.time())
time.sleep(1)
elif ( os.path.isfile(path) and compareModificationTime(path)):
f = io.open(path, mode="r", encoding="utf-8")
file = f.read()
uploadFileNew (file, os.path.basename(path))
lastRunTime[entry.path] = int(time.time())
time.sleep(1)
elif not os.path.exists(path):
print ("Specified path doesn't exist")
with open(lastRunFilename, 'w') as f:
json.dump(lastRunTime, f)
if not files:
print("(d_EmpRate) No files in Dir.")
#service_func()
else:
print("(d_EmpRate) Directory not empty.")
#service_func()
如果我删除服务器上的文件,那么下次运行此脚本时它会发布文件吗?谢谢你的帮助