如何使用 Python requests 库发出 post 请求? [英] How to make a post request with the Python requests library?

查看:34
本文介绍了如何使用 Python requests 库发出 post 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Postman 中使用以下过滤器在 Web API 中发出 POST 请求,但我无法使用请求库在 Python 中发出简单的 POST 请求.

I am using the following filters in Postman to make a POST request in a Web API but I am unable to make a simple POST request in Python with the requests library.

首先,我向这个 URL (http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets),将 Postman 中的以下过滤器应用于 Body,原始和选择了 JSON(application/json) 选项.

First, I am sending a POST request to this URL (http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets) with the following filters in Postman applied to the Body, with the raw and JSON(application/json) options selected.

Filters in Postman

{
  "filter": {
    "filters": [
      {
        "field": "RCA_Assigned_Date",
        "operator": "gte",
        "value": "2017-05-31 00:00:00"
      },
      {
        "field": "RCA_Assigned_Date",
        "operator": "lte",
        "value": "2017-06-04 00:00:00"
      },
      {
        "field": "T_Subcategory",
        "operator": "neq",
        "value": "Temporary Degradation"
      },
      {
        "field": "Issue_Status",
        "operator": "neq",
        "value": "Queued"
      }],
     "logic": "and"
    }
}

存储数据的数据库是Cassandra,根据以下链接Cassandra 不等于运算符, Cassandra OR 运算符Cassandra 之间的操作顺序,Cassandra 不支持 NOT EQUAL TOORBETWEEN 运算符,因此除了 AND 之外,我无法使用这些运算符过滤 URL.

The database where the data is stored is Cassandra and according to the following links Cassandra not equal operator, Cassandra OR operator, Cassandra Between order by operators, Cassandra does not support the NOT EQUAL TO, OR, BETWEEN operators, so there is no way I can filter the URL with these operators except with AND.

第二,我使用以下代码对请求库应用一个简单的过滤器.

Second, I am using the following code to apply a simple filter with the requests library.

import requests
payload = {'field':'T_Subcategory','operator':'neq','value':'Temporary Degradation'}
url = requests.post("http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets",data=payload)

但我得到的是门票的完整数据,而不仅仅是那些不是暂时降级的.

But what I've got is the complete data of tickets instead of only those that are not temporary degradation.

第三,系统实际上正在运行,但我们看到数据有 2-3 分钟的延迟.逻辑如下:我们有 8 个用户,我们希望看到每个用户的所有票证不是临时降级,然后我们这样做:

Third, the system is actually working but we are experiencing a delay of 2-3 mins to see the data. The logic goes as follows: We have 8 users and we want to see all the tickets per user that are not temporary degradation, then we do:

def get_json():
    if user_name == "user 001":
        with urllib.request.urlopen(
    "http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets?user_name=user&001",timeout=15) as url:
            complete_data = json.loads(url.read().decode())

    elif user_name == "user 002":
        with urllib.request.urlopen(             
    "http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets?user_name=user&002",timeout=15) as url:
            complete_data = json.loads(url.read().decode())
    return complete_data

def get_tickets_not_temp_degradation(start_date,end_date,complete_):
    return Counter([k['user_name'] for k in complete_data if start_date < dateutil.parser.parse(k.get('DateTime')) < end_date and k['T_subcategory'] != 'Temporary Degradation'])

基本上,我们得到了今年和去年的全套票,然后我们让Python按用户过滤了完整的票,到目前为止只有10个用户,这意味着这个过程重复了10次,让我毫不奇怪地发现为什么我们会延迟......

Basically, we get the whole set of tickets from the current and last year, then we let Python to filter the complete set by user and so far there are only 10 users which means that this process is repeated 10 times and makes me no surprise to discover why we get the delay...

我的问题是如何解决请求库的这个问题?我正在使用以下链接 请求库文档 作为使其工作的教程,但似乎我的有效负载没有被读取.

My questions is how can I fix this problem of the requests library? I am using the following link Requests library documentation as a tutorial to make it working but it just seems that my payload is not being read.

推荐答案

您的 Postman 请求是一个 JSON 正文.只需在 Python 中重现相同的主体即可.您的 Python 代码不会发送 JSON,也不会发送与您的 Postman 示例相同的数据.

Your Postman request is a JSON body. Just reproduce that same body in Python. Your Python code is not sending JSON, nor is it sending the same data as your Postman sample.

对于初学者来说,通过 data 参数发送字典将该字典编码为 application/x-www-form-urlencoded 形式,而不是 JSON.其次,您似乎发送了一个过滤器.

For starters, sending a dictionary via the data arguments encodes that dictionary to application/x-www-form-urlencoded form, not JSON. Secondly, you appear to be sending a single filter.

以下代码完全复制了您的 Postman 帖子:

The following code replicates your Postman post exactly:

import requests

filters = {"filter": {
    "filters": [{
        "field": "RCA_Assigned_Date",
        "operator": "gte",
        "value": "2017-05-31 00:00:00"
    }, {
        "field": "RCA_Assigned_Date",
        "operator": "lte",
        "value": "2017-06-04 00:00:00"
    }, {
        "field": "T_Subcategory",
        "operator": "neq",
        "value": "Temporary Degradation"
    }, {
        "field": "Issue_Status",
        "operator": "neq",
        "value": "Queued"
    }],
    "logic": "and"
}}

url = "http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets"
response = requests.post(url, json=filters)

注意 filters 在这里是一个 Python 数据结构,它被传递给 json 关键字参数.使用后者有两件事:

Note that filters is a Python data structure here, and that it is passed to the json keyword argument. Using the latter does two things:

  • 将 Python 数据结构编码为 JSON(生成与原始 Postman 正文值完全相同的 JSON 值).
  • Content-Type 标头设置为 application/json(就像您在 Postman 配置中通过在下拉列表中选择 JSON 选项所做的那样)为正文选择 raw 后的菜单).
  • Encode the Python data structure to JSON (producing the exact same JSON value as your raw Postman body value).
  • Set the Content-Type header to application/json (as you did in your Postman configuration by picking the JSON option in the dropdown menu after picking raw for the body).

requests 否则只是一个 HTTP API,它不能让 Cassandra 比任何其他 HTTP 库做的更多.urllib.request.urlopen 代码发送 GET 请求,并通过以下方式简单地转换为 requests:

requests is otherwise just an HTTP API, it can't make Cassandra do any more than any other HTTP library. The urllib.request.urlopen code sends GET requests, and are trivially translated to requests with:

def get_json():
    url = "http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets"
    response = requests.get(url, params={'user_name': user}, timeout=15)    
    return response.json()

我删除了 if 分支并使用 params 参数替换了它,该参数将键值对字典转换为正确编码的 URL 查询(传入用户名作为 user_name 键).

I removed the if branching and replaced that with using the params argument, which translates a dictionary of key-value pairs to a correctly encoded URL query (passing in the user name as the user_name key).

注意响应中的 json() 调用;这负责解码从服务器返回的 JSON 数据.这仍然需要很长时间,您在这里没有对 Cassandra 数据进行太多过滤.

Note the json() call on the response; this takes care of decoding JSON data coming back from the server. This still takes long, you are not filtering the Cassandra data much here.

这篇关于如何使用 Python requests 库发出 post 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆