I am trying to add data to my mysql database with a HTTP post request, but in the way it's set up now, if we post more than once, the data from the first post gets changed to 0 because I declare all the variables in the same definition. How can I fix this?
I have tried to declare a global variable in a second def, but it just loops that def instead of the one I have now.
#!/usr/bin/env python
import pymysql.cursors
from flask import Flask, request
from Crypto.Cipher import AES
connection = pymysql.connect('localhost','esp', 'password', 'points')
app = Flask(__name__)
@app.route('/post', methods = ["POST"])
def post():
hits1 = 0
hits2 = 0
punch1 = 0
punch2 = 0
kick1 = 0
kick2 = 0
takedown1 = 0
takedown2 = 0
print(request.data)
cipher = AES.new("abcdefghijklmnop")
decryptedData = cipher.decrypt(request.data)
data = decryptedData.decode("utf-8")
print(data)
print(data)
if(data[:1]=="e"):
if(data[1:2] == "1"):
hits1+=1
print(hits1)
if (data[:1]=="1"):
if(data[1:2]=="1"):
punch1+=1
elif(data[1:2]=="2"):
kick1+=1
elif(data[1:2]=="3"):
takedown1+=1
elif(data[:1]=="2"):
if(data[1:2]=="1"):
punch2+=1
elif(data[1:2]=="2"):
kick2+=1
elif(data[1:2]=="3"):
takedown2+=1
points1 = punch1 + kick1 * 2 + takedown1 * 3
points2 = punch2 + kick2 * 2 + takedown2 * 3
print(points1)
print(points2)
try:
with connection.cursor() as cursor:
cursor.execute("INSERT INTO points values({0}, {1}, {2}, {3}, {4}, {5})".format(1, hits1, kick1, punch1, takedown1, points1))
cursor.execute ("INSERT INTO points values({0}, {1}, {2}, {3}, {4}, {5})".format(2, hits2, kick2, punch2, takedown2, points2))
connection.commit()
print ("Data committed")
return 'ok'
except:
connection.close()
app.run(host='0.0.0.0', port= 8090)
The value of the previous post gets changed to 0, but i want to keep that value