vendredi 7 août 2015

Migrate Flask models.py to MySQL

I'm new. Bear with me.

I'm developing a Flask application using SQLAlchemy as an ORM and up until today I have been using SQLite for convenience. I'm now putting the application live on Digital Ocean and want to use MySQL instead of SQLite.

I have MySQL installed on my ubuntu VPS on Digital Ocean and it seems like it is configured properly. However, obviously I have to create the database tables, so I can save the data inside.

Question: Is there a way for me to migrate my models.py, so the database tables are created from what I have written in models.py or do I have to create all the database tables myself manually in MySQL?

You can see the application live here: http://ift.tt/1IwusWa and I have made a small test to see if there is a database connection here: http://ift.tt/1W6rCk2

Models.py (Only user model):

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy 
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from datetime import datetime, date
from hashlib import md5
from bcrypt import hashpw, gensalt

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:password@localhost/database'
db = SQLAlchemy(app)

migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    slug = db.Column(db.String(80))
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(80))
    password = db.Column(db.String(80), unique=False)
    admin = db.Column(db.Boolean(), default=False)
    join_date = db.Column(db.DateTime)
    last_seen = db.Column(db.DateTime)
    topics = db.relationship('Topic')
    posts = db.relationship('Post')
    picture = db.Column(db.Boolean(), default=False)
    title = db.Column(db.String(80))
    company = db.Column(db.String(80))
    summary = db.Column(db.String(80))

def __init__(
    self, 
    slug,
    username, 
    password, 
    email, 
    join_date, 
    last_seen, 
    picture, 
    title,
    company, 
    summary, 
    admin=False
):
    self.slug = slug
    self.username = username
    self.password = password
    self.email = email
    self.join_date = join_date
    self.last_seen = last_seen
    self.admin = admin
    self.picture = picture
    self.title = title
    self.company = company
    self.summary = summary

def avatar(self, size):
    return 'http://ift.tt/1CViUYR' % (md5(self.email.encode('utf-8')).hexdigest(), size)

def __repr__(self):
    return "<User(slug='%s', username='%s', password='%s', email='%s', admin='%s', join='%s', picture='%s', title='%s', company='%s', summary='%s')>" % (
        self.slug,
        self.username, 
        self.password, 
        self.email, 
        self.admin, 
        self.join_date, 
        self.picture,
        self.title,
        self.company,
        self.summary
    )

Views.py (Only database test):

@app.route('/testdb')
    def testdb():
    if db.session.query("1").from_statement("SELECT 1").all():
        return 'It works.'
    else:
        return 'Something is broken.'

UPDATE after Lukas comment:

When trying to db.create_all() I get this traceback:

sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (1005, "Can't create table 'pwforum.topic' (errno: 150)") [SQL: u'\nCREATE TABLE topic (\n\tid INTEGER NOT NULL AUTO_INCREMENT, \n\tslug VARCHAR(255), \n\ttitle VARCHAR(80), \n\tdescription TEXT, \n\tpub_date DATETIME, \n\tlast_update DATETIME, \n\tuser_id VARCHAR(80), \n\tcategory_id INTEGER, \n\tviews INTEGER, \n\tlocked BOOL, \n\tpinned BOOL, \n\tPRIMARY KEY (id), \n\tUNIQUE (slug), \n\tFOREIGN KEY(user_id) REFERENCES user (id), \n\tFOREIGN KEY(category_id) REFERENCES category (id), \n\tCHECK (locked IN (0, 1)), \n\tCHECK (pinned IN (0, 1))\n)\n\n']

Aucun commentaire:

Enregistrer un commentaire