Numpty
Numpty

Reputation: 1481

Python Requests - Using variables within header and get request

I have two variables that must be injected into a PUT (curl -XPOST equivalent)

I'm running into two issues:

  1. What is the proper way to include variables into the request
  2. Since this is run across HTTPS, how do I validate what is actually included within the request? I'd like to validate this for debugging purposes

Upvotes: 2

Views: 17372

Answers (1)

Daniel
Daniel

Reputation: 2469

  1. What is the proper way to include variables into the request

Passing the headers dictionary as the headers argument, as you have it written, is fine. For your url string, I would just join() the base URL to your Variable2, and pass that as an argument.

Here's how I would write this code:

import requests

base_url = 'https://URL/1/2/3/4/5/'
url = ''.join([base_url, Variable2])

headers = {'Authorization': 'Bearer Variable1',}
files = [('server', '*'),]

resp = requests.put(url, headers=headers, files=files, verify=False)
  1. Since this is run across HTTPS, how do I validate what is actually included within the request? I'd like to validate this for debugging purposes

You can utilize the PreparedRequest object:

from requests import Request, Session

r = Request('PUT', url, headers=headers, files=files)
prepped = r.prepare()

# now, for example, you can print out the url, headers, method...
# whatever you need to validate in your request.
# for example:
# print prepped.url, prepped.headers

# you can also send the request like this...

s = Session()
resp = s.send(prepped)

Upvotes: 3

Related Questions