我一直在尝试使用POST
发送Python
HTTP请求(第一次使用它),并且一直返回TypeError: 'str' object is not callable
我的代码:
import requests
import json
c100 = "100";
url ="http://api.orange.com/smsmessaging/v1/outbound/tel+21654614211/requests"
payload = {
"outboundSMSMessageRequest": {
"address": "tel+21653424499",
"outboundSMSTextMessage": {
"message": "Capteur "+ c100 +" est en incendie"
},
"senderAddress": "tel+21654614211",
"senderName": "GCI"
}
}
headers = {'content-type': 'application/json'}
r = requests.post(url, auth=('Basic <omitted>'), data=json.dumps(payload), headers=headers)
输出:
Traceback (most recent call last):
File "main.py", line 18, in <module>
r = requests.post(url, auth=('Basic U0cwUE1aeGZmZ0JLbUkzWUV2ZWlsM0xBdEt0UVZ4Q1k6SVRqWXQxRU5nWlV4SGM5OQ=='), data=payload, headers=headers)
File "/usr/lib/python3/dist-packages/requests/api.py", line 88, in post
return request('post', url, data=data, **kwargs)
File "/usr/lib/python3/dist-packages/requests/api.py", line 44, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 433, in request
prep = self.prepare_request(req)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 371, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "/usr/lib/python3/dist-packages/requests/models.py", line 291, in prepare
self.prepare_auth(auth, url)
File "/usr/lib/python3/dist-packages/requests/models.py", line 470, in prepare_auth
r = auth(self)
TypeError: 'str' object is not callable
答案 0 :(得分:0)
原始代码中的身份验证参数错误。如果删除它,它将起作用。
r = requests.post(url, data=json.dumps(payload), headers=headers)
答案 1 :(得分:0)
您的身份验证是错误的,而且问题是:您是否需要身份验证?
基本身份验证:许多需要身份验证的Web服务都接受HTTP基本身份验证。这是最简单的一种,并且请求 直接支持它。
使用HTTP基本身份验证进行请求非常简单:
>>> from requests.auth import HTTPBasicAuth >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass')) <Response [200]>
事实上,HTTP Basic Auth非常普遍,因此Requests提供了方便 使用的简写:
>>> requests.get('https://api.github.com/user', auth=('user', 'pass')) <Response [200]>
像这样在元组中提供凭据与 上面的HTTPBasicAuth示例。
注意:
如果您有令牌,则可能需要以下内容:
import requests
auth_token='sdasadadsadas'
head = {'Authorization': 'Bearer ' + auth_token}
payload = {
"outboundSMSMessageRequest": {
"address": "tel+21653424499",
"outboundSMSTextMessage": {
"message": "Capteur "+ c100 +" est en incendie"
},
"senderAddress": "tel+21654614211",
"senderName": "GCI"
}
}
url = 'http://api.orange.com/smsmessaging/v1/outbound/tel+21654614211/requests'
response = requests.post(url, json = payload, headers=head)