python3 flask:在json post请求中获取key的多个值

时间:2018-01-08 20:36:39

标签: python json flask

我有一个简单的现有python API使用flask在body中提交post请求,然后调用并执行另一个python脚本:

testflask.py

import testlogicdf
import json 
from flask import Flask, json, request, Response
app = Flask(__name__)


@app.route("/results", methods=['POST'])
def createResults():
  entry = request.get_json().get('entry', '')
  passcode = request.get_json().get('passcode', '')


  data = testlogicdf.test(entry, passcode)
  return Response(data, mimetype='application/json')    

if __name__ == "__main__":
    app.run(debug = True, host='localhost', port=8080, passthrough_errors=False)
被调用的

脚本:testlogicdf.py

 import pandas as pd

def passcodeMapping(entry):
  result = ''
  entry = int(entry)
  if (entry in range(1000, 3000)):       
    result = 'UKNOWN'
  elif (entry in range(0, 100)):
    result = 'Success'
  elif (entry in range(200, 999)):
    result = 'Error'
  return result

def test(entry, passcode):
    df = pd.DataFrame()
    testInput = zip(entry, passcode)
    for entry, passcode in testInput:
        result = passcodeMapping(entry)
        df = df.append({'Entry': entry, 'Passcode': passcode, 'Second Attempt': result}, ignore_index=True)
    response = df.to_json(orient='records')
    return response

要实现这些结果:

 [
    {
        "Entry": 2442,
        "Passcode": "Restart",
        "Second Attempt": "UKNOWN"
    },
    {
        "Entry": 24,
        "Passcode": "Try Again",
        "Second Attempt": "Success"
    },
    {
        "Entry": 526,
        "Passcode": "Proceed",
        "Second Attempt": "Error"
    }
]

我想要完成的不是在请求正文中传递它:

{
"entry":[2442, 24, 526],
"passcode":["Restart", "Try Again", "Proceed"]
}

我想将此传递给API

[{
    "entry": "2442",
    "passcode": "Restart"
}, {
    "entry": "24",
    "passcode": "Try Again"
}, {
    "entry": "526",
    "passcode": "Proceed"
}]

因为这更清洁,更自我解释。但是我遇到的问题是将该请求传递给我的api时,我收到错误" AttributeError:' list'对象没有属性' get'"

我没有运气调试为什么我无法以该格式传递我的请求正文。提前致谢

1 个答案:

答案 0 :(得分:0)

您的服务器正在尝试使用JSON中的密钥获取值。您发送的JSON是列表,而不是字典。您必须将发送的JSON更改为字典并相应地更改服务器,或者更改服务器(createResults())以将JSON解释为列表并迭代它。

如果你想让它成为一个词典,你可以这样做: { 1: {{"Password": "asdf"}, ...}, 2: {{"Password": "xzvx"}, ...}, ... }

但在我看来,列表更有意义。