0

I am trying to familiarize myself with Python, coming from a heavy PHP background. I want to create a JSON object that returns the following:

Endpoint: /dashboard
Request params:{ 
                   method:”get”,
                   headers:headers,
                   url:string,
                   data:{
                           userId: string,
                           date: int
                        }
}

Response: (JSON Object)
{
     code: 200/400,
     message: String,
     data: {     
                  totalCal:
                  remainingCal:
               }
}

Essentially connecting to the database and returning a 200 if the data matches, a 400 if i hit any errors. I came up with this so far, but I'd appreciate any input on how I could perform this better!

@app.route('/dashboard', methods=['GET'])
def availCalories():
    cur = conn.cursor()
    cur.execute('''SELECT remaining_cal FROM daily_cal WHERE user_id = 1 AND day= curdate();''')# WHERE userID=userID in session???
    row_headers=[x[0] for x in cur.description]  #EXTRACT ROW HEADERS
    rv = cur.fetchall()
    json_data=[]
    for result in rv:
        json_data.append(dict(zip(row_headers,result)))
    return json.dumps(json_data)

I've been teaching myself Python for only 3 months now, so a lot of this is trial and error, but I find myself hitting a wall with this!

Thanks for your time in advance!

1
  • 1
    I'm voting to close this question as off-topic because questions about improving already-working code belong on Code Review, not Stack Overflow. Commented Nov 11, 2018 at 20:38

1 Answer 1

1

You are using flask so you can also investigate the jsonify method, which is convenient and common:

flask.json.jsonify(*args, **kwargs)

This function wraps dumps() to add a few enhancements that make life easier. It turns the JSON output into a Response object with the application/json mimetype. For convenience, it also converts multiple arguments into an array or multiple keyword arguments into a dict. This means that both jsonify(1,2,3) and jsonify([1,2,3]) serialize to [1,2,3].

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

1 Comment

Thank you so much! Appreciate the input.

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.