Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask application GET returning the same thing twice

Tags:

python

flask

I currently have two methods to which I call simultaneously (via HTTP in Java)

For some reason, there is an instance in which getAcc() returns the same account info twice? I don't quite understand why this is.

I think it's possible that the second call to get_account is happening before toggleUse() is called (and therefore the IN_USE variable is not set to 1 yet). Does anyone know how to fix this? I've done some reading on the web, and I believe the term is Serialization. I've seen this mostly regarding databases, but have seen almost no references on how to "lock" the method. I could create a lock and do "with lock:" but I've heard that's not the way to go.

@app.route('/getAcc')
def get_account():
    try:
        cursor.execute("SELECT USER,PASS FROM ACCOUNTS WHERE TUT_DONE = 0 AND IN_USE = 0 LIMIT 1;")
        return jsonify(data=cursor.fetchall())
    except (AttributeError, MySQLdb.OperationalError):
        open_db()
        return get_account()


@app.route('/toggleUse', methods=['POST'])
def toggle_use():
    try:
        username = request.values['username']
        update_stmt = (
          "UPDATE ACCOUNTS SET IN_USE = !IN_USE WHERE USER = (%s)"
        )
        data = (username,)
        cursor.execute(update_stmt,data)
        db.commit()
        return 'Account ' + str(username) +  ' IN_USE toggled'

    except (AttributeError, MySQLdb.OperationalError):
        open_db()
        return toggle_use()
like image 878
k9b Avatar asked Jan 30 '17 18:01

k9b


1 Answers

I would have to test it, but suspect you have an issue with your except opening a db connection and calling itself.

Have you tried to create a connection that give you a pool you can just call?

connection = pyodbc.connect(connection_string, autocommit=True) #I think you can set autocommit here.

@app.route('/getAcc')
def get_account():
    try:
        cursor = connection.cursor()
        cursor.execute("SELECT USER,PASS FROM ACCOUNTS WHERE TUT_DONE = 0 AND IN_USE = 0 LIMIT 1;")
        return jsonify(data=cursor.fetchall())
    except (AttributeError, MySQLdb.OperationalError):
        # Return a meaningful message

Same thing for the other function.

like image 99
Kelvin Avatar answered Oct 28 '22 11:10

Kelvin