Somehow cannot download complete attachment by REST API in Python

Hi,

I refer to Python requests, how to limit received size, transfer rate, and/or total time? - Stack Overflow and my code is as follows:

#!/usr/bin/python
import time

import requests
from jira import JIRA

PAT = "MYPAT"
headers = JIRA.DEFAULT_OPTIONS["headers"].copy()
headers["Authorization"] = f"Bearer {PAT}"
myTicket = "JTE-311"
jiraURL = "https://jira.accton.com:8443/rest/api/2/issue/"
fileName = (
    "Docker.png"  # In this case we'll be looking for a specific file in the attachments
)

attachment_final_url = ""  # To validate if there are or not attachments
initial_timeout = 115
your_maximum = 2000000
receive_timeout = 10000000000000


def main():
    print(f"[ You are checking ticket: '{myTicket}']")
    r = requests.get(jiraURL + myTicket, headers=headers, timeout=initial_timeout)
    
    r.raise_for_status()

    # if int(r.headers.get("Content-Length")) > your_maximum:
    #     raise ValueError("response too large")

    size = 0
    start = time.time()

    for chunk in r.iter_content(1024):
        if time.time() - start > receive_timeout:
            raise ValueError("timeout reached")

        size += len(chunk)
        if size > your_maximum:
            raise ValueError("response too large")

        # do something with chunk

    # If the status isn't 200 we leave
    if not r.status_code == 200:
        print("Error accesing JIRA:" + str(r.status_code))
        exit()
    else:
        data = r.json()

    if not data["fields"]["attachment"]:
        status_attachment = "ERROR: Nothing attached, attach a file named: " + fileName
        attachment_final_url = ""
    else:
        for i in data["fields"]["attachment"]:
            if i["filename"] == fileName:
                attachment_final_url = i["content"]
                status_attachment_name = (
                    "OK: The desired attachment exists: " + fileName
                )
                attachment_name = False
                attachment_amount = False
                attachment_files = False
                break
            else:
                attachment_files = False
                status_attachment_name = (
                    "ERROR: None of the files has the desired name "
                )
                attachment_final_url = ""
                attachment_name = True
                attachment_amount = True
                continue

    if attachment_final_url != "":
        # with open(fileName, "wb+") as f:
        #     # f.write(r.content)
        #     # f.write(r.content.encode("utf8").decode("utf8"))
        #     f.write(r.content.decode("utf8").encode("utf8"))
        #     # f.write(r.content.decode("iso-8859-1").encode("utf8"))
        # f.close()
        r = requests.get(attachment_final_url, headers=headers, stream=True)
        f = open(fileName, "wb")
        for chunk in r.iter_content(chunk_size=512):
            # for chunk in r.iter_lines():
            if chunk:
                f.write(chunk)
    else:
        print(status_attachment)


if __name__ == "__main__":
    main()

The value of the “size” variable is 11476, but the size of the downloaded “Docker.png” is 62271 as well as the other downloaded attachment.

I also upload a 1.txt file that contains “123” words. After downloading the 1.txt, I found its content is as follows:

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><title>Oops - an error has occurred</title><script type="text/javascript">contextPath = "";</script><link type='text/css' rel='stylesheet' href='/static-assets/metal-all.css' media='all'><script src='/static-assets/jquery-min.js'></script><script src='/static-assets/metal-all.js'></script><meta name="decorator" content="none" /></head><body class=" error-page error500"><script type="text/javascript">document.body.className += " js-enabled";</script><div id="page"><header id="header" role="banner" aria-label="Site"></header><div id="content"><div class="aui-page-panel" ><div class="aui-page-panel-inner"><main role="main" id="main" class="aui-page-panel-content lowerContent" ><div id="error-state"><span class="error-type"></span><h1>Sorry, we had some technical problems during your last operation.</h1><div id="technical-details-content" class="technical-details "><p>Copy the content below and send it to your Jira Administrator</p><div class="technical-details-content short" contentEditable readonly><p class="referral">Log&#39;s referral number: <strong id="log-referral-id">5f5dfa86-bfd1-45c9-9502-e5de7108d028</strong></p></div></div><a href="javascript:window.history.back()" class="aui-button">Return to the previous page</a></div></main></div></div></div><footer id="footer" role="contentinfo"><section class="footer-body"><ul class="atlassian-footer">
    <li>
        Atlassian Jira <a class="seo-link" rel="nofollow" href="https://www.atlassian.com/software/jira">Project Management Software</a>
            </li>
    <li>
        <a id="about-link" rel="nofollow" href="/secure/AboutPage.jspa/secure/AboutPage.jspa">About Jira</a>
    </li>
    <li>
        <a id="footer-report-problem-link" rel="nofollow" href="/secure/CreateIssue!default.jspa">Report a problem</a>
    </li>
</ul>
    <p class="atlassian-footer">
        <span class="licensemessage">
            
        </span>
    </p>
<div id="footer-logo"><a href="http://www.atlassian.com/" rel="nofollow">Atlassian</a></div></section></footer></div></body></html>

I’ve converted the 1.txt to 1.html and attached its screenshot for your reference.

Could you please check the error message? Thanks.