Abhay Jain
Abhay Jain

Reputation: 149

pythonic way of making POST http[s] session requests

I am trying to make requests to server based on some condition. Is there any efficient way to do that. I have to filter information based on

  1. If authentication is required
  2. If header is required
  3. Make direct request
import requests
session = requests.Session()

url='http://someurl.com'

if username != "" and password != "" and headers != "":
    resp = session.request('POST', url=url, json=json, auth=(username,password), headers=headers)
elif headers != "":
    resp = session.request('POST', url=url, json=json, headers=headers)
else:
    resp = session.request('POST', url=url, json=json)

I am total noob to python. I was able to find way to use it but didn't find any resource which can point me to industry practice.

Upvotes: 0

Views: 699

Answers (2)

Mark
Mark

Reputation: 684

The most common way I've seen this done would be to create a function that forwards its keyword arguments and provides default values.

import requests

session = requests.Session()
url = 'http://someurl.com'


def send_post(**kwargs):
    data = {'url': url, 'json': json}
    data.update(kwargs)

    return session.request('POST', **data)


# All of these are valid:
send_post(auth=(username, password))
send_post(headers={'X-My-Header': 'value'}, auth=(username, password))
send_post(headers={'X-My-Header': 'value'})

Upvotes: 1

dukkee
dukkee

Reputation: 1122

You can use params unpacking, i.e. create a dict, add new values via conditions and then unpack it via **kwargs.

import requests
session = requests.Session()

url = 'http://someurl.com'

kwargs = {}

if username and password:
    kwargs["auth"] = (username, password)
if headers:
    kwargs["headers"] = headers

response = session.request('POST', url=url, json=json, **kwargs)

Upvotes: 2

Related Questions