python - 如何将来自 Postman 的 Json 数据转换为 python 中的整数?
问题描述
在这里,我使用 MQL5 编写了一个 python 脚本来从 MetaTrader5 获取总历史订单。这是代码,
from_date = datetime(2020, 1, 1)
to_date = datetime.now()
history_orders = mt.history_orders_total(from_date, to_date )
print(history_orders)
我的要求是我需要从用户那里获取 from_date 和 to_date 参数。所以我使用 POST 请求从 Postman 传递了这些参数。这是有效负载
{
"fromDate" : "2020, 1, 1",
"toDate": "2020, 11, 8"
}
它说,
history_orders = mt.history_orders_total(datetime(fromDate), datetime(toDate)) TypeError: an integer is required (got type str)
如何在 python 中将这些 Json 有效负载转换为整数?这是我的代码。
@app.route("/", methods=['POST', 'GET'])
def historyOrderTotal():
fromDate = None
toDate = None
if request.method == 'POST':
fromDate = request.json['fromDate']
toDate = request.json['toDate']
mt.initialize()
history_orders = mt.history_orders_total(datetime(fromDate), datetime(toDate))
print(history_orders)
解决方案
你不太关心整数,你想要datetime
对象。您已决定要<year>, <month>, <day>
作为传入的序列化 JSON 格式的日期。
所以你可能会这样做:
from datetime import datetime
pattern = "%Y, %m, %d"
from_date = datetime.strptime(fromDate, pattern)
to_date = datetime.strptime(toDate, pattern)
assert from_date <= to_date
根据您的用例,您可能想要添加验证等。
我还建议您研究 ISO 8601 日期格式,作为更标准化的日期序列化方式。
调试说明,请根据您的评论尝试此操作:
@app.route("/", methods=['POST', 'GET'])
def historyOrderTotal():
fromDate = None
toDate = None
if request.method == 'POST':
fromDate = request.json['fromDate']
toDate = request.json['toDate']
print("json-from:", fromDate)
print("json-to:", toDate)
pattern = "%Y, %m, %d"
from_date = datetime.strptime(fromDate, pattern)
to_date = datetime.strptime(toDate, pattern)
print("parsed-from:", from_date)
print("parsed-to:", to_date)
if mt.initialize():
history_orders = mt.history_orders_total(from_date, to_date)
print("history-orders", history_orders)
else:
print("initialize() failed, error code =", mt.last_error())
else:
print(">> Not a POST request")
推荐阅读
- node.js - 在套接字事件上更新 MongoDB 数据
- javascript - 使用 Chai 执行断言
- docker - Nexus3:如何在 ec2 中持久化 docker 数据?
- javascript - 幻灯片,使用 HTML、CSS 和 JS 不起作用?卡在第一张幻灯片上不动
- docker - Cannot restart container OCI runtime create failed: container_linux.go:367: starting container process caused: exec:: permission denied: unknown
- python - 月球着陆器问题的 DQN 训练,无法学习。无法收敛
- python - 在批处理模式下将结果导出为 csv 时使用 pyradiomics 禁用科学记数法
- typescript - 根据输入结构推断类型
- r - 如何优化代码以快速计算数据框中的滚动计算?
- api - SharePoint Online - 在批处理模式下通过 rest api 从列表中删除