Some way to covert the string representation of a pdf into bytes in python Some way to covert the string representation of a pdf into bytes in python flask flask

Some way to covert the string representation of a pdf into bytes in python


In such cases, it's preferred to send file data passing that with the files keyword, like so:

import requestsdef send_pdf_data(filename_list, encoded_pdf_data):    files = {}    for (filename, encoded, index) in zip(filename_list, encoded_pdf_data, range(len(filename_list))):        files[f"pdf_name_[index].pdf"] = (filename, open(filename, 'rb'), 'application/pdf')    data = {}    # *Put whatever you want in data dict*    requests.post("http://yourserveradders", data=data, files=files)def main():    filename_list = ["pdf_name_1.pdf", "pdf_name_2.pdf"]    pdf_blob_data = [open(filename, 'wb').read() for filename                     in filename_list]if __name__ == '__main__':    main()

However, if you really want to pass data as json, you should use base-64 module as @Mark Ransom mentioned.

You can implement it in this way:

import requestsimport jsonimport base64def encode(data: bytes):    """    Return base-64 encoded value of binary data.    """    return base64.b64encode(data)def decode(data: str):    """    Return decoded value of a base-64 encoded string.    """    return base64.b64decode(data.encode())def get_pdf_data(filename):    """    Open pdf file in binary mode,    return a string encoded in base-64.    """    with open(filename, 'rb') as file:        return encode(file.read())def send_pdf_data(filename_list, encoded_pdf_data):    data = {}    # *Put whatever you want in data dict*    # Create content dict.    content = [dict([("name", filename), ("data", pdf_data)])               for (filename, data) in zip(filename_list, encoded_pdf_data)]    data["content"] = content    data = json.dumps(data) # Convert it to json.    requests.post("http://yourserveradders", data=data)def main():    filename_list = ["pdf_name_1.pdf", "pdf_name_2.pdf"]    pdf_blob_data = [get_pdf_data(filename) for filename                     in filename_list]if __name__ == '__main__':    main()