简体   繁体   中英

AttributeError: 'str' object has no attribute 'items' (python)

I am trying to post data to api of website using this code:

import requests as r
import json


load={"accept": "application/json, text/plain, */*",
"accept-encoding": "gzip, deflate, br",
"accept-language": "en-US,en;q=0.9",
"content-length": "40",
"content-type": "application/json",
"origin": "www.mysite.com",
"referer": "www.mysite.com",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 Edg/83.0.478.37",
}

pd={"version"="1.0"}
ro = r.post("api.mysite.com", headers=json.dumps(load),data=pd)


print(ro.status_code, ro.reason)

But I keep getting this error:

Traceback (most recent call last):
  File "test.py", line 18, in <module>
    ro = r.post("https://api.mysite.com", headers=json.dumps(load),data=pd)
  File "C:\Users\ajay1998A\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\api.py", line 119, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Users\ajay1998A\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\api.py", line 61, in reques
t
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\ajay1998A\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\sessions.py", line 516, in
request
    prep = self.prepare_request(req)
File "C:\Users\ajay1998A\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\sessions.py", line 459, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "C:\Users\ajay1998A\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\models.py", line 315, in prepare
    self.prepare_headers(headers)
  File "C:\Users\ajay1998A\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\models.py", line 447, in prepare_headers
for header in headers.items():
AttributeError: 'str' object has no attribute 'items'

I checked the type of load and it's dictionary. Any help is appreciated.

Since as you say, your load object is already a dictionary (which is json serializable, and has an items attribute) by writing

headers = json.dumps(load)

the json.dumps method is JSON encoding your load object into a string (which does not have an item method)

Try

headers = load

instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM