程序正在运行,但我对post有问题,我有错误500,在控制台中我有
File "main.py", line 34, in add_user
cursor.close()
UnboundLocalError: local variable 'cursor' referenced before assignment
127.0.0.1 - - [06/Nov/2019 12:03:38] "POST /add HTTP/1.1" 500 -
import pymysql
from app import app
from db_config import mysql
from flask import jsonify
from flask import flash, request
@app.route('/add', methods=['POST'])
def add_user():
try:
_json = request.json
_wartosc = _json['wartosc_pojazdu']
_email = _json['email']
_datazakupu = _json['data_zakupu_pojazdu']
_datarejestracji = _json('data_pierwszejrejestracji')
if _wartosc and _email and _datazakupu and _datarejestracji and request.method == 'POST':
# save edits
sql = "INSERT INTO tbl_gap(id, wartosc, email, data_zakupu_pojazdu, data_pierwszejrejestracji) VALUES(%d, %d, %s, %s, %s)"
data = (_id, _wartosc, _email, _datazakupu, _datarejestracji)
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute(sql, data)
conn.commit()
resp = jsonify('User added successfull!')
resp.status_code = 200
return resp
else:
return not_found()
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.errorhandler(404)
def not_found(error=None):
message = {
'status': 404,
'message': 'Not Found: ' + request.url,
}
resp = jsonify(message)
resp.status_code = 404
return resp
if __name__ == "__main__":
app.run()
app= Flask(__name__)
app.config['TESTING'] = True
我认为主要问题是json请求,但我找不到哪里。
"wartosc_pojazdu":300,
"email":"casdf@roytuts.com",
"data_zakupu_pojazdu":"1992/12/12",
"data_pierwszejrejestracji": "1992/23/23"
帖子请求正确吗?
这么长时间都找不到解决这个问题的方法,所以谢谢你的建议。
好的,这有帮助,但我仍然得到信息,我有错误的返回语句。
"The view function did not return a valid response. The" TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement. 127.0.0.1 - - [06/Nov/2019 12:43:32] "POST /add HTTP/1.1" 500 -
这正是try
块应该尽可能小的原因。
仔细查看您的代码。如果if
条件是False
,则不定义cursor
。然后,在finally
块中,您正在调用cursor.close()
,但由于未定义cursor
,因此无法执行此操作!
conn
也是如此。
最好的解决方案是确保try
块尽可能小,也许可以将其移动到if
条件内。
您需要在所有情况下定义cursor
:
def add_user():
try:
cursor = None
# other code elided
except Exception as e:
print(e)
finally:
if cursor:
cursor.close()