Friday, 29 July 2022

python requests how to send post request, requetResponseObjModel

import requests

import json  

https://stackoverflow.com/questions/8685790/adding-headers-to-requests-module

            payload = {

                'data' : 123

            }

            headers = {

                'accept': 'application/json',

                'content-type' : 'application/json'

            }

#certs is for client certs for validation, should be a location in the project directory, for docker newly created folders, re-run container to sync

Fore example in settings.py

# Build paths inside the project like this: BASE_DIR / 'subdir'.

BASE_DIR = Path(__file__).resolve().parent.parentgs.py

# Server Certificate location

FULL_CHAIN = os.path.join(CERT_FOLDER, 'fullchain.pem')

PRIV_KEY = os.path.join(CERT_FOLDER, 'privkey.pem')

# If above directory are newly created in your project, re-run docker-compose down -v and docker-compose up to sync them to docker container, or else they wont exist

Myviews.py

from django.conf import setting

           respObjModel = requests.post(

                URL,

                json=payload,

                verify=False,

                headers=headers,

                cert=(

                    settings.FULL_CHAIN,

                    settings.PRIV_KEY

                )

            )


request responseObj

https://stackoverflow.com/questions/52159376/why-do-i-get-error-attributeerror-response-object-has-no-attribute-get-in-p

from django.http import (HttpResponse, HttpResponseRedirect,

                         HttpResponseServerError)


import json  



>>> respObjModel .status_code
200
>>> respObjModel .headers['content-type']
'application/json; charset=utf8'
>>> respObjModel .encoding
'utf-8'
>>> respObjModel .text
u'{"type":"User"...'
>>> respObjModel .json()
{u'disk_usage': 368627, u'private_gists': 484, ...}


.json() returns a dictonary


# Saving dict convereted from .json() to DB will have format issue :

visit the following blog python, django saving resp.json() dict or  dict to DB, then retrieve from DB to cast to JSON

: https://joeyxff.blogspot.com/2022/08/python-django-saving-respjson-dict-or.html

convert dict to JSON string in HTTPResponse is 


    response={

        'payload': responseDict,

        'errors': errors

    }

    return  HttpResponse(content=json.dumps(response), content_type='application/json')


No comments:

Post a Comment