[英]Python Flask API Restful
How Are you? 你好吗? I am play, with Python + Flask + MySQL to create a API. 我在玩,用Python + Flask + MySQL创建一个API。 But I have some errors! 但是我有一些错误! With the connection. 与连接。 Here is the code of the Entry Point. 这是入口点的代码。
@app.route('/add', methods=['POST'])
def add_user():
try:
_json = request.json
_name = _json['name']
_email = _json['email']
_password = _json['pwd']
# validate the received values
if _name and _email and _password and request.method == 'POST':
#do not save password as a plain text
_hashed_password = generate_password_hash(_password)
# save edits
sql = "INSERT INTO user(user_name, user_email, user_password) VALUES(%s, %s, %s)"
data = (_name, _email, _hashed_password,)
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute(sql, data)
conn.commit()
resp = jsonify('User added successfully!')
resp.status_code = 200
return resp
else:
return not_found()
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
And here the error 这是错误
I'm installed all the dependencies, but...I dont know. 我已经安装了所有依赖项,但是...我不知道。 I connected the cursor, previosly, but nothing. 我粗略地连接了光标,但什么也没有。
Can you help me? 你能帮助我吗? Thanks! 谢谢!
The cursor variable defined in your try clause and being used in your finally clause. 在您的try子句中定义并在您的finally子句中使用的游标变量。 You probably getting exception before cursor being defined (I assume when you trying to create the connection to mysql) and therefore you receiving this error. 在定义游标之前,您可能会遇到异常(我假设您试图创建与mysql的连接),因此您收到此错误。
If you catch an exception before you define a cursor variable -> you cannot close the cursor because you interpreter doesn't know about it. 如果在定义游标变量->之前捕获到异常,则您将无法关闭游标,因为您的解释器对此一无所知。 I think the best way is to remove finally
block and move 我认为最好的方法是移除finally
障碍物并移动
cursor.close()
conn.close()
to the try
block after conn.commit()
. 到conn.commit()
之后的try
块。 With that approach you can avoid error that you received. 通过这种方法,您可以避免收到的错误。
PS It's not a good practice to catch errors with except Exception as e:
because it impossible to understand what have been failed. PS捕获错误不是一个好习惯,因为except Exception as e:
因为无法理解失败的原因。 It is better to define what errors you could face with and use the specific exceptions. 最好定义可能遇到的错误并使用特定的异常。
So what's happening is that your try...catch
is being triggered before the cursor is being made. 所以发生的事情是在创建游标之前触发了try...catch
。 If you look at your log, two lines above the beginning of the traceback it says: 如果查看日志,则在回溯开始的上方两行显示:
'NoneType' object is not subscriptable “ NoneType”对象不可下标
This is referring to request.json
not being defined. 这是指未定义request.json
。 It is not defined because you are not sending your request with JSON. 未定义,因为您没有使用JSON发送请求。 Instead you are sending it with query parameters . 相反,您将其与查询参数一起发送。 To fix this you can either use request.args
or add argument checks. 要解决此问题,您可以使用request.args
或添加参数检查。
You should also change the finally
clause to check whether cursor
and conn
are defined. 您还应该更改finally
子句以检查是否定义了cursor
和conn
。
@app.route('/add', methods=['POST'])
def add_user():
# Placeholder values
conn = None
cursor = None
try:
# This checks the body so you won't get an error thrown
if request.json.get("name") is None or request.json.get("email") is None or request.json.get("pwd") is None:
return "invalid body"
_json = request.json
_name = _json['name']
_email = _json['email']
_password = _json['pwd']
# validate the received values
if _name and _email and _password and request.method == 'POST':
#do not save password as a plain text
_hashed_password = generate_password_hash(_password)
# save edits
sql = "INSERT INTO tbl_user(user_name, user_email, user_password) VALUES(%s, %s, %s)"
data = (_name, _email, _hashed_password,)
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute(sql, data)
conn.commit()
resp = jsonify('User added successfully!')
resp.status_code = 200
return resp
else:
return not_found()
except Exception as e:
print(e)
finally:
# Check if defined
if cursor is not None:
cursor.close()
if conn is not None:
conn.close()
To send a JSON request in Postman, go to the body tab and set the type to Raw
and then on the dropdown, change it from Text
to JSON (application/json)
. 要在Postman中发送JSON请求,请转到正文标签并将类型设置为Raw
,然后在下拉列表中将其从Text
更改为JSON (application/json)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.