首页 > 解决方案 > 如何将来自 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)

标签: pythonjsonpostmanmql5metatrader5

解决方案


你不太关心整数,你想要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")

推荐阅读