0

I am trying to get records from mysql, if records found then adding success status with the mysql records and return by jsonify function, On the other side i am getting response and then check whether the status is success or not.

This is my response format

 [ { "SQL_STATUS": true }, { "id": "126","etc":"etc"} ]

i need to check whether the SQL_STATUS is true or false, so i tried the below method

      response.SQL_STATUS   

but got the below error

      AttributeError: 'Response' object has no attribute 'SQL_STATUS'

These are my code

 def Details(self,request):

    res = self.db.SelectByConditionModel(request,self.model)


    if res.SQL_STATUS == True:
        response_data = SuccessResponse('','Success')
    else:
        response_data = ErrorResponse(res,"Database Error")

    return response_data

this is the fundtion where i am doing select operation

 @staticmethod
def SelectByConditionModel(request,model):

    try:

        where_condition  = []

        for key in request:
            where_condition.append(key+"='"+conn.escape_string(str(request[key]))+"'")


        where_condition_str = ', '.join(where_condition)

        sql = ''' SELECT * from %s WHERE %s ''' %(model.TABLE, where_condition_str)


        cursor.execute(sql)
        row_headers=[x[0] for x in cursor.description]
        conn.commit()
        data = cursor.fetchall()

        json_data=[]

        json_data.append({"SQL_STATUS" : True})

        for result in data:
            json_data.append(dict(zip(row_headers,result)))


        return jsonify(json_data)

    except Exception as e:

        return str(e)

i need to check SQL_STATUS is true or false, please help me

Ashok Sri
  • 196
  • 2
  • 14

1 Answers1

2

Your json_data is a list. lists are accessed by indexing, not through attributes.

json_data[0]['SQL_STATUS']

This would give you what you want. But you're turning it into a string before returning - so you'll need to turn it back into an object to access it like that.

@staticmethod
def SelectByConditionModel(request,model):
    try:
        where_condition  = []
        for key in request:
          where_condition.append(key+"='"+conn.escape_string(str(request[key]))+"'")
        where_condition_str = ', '.join(where_condition)
        sql = ''' SELECT * from %s WHERE %s ''' %(model.TABLE, where_condition_str)
        cursor.execute(sql)
        row_headers=[x[0] for x in cursor.description]
        conn.commit()
        data = cursor.fetchall()

        json_data=[]

        for result in data:
            json_data.append(dict(zip(row_headers,result)))

        return True, jsonify(json_data)

    except Exception as e:

        return False, str(e)

Here I'm returning SQL_STATUS separately from the method. Instead of adding it to the response. You can then do:

def Details(self,request):
    sql_status, res = self.db.SelectByConditionModel(request,self.model)
    if sql_status:
        response_data = SuccessResponse('','Success')
    else:
        response_data = ErrorResponse(res, "Database Error")
    return response_data
rdas
  • 20,604
  • 6
  • 33
  • 46
  • thank you, it's working now. but it's throw an error while framing response `TypeError: is not JSON serializable` – Ashok Sri Apr 20 '19 at 06:59
  • here is the method, i wrote for framing response for the API call `def SuccessResponse(data,message): return json.dumps({'status':'success','data':data,'message':message,'status_code':200}), 200, {'ContentType':'application/json'}` – Ashok Sri Apr 20 '19 at 07:01
  • when i put the `res` to this method, i got this error `response_data = SuccessResponse(res,'Success')` if i use empty string instead, there is no error `response_data = SuccessResponse("",'Success')` – Ashok Sri Apr 20 '19 at 07:10
  • Yeah this is the reason: https://stackoverflow.com/questions/7907596/json-dumps-vs-flask-jsonify – rdas Apr 20 '19 at 07:11
  • You don't need to do `json.dumps` if you've used `jsonify` already. – rdas Apr 20 '19 at 07:12
  • ok, i have changed to make_response `return make_response(jsonify({'status':'success','data':data,'message':message,'status_code':200}),200)` but now also having same pblm, is there any response size restriction in python-flask? – Ashok Sri Apr 20 '19 at 07:18
  • I don't think you've understood how `jsonify` works. It's returning a proper response object already. – rdas Apr 20 '19 at 07:20