简体   繁体   中英

python3 flask: get multiple values for key in json post request

I have a simple existing python API using flask that submits a post request in the body, then calls and executes another python script:

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)

script that gets called: 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

To achieve these results:

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

What I am trying to accomplish is instead of passing this in the request body:

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

I want to pass this to the API

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

as this is more cleaner and self explanatory. However the issue I am having is when passing that request to my api, I am getting the error "AttributeError: 'list' object has no attribute 'get'"

I've had no luck debugging why I'm not able to pass my request body in that format. Thanks in advance

Your server is trying to get value given a key from the JSON. The JSON you're sending is a list, not a dictionary. You have to either change the JSON you send to be a dictionary and change the server accordingly, or change your server ( createResults() ) to interpret the JSON as a list and iterate through it.

If you want it to be a dict, you can do something like this: { 1: {{"Password": "asdf"}, ...}, 2: {{"Password": "xzvx"}, ...}, ... }

But a list makes more sense, in my opinion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM