简体   繁体   English

Flask-SQLAlchemy 不创建表

[英]Flask-SQLAlchemy doesn't create table

I am trying to use PostgreSQL with Flask-SQLAlchemy.我正在尝试将 PostgreSQL 与 Flask-SQLAlchemy 一起使用。 I made a database named data_collector using pgAdmin4.我使用 pgAdmin4 创建了一个名为data_collector的数据库。 When I try to create a table it's not getting created.当我尝试创建一个表时,它没有被创建。 I think the connection to the database is not getting established.我认为与数据库的连接尚未建立。

I am trying to run it from cmd as:我正在尝试从 cmd 运行它:

from app import db
db.create_all()
from flask import Flask, render_template,request
from flask_sqlalchemy import SQLAlchemy

app=Flask(__name__)
app.config['SQLALCHEMY DATABASE_URI'] = 'postgresql://postgres:postgresql@localhost/data_collector'

db=SQLAlchemy(app)

class Data(db.Model):
    __tablename__="data"
    id=db.Column(db.Integer,primary_key=True)
    email_=db.Column(db.String(120),unique=True)
    height_=db.Column(db.Integer)

    def __init__(self,email_,height_):
        self.email_=email_
        self.height_=height_

db.create_all()

You didn't commit to the database after creating the tables.创建表后,您没有提交到数据库。
You can do that by:您可以通过以下方式做到这一点:

with app.app_context():
    db.create_all()
    db.session.commit()

Do something like this.做这样的事情。

from flask_sqlalchemy import SQLAlchemy
from flask import Flask


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

# ---snip---

with app.app_context():
    db.create_all()
    db.session.commit()    # <- Here commit changes to database


@app.route("/")
def index():
    return "Hello, World!"

This should solve your problem.这应该可以解决您的问题。

If you want to reset(delete) your database then:如果你想重置(删除)你的数据库,那么:

with app.app_context():
    db.drop_all()
    db.session.commit()

Nothing is written or deleted or updated in database unless you commit using除非您提交使用,否则不会在数据库中写入、删除或更新任何内容
db.session.commit()

If you want to revert the changes before comitting use: db.session.rollback()如果您想在提交之前还原更改,请使用: db.session.rollback()

Finally got the solution after alot of Googling.经过大量的谷歌搜索后终于得到了解决方案。

You must import all the models before calling db.create_all() function like this,在像这样调用db.create_all()函数之前,您必须导入所有models

def create_db():

from src import models

db.create_all()
db.session.commit()

I have all my models in single file but if you have different files, make sure to import them all.我将所有模型都放在一个文件中,但如果您有不同的文件,请确保将它们全部导入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM