You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Paylocity API拉取数据时出现TypeError报错如何解决?

问题原因及解决方法

报错定位

  • 报错触发的核心原因是urllib.parse.urlencode被重复调用:你已经将参数字典编码为字符串赋值给body_params,后续发起请求时又对这个字符串再次执行urlencode操作,而urlencode仅支持传入字典/键值对序列,传入字符串就会触发该TypeError: not a valid non-string sequence or mapping object。
  • 可以通过逐行加打印、加断点的方式确认具体报错行,和上述判断一致。

修复方案

  • 移除重复的urlencode逻辑:requests的data参数原生支持直接传入字典,不需要手动做表单编码,框架会自动处理编码逻辑并添加对应请求头。
  • 改用requests内置的.json()方法解析响应,避免手动调用json.loads可能引发的编码问题。
  • 提前修正token字段名:OAuth2标准返回的访问令牌字段为access_token,你原有代码中调用的response['access']不存在,后续会触发KeyError,可提前调整。

修复后的完整代码如下:

import requests
import json

client_id = "替换为你的实际client_id"
client_secret = "替换为你的实际client_secret"
company_id = "替换为你的实际company_id"
prod_auth_url = 'https://apisandbox.paylocity.com/IdentityServer/connect/token'
# 直接定义参数字典,不需要提前编码
body_params = {'grant_type': 'client_credentials','scope':'WebLinkAPI'}

# 发起请求,data直接传字典即可
auth_response = requests.post(prod_auth_url, auth=(client_id, client_secret), data=body_params)
# 先校验请求状态,避免异常响应解析失败
if auth_response.status_code == 200:
    response = auth_response.json()
    # 修正token字段为access_token
    api_call_headers = {'Authorization': 'Bearer ' + response['access_token']}
else:
    print(f"鉴权请求失败,状态码:{auth_response.status_code},返回信息:{auth_response.text}")

内容的提问来源于stack exchange,提问作者Kevin Nash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 15:15:04