0

I am sending an ajax GET request to a flask server (http://localhost:5000/req/?q=139,2,10,60,5,1462,7,5,6,9,17,78) in order to retrieve some values and assign them to a Dataframe. Doing it manually, it works fine:

df = pd.DataFrame(data=[[139,2,10,60,5,1462,7,5,6,9,17,78]],columns=['col1','col2','col3','col4','col5','col6','col7','col8','col9','col10','col11','col12'])

but i need the numbers to come from request.args via ajax and then be based in the Dataframe as an array.

@app.route('/req/', methods=['GET'])
def foo():
    args = dict(request.args.to_dict())
    t = request.args["q"]
    return getResults(t), 200

And the getResults() would be something like:

def getResults(name):
    df = pd.DataFrame(data=[[name]], columns=['col1','col2','col3','col4','col5','col6','col7','col8','col9','col10','col11','col12'])
    """"

but of course this doesn't work. Gives an error: ValueError: 12 columns passed, passed data had 1 columns

How can i do this ? I've tried splitting the string, try to convert to an array..nothing worked.

1
  • Why args = dict(request.args.to_dict()) ? request.args is already a nice dict Commented Jul 13, 2020 at 19:08

1 Answer 1

1

The args is resolved as a string, so after t = request.args["q"], t is "139,2,10,60,5,1462,7,5,6,9,17,78", you need a list of int

@app.route('/req') # GET only is default method
def foo():
    t = request.args["q"]
    t = [int(val) for val in t.split(",")]
    return getResults(t) # 200 is the default status code

And

def getResults(name):
    df = pd.DataFrame(data=[name], # no extra []

Also prefer /req (that allows both with and without trailing slash) rather than /req/ that accept only one , refer to this for detail

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, Thanks @azro, just a small fix, it is: int(val) for val (not van), and for anyone else, in the function it should be: pd.DataFrame(data=[name]..... ps: i will accept it in 4 min :) Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.