skip to Main Content

Flask in Python is converting all of my lists to strings. Here is my code:

class OpenAI(Resource):
    # methods go here
    def post(self):
        parser = reqparse.RequestParser()  # initialize

        parser.add_argument('model', type=str, required=True)  # add arguments
        parser.add_argument('conversation', type=list, required=True)
        parser.add_argument('functions', type=list, required=False)
        parser.add_argument('settings', type=dict, required=False)

        args = parser.parse_args()  # parse arguments to dictionary

        print(args)
        

        resp, tokencost = bare_api.Chat.OpenAI(args['model'], args['conversation'], functions=args.get("functions"), settings=args.get("settings"))

        resp["tokencost"] = tokencost
        if resp.get("error"):
            return resp, 400
        else:
            return resp, 200
    
api.add_resource(OpenAI, '/chat/openai')  # '/chat' is our entry point

if __name__ == '__main__':
    app.run()  # run our Flask app

This is what I am sending to my endpoint as JSON:

{
    "model": "gpt-3.5-turbo-0613",
    "conversation": [
        {
            "role": "user",
            "content": "ho"
        },
        {
            "role": "assistant",
            "content": "hi"
        }
    ]
}

This is what I am being given from parser.parse_args():

{'model': 'gpt-3.5-turbo-0613', 'conversation': ['role', 'content'], 'functions': None, 'settings': None}

,
instead of what I actually want, which is my postman JSON in the form of a Python dictionary.

How can I fix this?

2

Answers


  1. Chosen as BEST ANSWER

    I figured it out! I needed to use request.json instead of the parser in flask_restful.


  2. Because you’re specifying it as a list

    parser.add_argument('conversation', type=list, required=True)
    

    Try:

    parser.add_argument('conversation', type=dict, required=True)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search