Python AttributeError: 'str' 对象没有属性 'items'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18867898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:07:15  来源:igfitidea点击:

AttributeError: 'str' object has no attribute 'items'

pythonstringrestdictionaryhttp-request

提问by snrkl

In the following code:

在以下代码中:

#!/usr/local/bin/python
import json

APPLICATION_NAME = 'cc9226315643df89-36bf02429075329d0ba36748360d050c'

HEADERS1 = json.dumps(dict(Destination = u"/api/af/latest/applications/%s/rulesets" % (APPLICATION_NAME)))
print "Headers1 is %s" % (HEADERS1)
HEADERS2 = {'Destination': '/api/af/latest/applications/%s/rulesets' % (APPLICATION_NAME)}
print "Headers2 is %s" % (HEADERS2)

I get the following output:

我得到以下输出:

Headers1 is {"Destination": "/api/af/latest/applications/cc9226315643df89-36bf02429075329d0ba36748360d050c/rulesets"}
Headers2 is {'Destination': '/api/af/latest/applications/cc9226315643df89-36bf02429075329d0ba36748360d050c/rulesets'}

but when I try to use either HEADER1 or HEADER2 in a REST call using requests(), I get very different results:

但是当我尝试在使用 requests() 的 REST 调用中使用 HEADER1 或 HEADER2 时,我得到了非常不同的结果:

SERVER_URL = 'http://1.1.33.109:8087%s' % (APP_PATH)
REQ_DATA = None
print "Headers are: ", HEADERS
print "SERVER_URL is: ", SERVER_URL
print "Request Data is:", REQ_DATA
print ""

RESPONSE = requests.request(
    'MOVE', 
    SERVER_URL, 
    auth = ('admin', 'admin'), 
    verify = False, 
    data = REQ_DATA,
    headers = HEADERS1 )     #<-- If I use HEADER1 it breaks, if I use HEADER2 it works
print "Move Ruleset back to the Application RESULT: %s\n" % (RESPONSE)

I get the following with HEADER1:

我用 HEADER1 得到以下信息:

Traceback (most recent call last):
   File "./myrest.py", line 234, in <module>
     headers = HEADERS1 )
   File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/api.py", line 44, in request
     return session.request(method=method, url=url, **kwargs)
   File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/sessions.py", line 324, in request
     prep = req.prepare()
   File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/models.py", line 223, in prepare
     p.prepare_headers(self.headers)
   File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/models.py", line 340, in prepare_headers
     headers = dict((name.encode('ascii'), value) for name, value in headers.items())
AttributeError: 'str' object has no attribute 'items'

If I use HEADER2 it executes cleanly:

如果我使用 HEADER2,它会干净地执行:

Move Ruleset back to the Application RESULT: Response [200]

将规则集移回应用程序结果:响应 [200]

Can anyone explain what the differences are?

谁能解释一下有什么区别?

采纳答案by Martijn Pieters

You are passing in a string; headerscan't everbe a JSON encoded string, it is always a Python dictionary.

您正在传递一个字符串headers不能永远是一个JSON编码字符串,它始终是一个Python字典。

The printresults are deceptive; JSON encoded objects look a lot like Python dictionary representations but they are farfrom the same thing.

print结果都是骗人的; JSON 编码的对象看起来很像 Python 字典表示,但它们相去甚远

The requestsAPIclearly states that headersmust be a dictionary:

requestsAPI明确规定,headers必须是一个字典:

  • headers– (optional) Dictionary of HTTP Headers to send with the Request.
  • headers–(可选)与Request.

JSON data is something you'd send as content to another server, not something you'd use to communicate with a Python API.

JSON 数据是作为内容发送到另一台服务器的数据,而不是用于与 Python API 通信的数据。

回答by ddtraveller

I had this issue and I needed to make the header with a content type and pass in a data element as json.

我遇到了这个问题,我需要使用内容类型制作标题并将数据元素作为 json 传递。

import requests
import json

headerInfo = {'content-type': 'application/json' }
payload = {'text': 'okay!!!', 'auth_token': 'aasdasdasdasd'}
jLoad = json.dumps(payload)

r = requests.post('http://example.com:3030/widgets/init', headers=headerInfo, data=jLoad)
print r.text
print r.status_code

回答by channareddy biradar

You Can pass {

你可以通过{

  'Content-Type': 'application/json;charset=UTF-8'
}

it worked

有效