我想向VNF发送POST请求以保存服务。
这是我的密码。
class APIClient:
def __init__(self, api_type, auth=None):
if api_type == 'EXTERNAL':
self.auth_client = auth
def api_call(self, http_verb, base_url, api_endpoint, headers=None, request_body=None, params=None):
if headers is not None:
headers = merge_dicts(headers, auth_header)
else:
headers = auth_header
url_endpoint = base_url + api_endpoint
request_body = json.dumps(request_body)
if http_verb == 'POST':
api_resp = requests.post(url_endpoint, data=request_body, headers=headers)
return api_resp
else:
return Falsedef add_service():
for service in service_list:
dict = service.view_service()
auth_dict = {
'server_url': 'https://authserver.nisha.com/auth/',
'client_id': 'vnf_api',
'realm_name': 'nisha,
'client_secret_key': 'abcd12345',
'grant_type': 'client_credentials'
}
api_client = APIClient(api_type='EXTERNAL', auth=auth_dict)
response = api_client.api_call(http_verb='POST',
base_url='http://0.0.0.0:5054',
api_endpoint='/vnf/service-management/v1/services',
request_body=f'{dict}')
print(response)
if response.ok:
print("success")
else:
print("no")当我运行这段代码时,它会打印
<Response [415]>
noVNF端的所有函数都是没有问题的,我对GET服务api调用没有问题。怎么解决这个问题?
发布于 2021-03-19 16:39:13
如果需要将application/json数据发布到端点,则需要在requests.post中使用json kwarg而不是data kwarg。
显示json和data在requests.post中的区别
import requests
from requests import Request
# This is form-encoded
r = Request('POST', 'https://myurl.com', headers={'hello': 'world'}, data={'some': 'data'})
x = r.prepare()
x.headers
# note the content-type here
{'hello': 'world', 'Content-Length': '9', 'Content-Type': 'application/x-www-form-urlencoded'}
# This is json content
r = Request('POST', 'https://myurl.com', headers={'hello': 'world'}, json={'some': 'data'})
x = r.prepare()
x.headers
{'hello': 'world', 'Content-Length': '16', 'Content-Type': 'application/json'}因此,这里根本不需要json.dumps步骤:
url_endpoint = base_url + api_endpoint
if http_verb == 'POST':
api_resp = requests.post(url_endpoint, json=request_body, headers=headers)https://stackoverflow.com/questions/66711943
复制相似问题