一、
在訪問python-web項目的某網頁時,顯示decoding to str: need a bytes-like object, tuple found錯誤。
二、
錯誤大概意思是解碼成字符串是需要字節類的對象,但現在發現了一個元組類型對象。
找到后台代碼:
db=pymysql.connect(host='localhost',port=3306,user='root',password='123456',database='stock_db',charset='utf8') cursor=db.cursor() sql="select * from info;" cursor.execute(sql) data_from_mysql=cursor.fetchall() cursor.close() db.close() content=re.sub(r"\{%content%\}", data_from_mysql, content) return content
發現
data_from_mysql=cursor.fetchall()
返回的是是多行記錄,是一個二維元組。類似於((username1,password1,nickname1),(username2,password2,nickname2),(username3,password3,nickname))
而在
content=re.sub(r"\{%content%\}", data_from_mysql, content)
中直接將data_from_mysql當做字符串來處理~
解決:
將
content=re.sub(r"\{%content%\}", data_from_mysql, content)
改成
content=re.sub(r"\{%content%\}", str(data_from_mysql), content)
,也就是使用str來轉化data_from_mysql的類型。
Accept what was and what is, and you’ll have more positive energy to pursue what will be.