Python Requests: Post JSON and file in single request

前端 未结 6 511
天涯浪人
天涯浪人 2020-12-01 05:16

I need to do a API call to upload a file along with a JSON string with details about the file.

I am trying to use the python requests lib to do this:



        
6条回答
  •  离开以前
    2020-12-01 05:36

    What is more:

    files = {
        'document': open('file_name.pdf', 'rb')
    }
    

    That will only work if your file is at the same directory where your script is.

    If you want to append file from different directory you should do:

    files = {
        'document': open(os.path.join(dir_path, 'file_name.pdf'), 'rb')
    }
    

    Where dir_path is a directory with your 'file_name.pdf' file.

    But what if you'd like to send multiple PDFs ?

    You can simply make a custom function to return a list of files you need (in your case that can be only those with .pdf extension). That also includes files in subdirectories (search for files recursively):

    def prepare_pdfs():
        return sorted([os.path.join(root, filename) for root, dirnames, filenames in os.walk(dir_path) for filename in filenames if filename.endswith('.pdf')])
    

    Then you can call it:

    my_data = prepare_pdfs()
    

    And with simple loop:

    for file in my_data:
    
        pdf = open(file, 'rb')
    
        files = {
            'document': pdf
        }
    
        r = requests.post(url, files=files, ...)
    

提交回复
热议问题