简体   繁体   English

无法使用 SQLAchemy 在数据库中创建表

[英]Cannot Create tables in a database using SQLAchemy

i have created app.py and tables.py which are the main app and a file used to define the tables of a database [database.db] respectively.我已经创建了 app.py 和 tables.py,它们分别是主要的应用程序和用于定义数据库 [database.db] 表的文件。 I cannot create tables in the database.db, what could be the problem?我无法在 database.db 中创建表,可能是什么问题? Code for both is given below两者的代码如下

#app.py #app.py

from flask import Flask, render_template, request, session, redirect
from tables import db
from flask_session import Session
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db.init_app(app)

@app.before_first_request
def create_tables():
db.create_all()
 @app.route("/")
def home():
return render_template("register.html")

#tables.py #tables.py


from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class users (db.Model):
    users_key = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(21), nullable=False)
    email = db.Column(db.String(31), nullable=False, unique=True)
    password = db.Column(db.String(61), nullable=False)

i expected to get tables in the database.db file which is located in the same directory as the app.py file.我希望在与 app.py 文件位于同一目录中的 database.db 文件中获取表。 i could not add any tables though.虽然我无法添加任何表格。

You have to create database context and initialize it.您必须创建数据库上下文并对其进行初始化。

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

Also make sure to import the Flask module from the flask package and SQLAlchemy from the flask_sqlalchemy package in tables.py.还要确保从 flask package 导入 Flask 模块,从 tables.py 中的 flask_sqlalchemy package 导入 SQLAlchemy 模块。

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)

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

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