无法将烧瓶sqlAlchemy连接到mysql数据库

时间:2020-09-25 23:05:43

标签: python mysql flask-sqlalchemy pymysql alembic

我正在尝试将我的flask应用程序与MySQL数据库连接。 这是MySQL数据

mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.01 sec)

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| alchemy            |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

mysql> SHOW GLOBAL VARIABLES LIKE 'PORT';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.01 sec)

这是初始 .py

from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)

from app import routes, models

这是config.py

import os
basedir = os.path.abspath(os.path.dirname(__file__))

class Config(object):
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'test-key-motherfucker'
    SQLALCHEMY_DATABASE_URI = 'mysql://root@127.0.0.1:3360/alchemy'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

和models.py

from app import db

class Test(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True, unique=True)

    def __repr__(self):
        return '<Test {}>'.format(self.name)

当我尝试使用db初始化

flask db init
flask db upgrade

我收到

sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:mysql

我尝试使用pymysql SQLALCHEMY_DATABASE_URI ='mysql + pymysql://rootl@127.0.0.1:3360 / alchemy'

如何将mysql与sqlalchemy连接?

1 个答案:

答案 0 :(得分:1)

为什么连接到mysql数据库是正确的

mysql://username:password@server/db

首先尝试

SQLALCHEMY_DATABASE_URI = 'mysql://root:@127.0.0.1/alchemy'

如果它不起作用,请尝试

SQLALCHEMY_DATABASE_URI = 'mysql://root:@127.0.0.1:3306/alchemy'

如果它不起作用,请尝试

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:@127.0.0.1:3306/alchemy

对不起,我提出了很多选择,但我希望其中一个能起作用:)

如果没有成功,则问题不在于与数据库的连接