flask link mysql database pits

#config.py


MYSQL_NAME = 'root'
MYSQL_PASSWORD = 'zyms90bdcs'
MYSQL_HOST = 'xxxx'
MYSQL_POST = '3306'
MYSQL_DBNAME = 'flask_sql'
MYSQL_CHARSET = 'utf8'

# SQLALCHEMY_DATABASE_URI = 'mysql://{}:{}@{}:{}/{}?charset={}'.format(MYSQL_NAME,MYSQL_PASSWORD,
#                                                                      MYSQL_HOST,MYSQL_POST,
#                                                                      MYSQL_DBNAME,MYSQL_CHARSET)

SQLALCHEMY_DATABASE_URI = 'mysql://{}:{}@{}:{}/{}'.format(MYSQL_NAME,MYSQL_PASSWORD,
                                                                     MYSQL_HOST,MYSQL_POST,
                                                                     MYSQL_DBNAME)

This is the link to the database configuration file, if you create a file in the db table models, and create (shell or direct routes created) create_all ()

 

#models

import pymysql
from flask_sqlalchemy import SQLAlchemy

pymysql.install_as_MySQLdb()

db = SQLAlchemy()

def init_db(app):
    db.init_app(app)


class User(db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    u_name = db.Column(db.String(20),unique=True)
    u_id = db.Column(db.Integer,unique=True)

# Create a User model, create a user database table 

 

# views.py

from flask import Blueprint
from App.models import User, db

blue = Blueprint('base1',__name__)


@blue.route('/create_all/')
def create_all():

    db.create_all()

    return "DB create success"

 

 

It is prone to a problem 

sqlalchemy.exc.InternalError: (InternalError) (1049, "Unknown database 'dome'") None None

 

Had learned mysql will know, but encountered a bad foundation.

The reason is that

create_all () 
function simply create a table, do not create data





There is also a pit updated 
when you happily completing the above operation, open (my way) to create the table again the question arises hairstyle
ModuleNotFoundError
ModuleNotFoundError: No module named 'MySQLdb'

Look at mysqldb obviously a problem, but we did not pack called mysqldb ah only mysql

Finally found the problem may be pymysql online

In models.py file or the configuration file is also OK

import pymysql
pymysql.install_as_MySQLdb()

ok

Guess you like

Origin www.cnblogs.com/zengxm/p/11129864.html