Python interface testing, post requests for file upload request library

Foreword

If you need to send a file to the server, such as uploading pictures, videos, etc., we need to send binary data.

Are generally used to upload files  Content-Type: multipart / form- data;  type of data, the file can be transmitted, you can also send data related to the message body.

 

A multi-part encoded POST (Multipart-Encoded) file

The basic steps for requests to upload files

  1. Configuration data files, open the file open function in binary mode by
  2. Data structure
  3. Send a request to the file data   files  parameters passed, other messages volume data   Data  , JSON  ,  headers  ,  Cookies  afferent
. 1 URL = ' http://httpbin.org/post '   # Upload File Interface 
2 Files = {
 . 3      ' File ' : ( ' test.png ' ,   # file name 
. 4               Open ( ' ../file/test.png ' , ' RB ' ),   # file path 
. 5               ' Image / PNG ' ,   # file type 
. 6               { ' the Expires ' : ' 0 '}  #Other parameters, non-essential pass 
7               )
 8 }   # => Open file upload and add the relevant parameters 
. 9  
10 Data = {
 . 11      " name " : " Test " 
12 is  }
 13 is  
14  # Data incoming request parameters dict, files to be passed Upload file parameters dict 
15 R & lt requests.post = (URL, Data = Data, files = files)
 16  Print (r.json ())

note

The dictionary files   ' File '  button is a name attribute upload component to change and not necessarily the File;

Upload component in the following figure, when you upload an image, capture will pass two values can be found, one fileField, one type, so your data file to be included dict  fileField  and  type  two key

. 1      Files = {
 2          ' FileField ' : ( ' test.png ' ,   # file name 
. 3                        Open ( ' ../file/test.png ' , ' RB ' ),   # file path 
. 4                        ' Image / PNG ' ,   # file type 
. 5                        { ' the Expires ' : ' 0 ' }   # other parameters, will transmit non- 
6                        ),
 7          'type ' :. 1
 . 8      }   # => Open file upload and add parameters


Guess you like

Origin www.cnblogs.com/poloyy/p/12232541.html