今天在使用Flask连接mysql的时候,遇到了一个报错:encoding with ‘idna’ codec failed (UnicodeError: label empty or too long)
网上查了一下说是字符集的问题,然后尝试修改了一下字符集,结果还是不行。
最后去翻阅SQLAlchemy的文档,才发现是url中存在特殊字符@,需要转义才可以正常使用。
然后我就尝试修改了下代码,结果错误就没有了。
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import urllib.parse
from sqlalchemy import text
app = Flask(__name__)
hostname = "localhost"
port = 3306
username = "test"
password = urllib.parse.quote_plus("test@123..")
# password = "gxy@123.."
database = "interSys"
app.config["SQLALCHEMY_DATABASE_URI"] = f"mysql+pymysql://{username}:{password}@{hostname}:{port}/{database}"
db = SQLAlchemy(app)
with app.app_context():
try:
with db.engine.connect() as conn:
rs = conn.execute(text("select 1"))
print(rs.fetchone())
except Exception as e:
print(f"Error: {e}")
最后说下我用的版本:
python:3.11.9
Flask:3.0.3
Flask-SQLAlchemy:3.1.1
SQLAlchemy:2.0.32
PyMySQL:1.1.1
urllib3:2.2.2
mysql:8.0.39