【问题标题】:Python CURL delete request functionPython CURL 删除请求函数
【发布时间】:2021-10-05 22:34:37
【问题描述】:

我正在尝试在 Python 中重新创建此 CURL 请求并让它循环通过 CSV。

curl -X "DELETE" --user 'api:<my-api-key>' \   https://api.mailgun.net/v3/messages.thewebsite/unsubscribes \  
-F address='email@gmail.com'

我在想我应该创建一个函数并返回结果。我将 requests 包与 CSV 一起使用,但得到了

的输出

打印到控制台。我在这里错过了什么?

下面的代码示例。

Import csv
Import requests


def remove_suppression():
    return requests.delete(
        "https://api.mailgun.net/v3/messages.thewebsite.com/unsubscribes",
        auth=("api", "key-abcdefg12345789gbb"),
        data={'address':'row[1]'})

with open('/Users/brett/Downloads/example.csv',newline='') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
            try:
                
                remove_suppression()
                print("=========================")
                print(remove_suppression.text)
                sleep(5)
 
            except:

            #write log to a text file

【问题讨论】:

  • 只是一个注释,但请记住确保这不是问题中的实际 api 密钥。我还建议进行修改。
  • 不使用print(remove_suppression.text),可以保存remove_suppression()的返回值,然后打印出来吗?

标签: python csv curl python-requests


【解决方案1】:

您需要将row 值作为参数传递给remove_supression。目前您正在打印出remove_suppression 的值,这是一个函数。

您应该将函数的顶部替换为:

def remove_supression(row): ...

确保也将'row[1]' 部分替换为row,否则您只是发送文字字符串'row[1]' 而不是实际行。

最重要的是,您需要将从 for 循环内的 remove_supression(row) 获得的值分配给一个值,然后您可以使用该值从中获取文本,例如:

resp = remove_supression(row)
print(resp.text)

【讨论】:

    【解决方案2】:

    您打印的不是结果,而是函数对象的字符串表示形式。将结果存储到变量并打印变量。例如:

    import csv
    import requests
    
    
    def remove_suppression():
        return requests.delete(
            "https://api.mailgun.net/v3/messages.thewebsite.com/unsubscribes",
            auth=("api", "key-abcdefg12345789gbb"),
            data={"address": "row[1]"},
        )
    
    
    with open("/Users/brett/Downloads/example.csv", newline="") as csvfile:
        readCSV = csv.reader(csvfile, delimiter=",")
        for row in readCSV:
            try:
                result = remove_suppression().text # <-- store the .text result
                print("=========================")
                print(result)  # <-- print it
                sleep(5)
            except:
                pass
    

    【讨论】:

    • 或者result = remove_suppression() 然后print(result.text)
    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2019-06-21
    相关资源
    最近更新 更多