Download Files with Python from PHP

I would like to download several files with a Python script from a PHP function.

These files are not accessible by a direct link e.g., www.example.com/file.pdf. However, the headers are sent after some security checks. PHP server side:

        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($publicName).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($internalPath));
        readfile($internalPath);

Calling this with common browsers works well.

For further purposes I need Python script on the client side to download and save the provided files which is currently very basic like this:

import urllib.request
urllib.request.urlretrieve("https://example.com/app/provideFile/filename", "download.pdf")

The script runs without any error and saves direct downloads (https://example.com/file.pdf) correctly. Calling the PHP logic (https://example.com/app/provideFile/filename) leads to broken files with very small file sizes on the client.

Is there a way to modify the server side or the client side to make this working?