Search code examples
pythonpython-3.xpymysql

Python service - get json body


I have an endpoint that returns data based on user selection. The user sends me these values : Name, ID, Age, Gender.

Then I use pymysql to query a table where Name = given name, for received ID and Gender.

But how do I get these values in python ?

@app.route('/userInfo', authorizer=authorizer)
def data():
try:
    params = app.current_request.query_params or json_body?
except:
    pass

  // get individual fields and assign to variables?

  sql = "SELECT SurveyResult From UserInfo WHERE Name = %(name)s AND Gender = %(gender)s AND Age = %(age)s

And then

   cursor.execute(sql, { 'name': ? , 'gender': ? , 'age': ?
  input values here? })

What is the safest way to get request those values to the service ?


Solution

  • Assuming you are using flask, here is a way to get the params/post data

    Note : you need to import request from flask import request

    POST :

    name = request.form['name']

    GET :

    name = request.args['name']

    and then insert them

    cursor.execute(sql, (name, gender, age))

    remember to commit

    connection.commit()

    To make your life easier, consider using an ORM such as peewee