为什么我的数据库没有在工作目录中创建.db文件?我正在使用Pycharm

时间:2019-02-01 13:20:59

标签: python-3.x sqlite flask-sqlalchemy

我正在使用Pycharm Professional。我有一个名为basic.py的文件,其中包含我的模型和用于在数据库中创建模型的代码。代码运行良好,没有遇到任何错误,但是运行代码后,它没有在我的工作目录中创建.db文件。即使使用了db.create_all(),我也找不到。我在这里想念什么?谢谢

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os

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

app = Flask(__name__)

app.config["SQLAlCHEMY_DATABASE_URI"] = 'sqlite:////site.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class Puppy(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text)

    to_owner = db.relationship("Owner", backref="puppy", uselist=False)
    to_toy = db.relationship("Toy", backref= "puppy", lazy = "dynamic")

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return f"This is {self.name}"



class Owner(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text)
    pupid = db.Column(db.Integer, db.ForeignKey("puppy.id"))

    def __init__(self, name, pup):
        self.name = name
        self.owner = pup


class Toy(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text)
    pupid = db.Column(db.Integer, db.ForeignKey("puppy.id"))

    def __init__(self, name, pup):
        self.name = name
        self.owner = pup

db.create_all()

john = Puppy("john")
jack = Puppy("jack")

print(john.name)
db.session.add_all([john, jack])
db.session.commit()
print(john.name)

print(Puppy.query.all())

john = Puppy.query.filter_by(name="john").first()
print(john)

owner1 = Owner("amr", john.id)


toy1 = Toy("ball", john.id)
toy2 = Toy("frisby", john.id)

db.session.add_all([owner1, toy1, toy2])
db.session.commit()

john = Puppy.query.filter_by(name="john").first()
print(john.name)

1 个答案:

答案 0 :(得分:0)

我认为您的SQLAlchemy URI的SQLite目录规范中的/过多。您可以将数据库URI更改为以下内容,看看是否可以解决您的问题:

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'