在此python代码中对此POST方法的json请求正确吗?

程序正在运行,但发布时出现问题,错误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)"
            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 - 
ygdbl 回答:在此python代码中对此POST方法的json请求正确吗?

这就是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() 
本文链接:https://www.f2er.com/3152644.html

大家都在问