簡體   English   中英

重力表 API 和 python

[英]Gravity form API with python

API 的文檔在這里,我嘗試在 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")

我可以測試哪些替代解決方案?

如果您使用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)

希望有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM