I migrating code from VB.Net to python and faced a problem. In VB.Net we gets an Stream object and write some data there, but i cant find likely methods in python.
VB.Net code
Dim myRequest As System.Net.HttpWebRequest = DirectCast(Net.WebRequest.Create(URLString), Net.HttpWebRequest)
myRequest.Timeout = 6000
myRequest.Method = "POST"
myRequest.KeepAlive = True
Dim pS As String = """"
Dim boundary As String = "boundStr"
myRequest.ContentType = "multipart/form-data; boundary=" + boundary
myRequest.Headers.Add(Net.HttpRequestHeader.Authorization, "Bearer " + access_token)
Console.WriteLine(myRequest.Headers)
Dim stream As System.IO.Stream = myRequest.GetRequestStream()
After we write some information about excel file into a stream and write a file there.
I tried to find somethink in requests docs but i found only read examples
Related
i'm not a expert in python and it's my fist post in stack overflow.
Maybe you can help me
I try to use python instead of vba to create document for a specific application.
This application is used to configure Programmable RTUs
It is possible to automate the creation of documents via excel by activating in excel a reference to this specific application.
This is a exemple to add a specific tag to a exsisting timer in a document with VBA in Excel
Sub timer()
Dim TWsdoc As TWinSoft.Document
Dim MyTag As TWinSoft.Tagname
Dim file_path As String
file_path = ThisWorkbook.Path
Set TWsdoc = GetObject("/RTU:MS32S2", "TWinSoft.Document")
Set TWsdoc = GetObject(file_path & "\test.tws")
Dim MyTimer As TWinSoft.OSCTimer
Set MyTimer = TWsdoc.OSCTimers("Timer_1")
'add Status Tag in Timer_1
Set MyTimer.Status = TWsdoc.Tagnames("Timer_1_State")
TWsdoc.Save 'save the document
Set TWsdoc = Nothing
End Sub
This is the python code i use to:
Creat a tag (status) with soms parameter
creat a timer (Timer 1)
try to associate timer status to a timer
and save the document
I use Visual Studio Code
THE problem, i can not associate the tag Timer_1_Status to the Timer_1 like in vba
I always have this error
Une exception s'est produite : AttributeError Property
'.Status' can not be set.
from multiprocessing import context
import win32com.client #need pywin32 (pip install pywin32)
import os, os.path
file = "\\test.tws"
file_path = os.path.dirname(os.path.abspath(__file__))
file_path = file_path + file
twdoc = win32com.client.Dispatch('Twinsoft.Document')
#-----------Creat Timer Status Tag-----------------
tagTimer1Sta=twdoc.AddTag('Timer_1_Status','DIV')
tagTimer1Sta.comment = 'Timer 1 Status'
tagTimer1Sta.ModbusAddress = 5000
#-----------Creat Timer-----------------
twdoc.AddOSCTimer("Timer_1")
#----------Associate Timer Status Tag to Timer
mytimer = twdoc.OSCTimers("Timer_1")
mytimer.Status = twdoc.Tagnames(tagTimer1Sta)
#-----------Save the created tws Document-----------------------
twdoc.SaveAs(file_path)
I thank you in advance for your help and I apologize for the bad English that I write, I am French.....
Yvan
I have written the following VBA code to automate SAS processes.
Rem Start the SAS server
Dim SASws As SAS.Workspace
Dim SASwsm As New SASWorkspaceManager.WorkspaceManager
Dim strError As String
Set SASws = SASwsm.Workspaces.CreateWorkspaceByServer _
("MySAS", VisibilityProcess, Nothing, "", "", strError)
Dim code_location As String, code_name As String, param_str As String
Dim param_flag As Boolean
code_location = "file:" & ThisWorkbook.Sheets("Control").Range("B2").Value
code_name = ThisWorkbook.Sheets("Control").Range("C2").Value
param_flag = ThisWorkbook.Sheets("Control").Range("C4").Value
If param_flag = True Then
param_str = ThisWorkbook.Sheets("Control").Range("D5").Value
Else: param_str = "ds=Sasuser.Export_output"
End If
Rem Run the stored process
Dim SASproc As SAS.StoredProcessService
Set SASproc = SASws.LanguageService.StoredProcessService
SASproc.Repository = code_location
SASproc.Execute code_name, "ds=Sasuser.Export_output"
'SASproc.Repository = "file:C:\Duopa_Repository\SAS_Codes\Weekly"
'SASproc.Execute "weekly_refresh_run.sas", "ds=Sasuser.Export_output"
Rem Shut down the SAS server
SASwsm.Workspaces.RemoveWorkspaceByUUID SASws.UniqueIdentifier
SASws.Close
Set SASws = Nothing
All the SAS codes seem to work through this except the ones that import csv files using proc import method. Can someone please explain me why
Thanks in advance
So I have a specific need to download and extract a cab file but the size of each cab file is huge > 200MB. I wanted to selectively download files from the cab as rest of the data is useless.
Done so much so far :
Request 1% of the file from the server. Get the headers and parse them.
Get the files list, their offsets according to This CAB Link.
Send a GET request to server with the Range header set to the file Offset and the Offset+Size.
I am able to get the response but it is in a way "Unreadable" cause it is compressed (LZX:21 - Acc to 7Zip)
Unable to decompress using zlib. Throws invlid header.
Also I did not quite understand nor could trace the CFFOLDER or CFDATA as shown in the example cause its uncompressed.
totalByteArray =b''
eofiles =0
def GetCabMetaData(stream):
global eofiles
cabMetaData={}
try:
cabMetaData["CabFormat"] = stream[0:4].decode('ANSI')
cabMetaData["CabSize"] = struct.unpack("<L",stream[8:12])[0]
cabMetaData["FilesOffset"] = struct.unpack("<L",stream[16:20])[0]
cabMetaData["NoOfFolders"] = struct.unpack("<H",stream[26:28])[0]
cabMetaData["NoOfFiles"] = struct.unpack("<H",stream[28:30])[0]
# skip 30,32,34,35
cabMetaData["Files"]= {}
cabMetaData["Folders"]= {}
baseOffset = cabMetaData["FilesOffset"]
internalOffset = 0
for i in range(0,cabMetaData["NoOfFiles"]):
fileDetails = {}
fileDetails["Size"] = struct.unpack("<L",stream[baseOffset+internalOffset:][:4])[0]
fileDetails["UnpackedStartOffset"] = struct.unpack("<L",stream[baseOffset+internalOffset+4:][:4])[0]
fileDetails["FolderIndex"] = struct.unpack("<H",stream[baseOffset+internalOffset+8:][:2])[0]
fileDetails["Date"] = struct.unpack("<H",stream[baseOffset+internalOffset+10:][:2])[0]
fileDetails["Time"] = struct.unpack("<H",stream[baseOffset+internalOffset+12:][:2])[0]
fileDetails["Attrib"] = struct.unpack("<H",stream[baseOffset+internalOffset+14:][:2])[0]
fileName =''
for j in range(0,len(stream)):
if(chr(stream[baseOffset+internalOffset+16 +j])!='\x00'):
fileName +=chr(stream[baseOffset+internalOffset+16 +j])
else:
break
internalOffset += 16+j+1
cabMetaData["Files"][fileName] = (fileDetails.copy())
eofiles = baseOffset + internalOffset
except Exception as e:
print(e)
pass
print(cabMetaData["CabSize"])
return cabMetaData
def GetFileSize(url):
resp = requests.head(url)
return int(resp.headers["Content-Length"])
def GetCABHeader(url):
global totalByteArray
size = GetFileSize(url)
newSize ="bytes=0-"+ str(int(0.01*size))
totalByteArray = b''
cabHeader= requests.get(url,headers={"Range":newSize},stream=True)
for chunk in cabHeader.iter_content(chunk_size=1024):
totalByteArray += chunk
def DownloadInfFile(baseUrl,InfFileData,InfFileName):
global totalByteArray,eofiles
if(not os.path.exists("infs")):
os.mkdir("infs")
baseCabName = baseUrl[baseUrl.rfind("/"):]
baseCabName = baseCabName.replace(".","_")
if(not os.path.exists("infs\\" + baseCabName)):
os.mkdir("infs\\"+baseCabName)
fileBytes = b''
newRange = "bytes=" + str(eofiles+InfFileData["UnpackedStartOffset"] ) + "-" + str(eofiles+InfFileData["UnpackedStartOffset"]+InfFileData["Size"] )
data = requests.get(baseUrl,headers={"Range":newRange},stream=True)
with open("infs\\"+baseCabName +"\\" + InfFileName ,"wb") as f:
for chunk in data.iter_content(chunk_size=1024):
fileBytes +=chunk
f.write(fileBytes)
f.flush()
print("Saved File " + InfFileName)
pass
def main(url):
GetCABHeader(url)
cabMetaData = GetCabMetaData(totalByteArray)
for fileName,data in cabMetaData["Files"].items():
if(fileName.endswith(".txt")):
DownloadInfFile(url,data,fileName)
main("http://path-to-some-cabinet.cab")
All the file details are correct. I have verified them.
Any guidance will be appreciated. Am I doing it wrong? Another way perhaps?
P.S : Already Looked into This Post
First, the data in the CAB is raw deflate, not zlib-wrapped deflate. So you need to ask zlib's inflate() to decode raw deflate with a negative windowBits value on initialization.
Second, the CAB format does not exactly use standard deflate, in that the 32K sliding window dictionary carries from one block to the next. You'd need to use inflateSetDictionary() to set the dictionary at the start of each block using the last 32K decompressed from the last block.
I have a legacy classic asp application, that allows us to upload pdf files. The file is saved as hex into a MS SQL DB into an image column. Here is a snip of the data in the column:
0x4A564245526930784C6A634E436957317462573144516F784944416762324A7144516F...
We are now working on a rework of the app using node.js as our backend and angular4 as the front end. As part of that, we need to be able to download the same file in the new app. If I upload the same file using angular4 then the image data looks like this:
0x255044462D312E370D0A25B5B5B5B50D0A312030206F626A0D0A3C3C2F547970652F43...
As you can see the hex is completely different and I am not sure what is causing this. I have tried to look at the classic asp code, but its very old and there is no special encoding or such that is happening that would cause this.
In Angular4 we are using the standard input type file control with the change event to capture the contents of the file and then saving it into our db:
myReader.onloadend = (f) => {
let image64;
if (myReader.result.toString()) {
let base64id = ';base64,';
image64 = myReader.result.substr(myReader.result.indexOf(base64id) + base64id.length);
}
someService.upload(image64);
}
So nothing crazy going on, right? The problem now is that I am able to download the file uploaded via angular fine, but not the ones that were uploaded via classic asp. I receive the following error when I try:
Failed to execute 'atob' on 'Window': The string to be decoded is not
correctly encoded.
Here is the code used to upload the files via classic ASP:
Public Function Load()
Dim PosBeg, PosEnd, PosFile, PosBound, boundary, boundaryPos, Pos
Dim Name, Value, FileName, ContentType
Dim UploadControl
PosBeg = 1
PosEnd = InstrB(PosBeg,m_FormRawData,getByteString(chr(13)))
boundary = MidB(m_FormRawData,PosBeg,PosEnd-PosBeg)
boundaryPos = InstrB(1,m_FormRawData,boundary)
'Get all data inside the boundaries
Do until (boundaryPos=InstrB(m_FormRawData,boundary & getByteString("--")))
Set UploadControl = Server.CreateObject("Scripting.Dictionary")
Pos = InstrB(BoundaryPos,m_FormRawData,getByteString("Content-Disposition"))
Pos = InstrB(Pos,m_FormRawData,getByteString("name="))
PosBeg = Pos+6
PosEnd = InstrB(PosBeg,m_FormRawData,getByteString(chr(34)))
Name = getString(MidB(m_FormRawData,PosBeg,PosEnd-PosBeg))
PosFile = InstrB(BoundaryPos,m_FormRawData,getByteString("filename="))
PosBound = InstrB(PosEnd,m_FormRawData,boundary)
If PosFile<>0 AND (PosFile<PosBound) Then
PosBeg = PosFile + 10
PosEnd = InstrB(PosBeg,m_FormRawData,getByteString(chr(34)))
FileName = getString(MidB(m_FormRawData,PosBeg,PosEnd-PosBeg))
UploadControl.Add "FileName", FileName
Pos = InstrB(PosEnd,m_FormRawData,getByteString("Content-Type:"))
PosBeg = Pos+14
PosEnd = InstrB(PosBeg,m_FormRawData,getByteString(chr(13)))
ContentType = getString(MidB(m_FormRawData,PosBeg,PosEnd-PosBeg))
UploadControl.Add "ContentType",ContentType
PosBeg = PosEnd+4
PosEnd = InstrB(PosBeg,m_FormRawData,boundary)-2
Value = MidB(m_FormRawData,PosBeg,PosEnd-PosBeg)
UploadControl.Add "value" , Value
m_dicFileData.Add LCase(name), UploadControl
Else
Pos = InstrB(Pos,m_FormRawData,getByteString(chr(13)))
PosBeg = Pos+4
PosEnd = InstrB(PosBeg,m_FormRawData,boundary)-2
Value = getString(MidB(m_FormRawData,PosBeg,PosEnd-PosBeg))
UploadControl.Add "value" , Value
End If
m_dicForm.Add LCase(name), UploadControl
BoundaryPos=InstrB(BoundaryPos+LenB(boundary),m_FormRawData,boundary)
Loop
Load = m_blnSucceed
End Function
Any idea what I can do here to fix this? I need to be able to download the old files as well. Is there an encoding or something else I am missing here?
After further looking into this, it seems the following is causing the error: Node.js will send a buffer to the front-end. On the front-end I then convert the buffer into base64 using the below code:
_arrayBufferToBase64(buffer) {
let base64 = '';
let bytes = new Uint8Array(buffer);
let len = bytes.byteLength;
for (let i = 0; i < len; i++) {
bbase64 += String.fromCharCode(bytes[i]);
}
return base64;
}
The returned base64 from the old classic asp is returned as garbage and looks like this:
*R{£ÌõGpÃì#j¾é>i¿ê A l Ä ð!!H!u!¡!Î!û"'"U""¯"Ý#
(?(q(¢(Ô))8)k))Ð5*hÏ++6+i++Ñ,,9,n,¢,×-''I'z'«'Ü(
3F33¸3ñ4+4e44Ø55M55Â5ý676r6®6é7$7`77×88P88È99B99¼9ù:6:t
I am still not sure how to fix this though.
I am working in Powerbuilder technology.
An OLE web browser object is defined in a window of the Powerbuilder.
Expected scenerio: Data from the Powerbuilder window will be passed to the server where the data will be parsed and a report will be generated which will be viewed in the OLE object in the powerbuilder window.
Steps taken:
Used powerbuilder's PostURL method to send the data to the server
While sending data from the Powerbuilder window to the server, the data is XML structure that i need to sand to WS
Problem
i get error -1
here is the code:
string ls_ret = ''
InternetResult ls_result
blob urldata
urldata = blob("")
string urlname = "http://secure.telemessage.com/partners/xmlMessage.jsp"
long ll_ret, ll_length
string ls
ls = '<?xml version="1.0" encoding="UTF-8" ?><TELEMESSAGE><TELEMESSAGE_CONTENT><MESSAGE><MESSAGE_INFORMATION><SUBJECT></SUBJECT></MESSAGE_INFORMATION><USER_FROM><CIML><NAML><LOGIN_DETAILS><USER_NAME>carelaser</USER_NAME><PASSWORD>11235813</PASSWORD></LOGIN_DETAILS></NAML></CIML></USER_FROM><MESSAGE_CONTENT><TEXT_MESSAGE><MESSAGE_INDEX>0</MESSAGE_INDEX><TEXT>test 1</TEXT> </TEXT_MESSAGE></MESSAGE_CONTENT> <USER_TO><CIML><DEVICE_INFORMATION> <DEVICE_TYPE DEVICE_TYPE="SMS"/><DEVICE_VALUE>0502201630</DEVICE_VALUE></DEVICE_INFORMATION></CIML></USER_TO></MESSAGE></TELEMESSAGE_CONTENT><VERSION>1.6</VERSION></TELEMESSAGE>'
ll_length = Len(ls)
string urlheader = "Content-Type: application/xml~n"
urlheader +="Content-Length: " + String(ll_length) + "~n~n"
urldata =blob(ls)
GetContextService("Internet", iinet_base)
messagebox("urlname", urlname)
messagebox("urlheader", urlheader)
messagebox("urldata",string(urldata))
ll_ret = iinet_base.posturl(urlname, urldata , urlheader, ls_result)
messagebox("Return: " + string(ll_ret) ,string(ls_result))
Return ls_ret