带有python的重力形式API

nfs0ujit  于 2023-02-21  发布在  Python
关注(0)|答案(2)|浏览(101)

API的文档是here,我尝试用python实现这一行

//retrieve entries created on a specific day (use the date_created field)
//this example returns entries created on September 10, 2019
https://localhost/wp-json/gf/v2/entries?search={"field_filters": [{"key":"date_created","value":"09/10/2019","operator":"is"}]}

但是当我尝试在下面的代码中使用python时,我得到了一个错误:

import json
import oauthlib
from requests_oauthlib import OAuth1Session

consumer_key = ""
client_secret = ""

session = OAuth1Session(consumer_key, 
client_secret=client_secret,signature_type=oauthlib.oauth1.SIGNATURE_TYPE_QUERY)

url = 'https://localhost/wp-json/gf/v2/entries?search={"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}'

r = session.get(url)
print(r.content)

错误消息为:

ValueError: Error trying to decode a non urlencoded string. Found invalid characters: {']', '['} in the string: 'search=%7B%22field_filters%22:%20[%7B%22key%22:%22date_created%22,%22value%22:%2209/01/2023%22,%22operator%22:%22is%22%7D]%7D'. Please ensure the request/response body is x-www-form-urlencoded.

一种解决方案是参数化url:

import requests
import json

url = 'https://localhost/wp-json/gf/v2/entries'

params = {
    "search": {"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}
}

headers = {'Content-type': 'application/json'}

response = session.get(url, params=params, headers=headers)

print(response.json())

但是在检索到的条目中,数据没有用指定的日期进行筛选。
在官方文件中,他们给出了一个格式为“09/01/2023”的日期,但在我的数据集中,格式是:“2023-01-10 19:16:59”我必须转换格式吗?我尝试了不同的日期格式

date_created = "09/01/2023"
date_created = datetime.strptime(date_created, "%d/%m/%Y").strftime("%Y-%m-%d %H:%M:%S")

我可以测试哪些替代解决方案?

qco9c6ql

qco9c6ql1#

如果你使用urllib.parse.urlencode函数,那么你的代码看起来像:

import json
import oauthlib
from requests_oauthlib import OAuth1Session

import urllib.parse

consumer_key = ""
client_secret = ""

session = OAuth1Session(consumer_key, 
client_secret=client_secret,signature_type=oauthlib.oauth1.SIGNATURE_TYPE_QUERY)

params = {
    "search": {"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}
}

encoded_params = urllib.parse.urlencode(params)
url = f'https://localhost/wp-json/gf/v2/entries?{encoded_params}'

r = session.get(url)
print(r.content)

希望能有所帮助

z31licg0

z31licg02#

我遇到了同样的问题,并找到了以下代码的解决方案:

params = {
    'search': json.dumps({
        'field_filters': [
            { 'key': 'date_created', 'value': '2023-01-01', 'operator': 'is' }
        ],
        'mode': 'all'
    })
}

encoded_params = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
url = 'http://localhost/depot_git/wp-json/gf/v2/forms/1/entries?' + encoded_params + '&paging[page_size]=999999999' # nombre de réponses par page forcé manuellement

我不是很确定是什么让它工作的,因为我是Python的初学者,但是我发现URL中需要双引号(“)而不是单引号('),所以William Castrillon的解决方案是不够的。
至于日期格式,Gravity Forms似乎可以理解DD/MM/YYYY,它也不需要时间。

相关问题