Python requests – HTTP library. Examples

If you need to send some HTTP requests and that requires additional processing on your side maybe it’d be better to draft some script. If you happen to know python then you can try its Requests library. Some simple snippets that can be used are placed further.

Set up a session

import requests
from requests import Request, Session
from requests.auth import HTTPBasicAuth

s = requests.Session()

Send POST request:

registrationData = {'registrationCode' :registrationCode ,'customerReference': customerRefNo} + '/customer-account/register',headers = headers, data = registrationData)

Just add required headers e.g

headers = {
 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36'

Send POST with json data

authorisationPayload = {"personRoles":[{"role":"Owner","personId":userId}],
 ["Full permissions","Amend ","No access - cs","No access - cs agree"],
 "personId":userId}]} + '/organisation/' +str(businessID),headers = headers, json = authorisationPayload)

Dealing with Cross-site request forgery

If we have XSRF token added to requests we need to extract it.

def getXsrf(cookies):
    for cookie in s.cookies:
       if =='XSRF-TOKEN':
          return cookie.value

and add it to our headers

xsrf = getXsrf(s.cookies)
 headers['X-XSRF-TOKEN'] = xsrf

Extract data from Json response:

 if ( ra.status_code == 200 ):
   organisationID = ra.json()['_data'][0]['id'] 

In case of unverified HTTPS requests we can suppress warnings (if we really want it) :

from requests.packages.urllib3.exceptions import InsecureRequestWarning

We also probably need to add to our request this parameter  verify=False
to skip verification of HTTPS certificate. Use it if needed of course.

Python requests – HTTP library. Examples

Django – how to view executed queries

You also can use python logging to log all queries generated by Django. Just add this to your settings file.

    'disable_existing_loggers': False,
    'version': 1,
    'handlers': {
        'console': {
            # logging handler that outputs log messages to terminal
            'class': 'logging.StreamHandler',
            'level': 'DEBUG', # message level to be written to console
    'loggers': {
        '': {
            # this sets root level logger to log debug and higher level
            # logs to console. All other loggers inherit settings from
            # root level logger.
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False, # this tells logger to send logging message
                                # to its parent (will send if set to True)
        'django.db': {
            # django also has database level logging


Also useful some template to show queries in the DEBUG mode:

Django – how to view executed queries