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

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

问题描述

我在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发送POST请求(

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不支持不等于 >, OR BETWEEN 运算符,因此除了使用 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.

推荐答案

您的邮递员请求是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配置中一样,在为正文选择raw之后在下拉菜单中选择JSON选项).
  • 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请求库发出发布请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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