我有一个将数据插入数据库表的端点。以下是我的代码: -
@app.route('/user',methods=['POST'])
def user():
data = request.form
loginfo= {
'user_id' : data['user_id'],
'dob' : data['dob'],
'gender' : data['gender'],
'imei1' : data['imei1'],
'epoch' : data['epoch'],
}
if CONNECTION is None:
return '{"status":503,"error":"MySQL not connected. Service Unavailable."}'
try:
create_user_profile(loginfo)
except Exception,e:
return '{"status":500,"error":' + str(e) + '}'
return '{"status":200}'
在我的访问日志中,我收到以下日志。
[pid: 17877|app: 0|req: 1/1] 127.0.0.1 () {36 vars in 494 bytes} [Thu May 21 05:49:22 2015] POST /user => generated 14 bytes in 11 msecs (HTTP/1.0 200) 2 headers in 79 bytes (1 switches on core 0)
虽然它正在返回200
(因为我已经应用了try除外),但它仍然没有在表中插入记录。无论我通过uwsgi --reload /var/run/uwsgi.pid
重新加载uwsgi,它都能正常运行。我假设重新加载uwsgi打破MySQL连接,重新制作它然后重新开始,因此工作正常。
我该如何调试?这个错误多次出现。我一直在重装。
PS:因为我已经应用了try-except因此我无法查看错误。它部署在生产上。我现在已经打印出来了。接下来会让你们知道。
在我的另一个项目中,发生了同样的错误,但它返回500,因为我没有应用try-except。
更新
以下是我的代码。请注意,为了方便起见,已修剪了一些变量。如果您发现任何语法错误,请忽略它们。休息逻辑保持不变。
def data_exist(self,data_exist_query):
with self.connection:
cur = self.connection.cursor()
cur.execute(data_exist_query)
rows = cur.fetchall()
if len(rows) >= 1 :
return True
else :
return False
def create_table_index_query(self,tc_query,in_query=None,ix_query=None,show_index_query=None):
with self.connection:
cur = self.connection.cursor()
cur.execute(tc_query)
cur.execute(in_query)
self.connection.commit()
if ix_query:
cur = self.connection.cursor()
cur.execute(show_index_query)
rows = cur.fetchall()
if len(rows) < 3 :
print 'Creating Index'
cur.execute(ix_query)
self.connection.commit()
def create_user_profile(self, dct):
rows = (str(dct['user_id']),str(datetime.strptime(dct['dob'],'%d-%m-%Y')), str(dct["gender"]), str(dct["imei1"]),str(dct['epoch']))
found = False
data_exist_query = "SELECT * from USER_PROFILE WHERE imei1 = '%s'" % (dct['imei1'],)
try:
found = self.data_exist(data_exist_query)
except:
pass
if not found:
in_query = "INSERT INTO USER_PROFILE (user_id,dob, gender, imei1,epoch) "\
"VALUES ('%s','%s','%s','%s','%s') " % rows
self.create_table_index_query(tc_query,in_query)