I'm trying to get a token from the Django authentication. But I'm getting following error:
Exception type: <class 'AttributeError'> msg: 'set' object has no attribute 'items'
My test code snippet looks like this:
import os
import requests
import json
from dotenv import load_dotenv
load_dotenv()
BASE_DEV_URL = "http://127.0.0.1:4000"
def login(url=(BASE_DEV_URL "/api/user/token")):
headers = {
'accept: application/json',
'accept: text/html,application/xhtml xml,application/xml;q=0.9,*/*;q=0.8',
'Content-Type:' 'application/x-www-form-urlencoded',
}
try:
payload = {"email": os.getenv('TEST_USER_NAME'), "password": os.getenv('TEST_USER_PASSWORD')}
print(payload)
res = requests.post(url, data=json.dumps(payload), headers=headers)
print(f'####### {type(res)}')
except Exception as e:
return f'Exception type: {type(e)} msg: {e}'
return res
response = login()
print(response)
However, when I test it with swagger with curl command it works fine curl looks like this
curl -X 'POST' \
'http://127.0.0.1:4000/api/user/token/' \
-H 'accept: application/json' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-H 'X-CSRFTOKEN: T7wW385wMiYDERJU2yWvqGorrbKjtb9zhWqlAkAlE30QKgP7DoQMbc7MnQT3UAti' \
-d '[email protected]&password=123XVW174'
Any idea how to make it work. I'm not sure, but it may because by serialized. I worked with request library a lot and never encountered such error. Will be grateful for any advice which could solve it.
CodePudding user response:
Your headers should be a dictionary, not a set, so:
headers = {
'accept': 'application/json',
'accept': 'text/html,application/xhtml xml,application/xml;q=0.9,*/*;q=0.8',
'Content-Type': 'application/x-www-form-urlencoded',
}
CodePudding user response:
I ended up disabling crfs from middleware.
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
My headers and request look like this:
headers = {
'accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'multipart': 'form-data',
}
payload = {"email": os.getenv('TEST_USER_NAME'), "password": os.getenv('TEST_USER_PASSWORD')}
res = requests.post(url, data=payload, headers=headers)
It finally gives me response 200 and proper data. However, I would like to know how to properly generate crf token for testing