【问题标题】:How to handle strings in headers using requests Python [closed]如何使用请求 Python 处理标头中的字符串 [关闭]
【发布时间】:2020-01-05 20:34:38
【问题描述】:

我有 REST API 我正在尝试获取数据。如果我使用字符串格式的值,API 可以正常工作,但如果使用占位符而不是字符串数据类型或串联字符串的值,API 请求将不起作用如下例所示:

import requests
import pandas as pd
import time
from datetime import date
url = 'http://abc.io/api/v1/modules/get-sale-manager'

payload = {'brand_id': 'sdfghjkl', 'from_timestamp': '1119405211','to_timestamp': '111940511'} #here value's are used

params=payload
headers = {'access_token': 'xxxxxxxxx','secret_key':'xxxxxxx'}
response = requests.get(url, headers=headers,params=payload)
response.json()

相反,我想使用占位符并提供如下计算值:

payload = {'brand_id': str(brand_id), 'from_timestamp': str(from_timestamp),'to_timestamp':'to_timestamp'} #here value's are used

我也想要这个:

payload = {'brand_id': "'"+brand_id+"'", 'from_timestamp': "'"+from_timestamp+"'",'to_timestamp': "'"+timestamp_too+"'"}

但这两种方法都不起作用。我得到500 状态码,但我确信服务器上没有错误,因为直接提供值时。

【问题讨论】:

  • 你能解决你的问题吗?什么不完全有效?你的要求是什么?

标签: python json string rest python-requests


【解决方案1】:

我认为问题在于您的日期时间序列化。您应该将日期时间转换为时间戳,如下所示

from_time_str = str(int(time.mktime(from_timestamp.timetuple())))
to_time_str = str(int(time.mktime(to_timestamp.timetuple())))
payload = {
    'brand_id': str(brand_id),
    'from_timestamp': from_time_str,
    'to_timestamp': from_time_str
}
response = requests.get(url, headers=headers,params=payload)

【讨论】:

    猜你喜欢
    • 2018-03-22
    • 2019-11-29
    • 2018-01-17
    • 2011-11-19
    • 2016-05-24
    • 2019-10-21
    • 1970-01-01
    • 2011-05-23
    • 2020-05-15
    相关资源
    最近更新 更多