Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →
from flask import Flask
from flask_restful import Resource, Api
from flask_restful import reqparse
from flask_mysqldb import MySQL



mysql = MySQL()
app = Flask(__name__)

# MySQL configurations
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'itemlistdb'
app.config['MYSQL_HOST'] = 'localhost'




    mysql.init_app(app)

    api = Api(app)

    class AuthenticateUser(Resource):
        def post(self):
            try:
                # Parse the arguments

                parser = reqparse.RequestParser()
                parser.add_argument('email', type=str, help='Email address for Authentication')
                parser.add_argument('password', type=str, help='Password for Authentication')
                args = parser.parse_args()

                _userEmail = args['email']
                _userPassword = args['password']

                conn = mysql.connection
                cursor = conn.cursor()
                cursor.callproc('sp_AuthenticateUser',(_userEmail,))
                data = cursor.fetchall()


                if(len(data)>0):
                    if(str(data[0][2])==_userPassword):
                        return {'status':200,'UserId':str(data[0][0])}
                    else:
                        return {'status':100,'message':'Authentication failure'}

            except Exception as e:
                return {'error': str(e)}


    class GetAllItems(Resource):
        def post(self):
            try: 
                # Parse the arguments
                parser = reqparse.RequestParser()
                parser.add_argument('id', type=str)
                args = parser.parse_args()

                _userId = args['id']

                conn = mysql.connection
                cursor = conn.cursor()
                cursor.callproc('sp_GetAllItems',(_userId,))
                data = cursor.fetchall()

                items_list=[];
                for item in data:
                    i = {
                        'Id':item[0],
                        'Item':item[1]
                    }
                    items_list.append(i)

                return {'StatusCode':'200','Items':items_list}

            except Exception as e:
                return {'error': str(e)}

    class AddItem(Resource):
        def post(self):
            try: 
                # Parse the arguments
                parser = reqparse.RequestParser()
                parser.add_argument('id', type=str)
                parser.add_argument('item', type=str)
                args = parser.parse_args()

                _userId = args['id']
                _item = args['item']

                print _userId;

                conn = mysql.connection
                cursor = conn.cursor()
                cursor.callproc('sp_AddItems',(_userId,_item))
                data = cursor.fetchall()

                conn.commit()
                return {'StatusCode':'200','Message': 'Success'}

            except Exception as e:
                return {'error': str(e)}



    class CreateUser(Resource):
        def post(self):
            try:
                # Parse the arguments
                parser = reqparse.RequestParser()
                parser.add_argument('email', type=str, help='Email address to create user')
                parser.add_argument('password', type=str, help='Password to create user')
                args = parser.parse_args()

                _userEmail = args['email']
                _userPassword = args['password']

                conn = mysql.connection
                cursor = conn.cursor()
                cursor.callproc('spCreateUser',(_userEmail,_userPassword))
                data = cursor.fetchall()

                if len(data) is 0:
                    conn.commit()
                    return {'StatusCode':'200','Message': 'User creation success'}
                else:
                    return {'StatusCode':'1000','Message': str(data[0])}

            except Exception as e:
                return {'error': str(e)}



    api.add_resource(CreateUser, '/CreateUser')
    api.add_resource(AuthenticateUser, '/AuthenticateUser')
    api.add_resource(AddItem, '/AddItem')
    api.add_resource(GetAllItems, '/GetAllItems')

    if __name__ == '__main__':
        app.run(debug=True)

It throws with an error "connection object is not callable" . I have searched all possible questions here in @stackoverflow posted before but unable to find the solution for the same.. If anyone has the solution please do help me over it. Thank you .

Note: now this code is working... Thank you

share|improve this question
    
Please be careful to post the full traceback including the name of the exception into the question itself. – Antti Haapala Aug 20 at 6:11
    
i.e. your problem very specifically is that you're catching the exception that you're not prepared to handle, but also you lose the original formatting, and are returning the str(e); minimally you should add traceback.print_exc() to your exception handler in such cases while you're still debugging. – Antti Haapala Aug 20 at 6:13
    
@AnttiHaapala can you please edit the code with yours.. I am very beginer in this. – Tanmoy Sarkar Aug 20 at 6:16
    
Add import traceback at the top of your file, and just before return {'error': str(e)} add traceback.print_exc() so that you can see the actual traceback on the server side. – Antti Haapala Aug 20 at 6:17
    
@AnttiHaapala look the error comes like this .. File "api.py", line 134 return {'error': str(e)} ^ IndentationError: unindent does not match any outer indentation level ...I have added ... except Exception as e: traceback.print_exc() return {'error': str(e)} – Tanmoy Sarkar Aug 20 at 6:24
up vote 1 down vote accepted

Replace

conn = mysql.connect()
cursor = conn.cursor()

with

conn = mysql.connection
cursor = conn.cursor()

Read more at the Flask-MySQLdb’s docs.

share|improve this answer
    
now it thorows an error ... { "error": "global name 'cursor' is not defined" } – Tanmoy Sarkar Aug 20 at 6:09
    
@TanmoySarkar You have to use cursor = and not conn = – Nehal J Wani Aug 20 at 6:10
    
now it throws ... { "error": "global name 'conn' is not defined" } ....... – Tanmoy Sarkar Aug 20 at 6:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.