问题描述
有一个小型的python应用程序,该API应用程序向gumroad提出了API验证请求,我正在尝试使用urllib进行此操作,但这给了我404错误。 有趣的是,与urllib相比,使用请求包(导入请求等)时,URL可以完美运行。
我需要实现的cURL请求如下:
curl https://api.gumroad.com/v2/licenses/verify \
-d "product_permalink=PRODUCT_PERMALINK" \
-d "license_key=INSERT_LICENSE_KEY" \
-X POST
如果密钥有效以及其他一些统计信息,它将返回“成功”:true 。
这是我的代码:
import json
import urllib.request
license_key = "yyyyyyyy-yyyyyyyy-yyyyyyyy-yyyyyyyy"
user_email = "xxxxx@xxxxx.com"
def licenseCheck(license_key,user_email,productID="xyzxy"):
url_ = "https://api.gumroad.com/v2/licenses/verify"
pf_permalink = productID
params = json.dumps({'product_permalink=': pf_permalink,'license_key=': license_key})
data=params.encode()
req = urllib.request.Request(url_,headers={'Content-Type':'application/json'})
response = urllib.request.urlopen(req,data,timeout=10)
get_response = json.loads(response.read())
if get_response['success'] and get_response['email'].lower() == user_email.lower():
status = True
else:
get_response = "Failed to verify the license."
return status,get_response,license_key
print(licenseCheck(license_key,user_email))
程序给出404错误的行是这样的:
response = urllib.request.urlopen(req,timeout = 10)
解决方法
之所以会发生这种情况,是因为在您的curl示例中,您将数据作为两个POST参数传递,而在python脚本中,您将它们作为JSON正文传递。另外,您需要考虑错误处理。
import json
from urllib import request,parse,error
license_key = "yyyyyyyy-yyyyyyyy-yyyyyyyy-yyyyyyyy"
user_email = "xxxxx@xxxxx.com"
def licenseCheck(license_key,user_email,productID="xyzxy"):
url_ = "https://api.gumroad.com/v2/licenses/verify"
pf_permalink = productID
params = {'product_permalink': pf_permalink,'license_key': license_key}
data=parse.urlencode(params).encode('ascii')
req = request.Request(url_,data=data)
try:
response = request.urlopen(req)
get_response = json.loads(response.read())
except error.HTTPError as e: get_response = json.loads(e.read())
status = False
if get_response['success'] and get_response['email'].lower() == user_email.lower():
status = True
else:
get_response = "Failed to verify the license."
return status,get_response,license_key
print(licenseCheck(license_key,user_email))