Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python encode() and decode() issues

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading