简体   繁体   中英

Python: conversion from requests library to urllib3

I need to convert the following CURL command into an http request in Python:

curl -X POST https://some/url
-H 'api-key: {api_key}'
-H 'Content-Type: application/json'
-H 'Accept: application/json'
-d '{ "data": { "dirname": "{dirname}", "basename": "{filename}", "contentType": "application/octet-stream" } }'

I initially successfully implemented the request using Python's requests library.

import requests

url = 'https://some/url'
api_key = ...
dirname = ...
filename = ...

headers = {
    'api-key': f'{api_key}',
    'Content-Type': 'application/json',
    'Accept': 'application/json',
}

payload = json.dumps({
    'data': {
        'dirname': f'{dirname}',
        'basename': f'{filename}',
        'contentType': 'application/octet-stream'
    }
})

response = requests.post(url, headers=headers, data=payload)

The customer later asked not to use pip to install the requests library. For this I am trying to use the urllib3 library as follows:

import urllib3

url = 'https://some/url'
api_key = ...
dirname = ...
filename = ...

headers = {
    'api-key': f'{api_key}',
    'Content-Type': 'application/json',
    'Accept': 'application/json',
}

payload = json.dumps({
    'data': {
        'dirname': f'{dirname}',
        'basename': f'{filename}',
        'contentType': 'application/octet-stream'
    }
})

http = urllib3.PoolManager()
response = http.request('POST', url, headers=headers, body=payload)

The problem is that now the request returns me an error 400 and I don't understand why.

Try calling .encode('utf-8') on payload before passing as a parameter.

Alternatively, try to pass payload as fields without manually converting it to JSON:

payload = {
  'data': {
    'dirname': f'{dirname}',
    'basename': f'{filename}',
    'contentType': 'application/octet-stream'
  }
}
http = urllib3.PoolManager()
response = http.request('POST', url, headers=headers, fields=payload)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM