I have the following code in C# that I need to convert into Python.
Code in C#:
{
var fileName = new FileInfo(file);
string requestString = "url to be used"
var request = (HttpWebRequest)WebRequest.Create(requestString);
request.KeepAlive = false;
request.AllowAutoRedirect = false;
request.Method = "POST";
request.Timeout = 50000;
var boundary = "------WebKitFormBoundaryv4JOuEW2XZeLh2TK";
byte[] startBoundaryBytes = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
string bodyHeader = "Content-Disposition: form-data; name=\"BackupFile\"; filename=\"" + fileName.Name + "\"\r\nContent-Type: application/octet-stream\r\n\r\n";
byte[] bodyHeaderBytes = Encoding.ASCII.GetBytes(bodyHeader);
byte[] trailerBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
using (var requestStream = request.GetRequestStream()) {
requestStream.Write(startBoundaryBytes, 0, startBoundaryBytes.Length);
requestStream.Write(bodyHeader2Bytes, 0, bodyHeader2Bytes.Length);
//read file and add it to request
using(var fileStream = new FileStream(fileName.FullName, FileMode.Open, FileAccess.Read)) {
var buffer = new byte[4096];
int bytesRead = 0;
do {
bytesRead = fileStream.Read(buffer, 0, buffer.Length);
if(bytesRead > 0) {
requestStream.Write(buffer, 0, bytesRead);
}
} while(bytesRead > 0);
}
//write body trailer bytes
requestStream.Write(trailerBytes, 0, trailerBytes.Length);
}
try {
var response = request.GetResponse();
using(var reader = new StreamReader(response.GetResponseStream())) {
string responseText = reader.ReadToEnd();
}
} catch (WebException e) {
...
}
What's the best way to convert this code to Python? So far I have the basics in Python, and from my searches I think I should be using requests library. But how can I add those boundary bytes as well as the file itself to the request?
Code in Python so far (really just the basic stuff, I've been trying different stuff with the requests lib but with no success at all):
url = "url_to_be_used"
fileName = "sample.sample"
boundary = "------WebKitFormBoundaryv4JOuEW2XZeLh2TK"
startBoundaryBytes = ("--" + boundary + "\r\n").encode("ascii")
bodyHeader2 = "Content-Disposition: form-data; name=\"BackupFile\"; filename=\"" + fileName + "\"\r\nContent-Type: application/octet-stream\r\n\r\n"
bodyHeader2Bytes = bodyHeader2.encode("ascii")
trailerBytes = ("\r\n--" + boundary + "--\r\n").encode("ascii")
headers = {"Content-Type": "multipart/form-data; boundary={}".format(boundary)}
Any help would be appreciated!
Thank you