如何在Flask上将模型迁移到Mysql数据库

时间:2015-12-15 11:42:27

标签: mysql flask flask-sqlalchemy

我是新手,请告诉我如何将查询从模型迁移到我在配置文件中提到的数据库。

我的树结构是,

search
|-- application
|   |-- config
|   |   |-- config.py
|   |   |-- __init__.py
|   |-- controllers
|   |   |-- __init__.py
|   |   |-- routes.py
|   |-- __init__.py
|   |-- models
|   |   |-- __init__.py
|   |   |-- model.py
|   |   |-- robot.py
|   |-- static
|   |   |-- css
|   |   |   |-- bootstrap.css
|   |   |   |-- bootstrap.min.css
|   |   |-- img
|   |   |   |-- aqua_dayDown.gif
|   |   `-- js
|   |       |-- CalendarControl.js
|   |       |-- chosen.jquery.min.js
|   `-- templates
|       |-- home.html
|       |-- index.html
|-- manage.py
`-- server.py

我的config.py包含

dbhost = 'localhost'
dbuser = 'root'
dbpass = 'password'
dbname = 'flask_test'

DB_URI = 'mysql://' + dbuser + ':' + dbpass + '@' + dbhost + '/' +dbname

在routes.py文件中包含插入查询,如

    Users.query.filter_by(id = 1).update({"name":new_name})
    db.session.commit()

在我的model.py文件中包含。

from application import app
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import Table, Column, func, Integer, String, Date, Float, Text
from application.config import config 

# DB class
app.config['SQLALCHEMY_DATABASE_URI'] =  config.DB_URI
db = SQLAlchemy(app)

# DB classess
class Users(db.Model):
    __tablename__ = 'users'

    id = db.Column('id', Integer, primary_key=True)
    userid = db.Column('userid', String(100))
    name = db.Column('name', String(30))
    email = db.Column('email', String(30), unique=True)
    password = db.Column('password', String(100))
    user_type = db.Column('user_type', String(30))
    created = db.Column('created', String(100))

    def __init__(self, userid=None, name=None, email=None, password=None, user_type=None, created=None):
        self.userid = userid
        self.name = name
        self.email = email
        self.password = password
        self.user_type = user_type
        self.created = created

    def __repr__(self):
        return Users(self.userid,self.name,self.email,self.password,self.user_type,self.created)

我已经从此链接https://flask-migrate.readthedocs.org/en/latest/安装了Flask migrate,我尝试了manage.py文件仅包含该代码。

请告诉我们如何进行迁移

先谢谢。

1 个答案:

答案 0 :(得分:0)

您必须将db命令注册到manage.py

from flask.ext.migrate import MigrateCommand

manager.add_command('db', MigrateCommand)

managerFlask-Script经理,您可能已经在manage.py