我有一個包含波斯語言字符串的變量,並且我無法正確地將該字符串保存到數據庫中。我正在使用REST API的燒瓶,並且我從客戶端獲取字符串。這是我的代碼:使用python將波斯語字符串保存到mysql數據庫中
@app.route('/getfile',methods=['POST'])
def get_file():
#check the validity of json format
if not request.json or not 'FileName' in request.json:
abort(400)
if not request.json or not 'FilePath' in request.json:
abort(400)
if not request.json or not 'Message' in request.json:
abort(400)
#retreive data from request
filename_=request.json['FileName']
filepath_=request.json['FilePath']
message_=request.json['Message']
try:
conn = mysql.connector.connect(host=DBhost,database=DBname,user=DBusername,password=DBpassword)
except:
return jsonify({'Result':'Error, Could not connect to database.'})
cursor_ = conn.cursor()
query_ = "INSERT INTO sms_excel_files VALUES(null,%s,%s,%s,0)"
data_ =(filename_,Dst_num_file,message_)
cursor_.execute(query_, data_)
last_row_id_=cursor_.lastrowid
conn.commit()
有問題的變量是message_
。我可以正確保存英文文本,但不能保存波斯文。我還在代碼頂部添加了# -*- coding: utf-8 -*-
,但這並未解決問題。但是,如果我手動使用Persian字符串填充message_
,它會正確保存到數據庫中。此外,如果我簡單地返回message_
的值,則是正確的。
例如,這是被插入時message_
包含字符串數據庫「سلام」:
سلام
任何幫助表示讚賞。
我不認爲它像你所解釋的那麼難。我可以在message_ = request.json ['Message']'之後正確返回message_。將該字符串插入數據庫時會損壞該字符串。數據庫排序規則是utf8_general_ci,列也是utf8_general_ci。 – Sinai
@Sinai你究竟是否確實可以正確返回message_'?你把它轉儲到一個文件中,你打印出來給瀏覽器還是其他東西? – Binarus
我打印出來給瀏覽器。我只是在我的代碼中的'message_ = request.json ['Message']'之後放了一個'return message_',我可以看到確切的字符串! – Sinai