首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Python ()中发送POST请求?

如何在Python ()中发送POST请求?
EN

Stack Overflow用户
提问于 2021-03-19 16:24:26
回答 1查看 2.3K关注 0票数 1

我想向VNF发送POST请求以保存服务。

这是我的密码。

代码语言:javascript
复制
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 False
代码语言:javascript
复制
def 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")

当我运行这段代码时,它会打印

代码语言:javascript
复制
<Response [415]>
no

VNF端的所有函数都是没有问题的,我对GET服务api调用没有问题。怎么解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-19 16:39:13

如果需要将application/json数据发布到端点,则需要在requests.post中使用json kwarg而不是data kwarg。

显示jsondatarequests.post中的区别

代码语言:javascript
复制
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步骤:

代码语言:javascript
复制
        url_endpoint = base_url + api_endpoint

        if http_verb == 'POST':
            api_resp = requests.post(url_endpoint, json=request_body, headers=headers)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66711943

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档