sqlite数据库中的Flask迁移集成

2024-06-09 18:33:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将迁移集成到我的Flask应用程序中的SQLite数据库中。我用过

set FLASK_APP = Basic.py

在项目目录的Pycharm终端中运行

^{pr2}$

但它不起作用。以下是我的代码:

Basic.py

__author__ = 'User'
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate,MigrateCommand


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

#__file__ -->Main.py

print(basedir)

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir,'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False

db = SQLAlchemy(app)

Migrate(app,db)

####################################################

class Puppy(db.Model):

    #manual table name choice
    __tablename__ = 'puppies'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text)
    age = db.Column(db.Integer)
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __repr__(self):
        return "Puppy {} is {} year/s old".format(self.name, self.age)

在设置数据库.py在

__author__ = 'Mitu'
from Basic import  db,Puppy

#CREATE ALL THE TABLES Model
db.create_all()


sam = Puppy('Sammy',3)
frank = Puppy('Frankie',4)


#none
#none
print(sam.id)
print(frank.id)

db.session.add_all([sam,frank])

db.session.commit()

print(sam.id)
print(frank.id)

在积垢在

__author__ = 'Mitu'
from Basic import  db,Puppy

### Create ###

my_puppy = Puppy('Rufus',5)
db.session.add(my_puppy)

db.session.commit()

#### Read ####

all_puppies = Puppy.query.all() #list of all puppies object

print(all_puppies)

# select by id

puppy_one = Puppy.query.get(1)
print(puppy_one)

# filters
# produce some sl code!
puppy_frankie = Puppy.query.filter_by(name='Frankie')
print(puppy_frankie.all())

#["Frankie is 3 years old"]


#### update

first_puppy = Puppy.query.get(1)
first_puppy.age = 10
db.session.add(first_puppy)
db.session.commit()


#### delete

second_pup = Puppy.query.get(2)
db.session.delete(second_pup)
db.session.commit()

# now all puppies

all_puppies = Puppy.query.all()
print(all_puppies)

最后两个文件用于设置数据库和sqlite数据库的CRUD操作。在

我的主要问题是迁移没有集成。在


Tags: namefromimportselfidappdbage
1条回答
网友
1楼 · 发布于 2024-06-09 18:33:09

我已经在使用python3.5创建的虚拟环境中安装了所需的包。在

virtualenv -p python3 venv  no-site-packages
source venv/bin/activate
pip install flask
pip install Flask-SQLAlchemy
pip install Flask-Migrate
pip freeze>requirements.txt

requirements.txt

^{pr2}$

由于flask-migrate在运行flask db init时搜索app.py,我将Basic.py重命名为app.py。在

我运行了附加的setupdatabase.py来创建SQLite数据库,运行了crud.py来创建虚拟记录。在

我创建了一个测试这些SQLite数据是否被传递到Flask模板的路径。在

更新app.py

__author__ = 'User'


import os
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, MigrateCommand


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

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir,'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False

db = SQLAlchemy(app)
migrate = Migrate(app, db)

class Puppy(db.Model):
    __tablename__ = 'puppies'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text)
    age = db.Column(db.Integer)
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __repr__(self):
        return "Puppy {} is {} year/s old".format(self.name, self.age)

@app.route('/')
def home():
    data = Puppy.query.all()
    return render_template("home.html", data = data)

if __name__ == '__main__':
    app.run(debug=True)

home.html

<html>
  <head>
    <title>Home</title>
  </head>
  <body>
    <h3>Puppies</h3>
    <div>{{ data }}</div>
  </body>
</html>

数据传递到模板:

SQLite data passed to template

然后我按照official documentation of flask-migrate中的指示运行initmigrate和{}命令。在

(venv) ➜ flask db init
/home/.../flask_data_migration/venv/lib/python3.5/site-packages/flask_sqlalchemy/__init__.py:794: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
  Creating directory
  /home/.../flask_data_migration/migrations ... done
  Creating directory
  /home/.../flask_data_migration/migrations/versions
  ... done
  Generating
  /home/.../flask_data_migration/migrations/env.py ... done
  Generating
  /home/.../flask_data_migration/migrations/README ... done
  Generating /home/.../flask_data_migration/migrations
  /script.py.mako ... done
  Generating /home/.../flask_data_migration/migrations
  /alembic.ini ... done
  Please edit configuration/connection/logging settings in '/home/.../flask_data_migration/migrations/alembic.ini' before proceeding.

(venv) ➜ flask db migrate
/home/.../flask_data_migration/venv/lib/python3.5/site-packages/flask_sqlalchemy/__init__.py:794: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.env] No changes in schema detected.

(venv) ➜ flask db upgrade
/home/.../flask_data_migration/venv/lib/python3.5/site-packages/flask_sqlalchemy/__init__.py:794: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.

运行迁移后的目录结构(跳过venv文件夹):

.
├── app.py
├── crud.py
├── data.sqlite
├── migrations
│   ├── alembic.ini
│   ├── env.py
│   ├── __pycache__
│   │   └── env.cpython-35.pyc
│   ├── README
│   ├── script.py.mako
│   └── versions
├── requirements.txt
├── setupdatabase.py
└── templates
    └── home.html

相关问题 更多 >