Can anyone help me with this issue please
encode method is not working and i cannot discover why
def encode_OctetString(A,flags,data):
fs="!"+str(len(data))+"s"
dbg="Encoding String format:",fs
logging.debug(dbg)
ret=struct.pack(fs,data).encode("hex")
pktlen=8+len(ret)/2
return encode_finish(A,flags,pktlen,ret
error code
File "/home/ubuntu/diameter-test/libDiameter.py", line 434, in encode_OctetString
ret=struct.pack(fs,data).encode("hex")
struct.error: argument for 's' must be a bytes object
>Solution :
Note that struct.pack() will normally return a bytes and bytes don’t have an .encode() method, just a .decode() one – were you trying to first decode and then re-encode as "hex"?
If so, you’ll need to import codecs.encode() and apply that to the bytes object:
import struct
import logging
import codecs
def encode_OctetString(A, flags, data):
fs = "!" + str(len(data)) + "s"
dbg = "Encoding String format:", fs
logging.debug(dbg)
ret = codecs.encode(struct.pack(fs, data), "hex")
pktlen = 8 + len(ret) / 2
return encode_finish(A, flags, pktlen, ret)
If you somehow intended encode_OctetString to work on strings instead of bytes objects, you’d use:
def encode_OctetString(A, flags, data):
fs = "!" + str(len(data)) + "s"
dbg = "Encoding String format:", fs
logging.debug(dbg)
ret = codecs.encode(struct.pack(fs, data.encode()), "hex")
pktlen = 8 + len(ret) / 2
return encode_finish(A, flags, pktlen, ret)
Given the link to the original code, that depends on the expected type for AVP_Value in encodeAVP – which is never called in the shared code, nor is its type documented and no type hint is provided, so it’s impossible to say.