Question

I have SQLAlchemy classes defined like this.

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

connections_table = db.Table('connections', db.metadata,
    db.Column('book_id', db.Integer, db.ForeignKey('book.id')),
    db.Column('author_id', db.Integer, db.ForeignKey('author.id')))

class Author(db.Model):
    __tablename__ = 'authors'
    __searchable__ = ['a_name']
    __table_args__ = {'sqlite_autoincrement': True,}

    id = db.Column(db.Integer, primary_key=True)
    a_name = db.Column(db.String(80), unique=True)

    def __repr__(self):
        return unicode(self.name)


class Book(db.Model):
    __tablename__ = 'books'
    __searchable__ = ['b_name']
    __table_args__ = {'sqlite_autoincrement': True,}

    id = db.Column(db.Integer, primary_key=True)
    b_name = db.Column(db.String(80))
    authors = db.relationship('Author', secondary=lambda: connections_table,
                              backref=db.backref('books'))

    def __repr__(self):
        return unicode(self.b_name)

How can I save sqlite database on a harddrive and use it in future? What commands would be helpful?

Était-ce utile?

La solution

create config.py along with your app.py(you main file in which you have written above code..) and its content as below

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

SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.sqlite')
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')

then in your app; add one line as:

app = Flask(__name__)
app.config.from_object('config')## add this line... .
db = SQLAlchemy(app)

now you can take app.sqlite anywhere..

further you can do: create "db_create.py" file in the same location, and make its content as:

from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
    api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))

now; run this 'db_create.py' to setup your db..
for more info click here

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top