简体   繁体   English

SQLALchemy, Flask, Python, code adds model object only once to database (PostgreSQL)

[英]SQLALchemy, Flask, Python, code adds model object only once to database (PostgreSQL)

My database looks like this:我的数据库如下所示:

CREATE TYPE APP_ROLE AS ENUM ('admin', 'user');

CREATE TABLE IF NOT EXISTS users (
  user_id SERIAL PRIMARY KEY,
  login VARCHAR ( 50 ) UNIQUE NOT NULL,
  password_hash TEXT NOT NULL,
  role APP_ROLE NOT NULL
);

I wrote a simple Flask/SQLAlchemy/Python code to test inserting to db.我写了一个简单的 Flask/SQLAlchemy/Python 代码来测试插入到 db。 However, it seems that my object is added only once, because no matter how many time I run the script ( python3 testdb.py ) it shows that there's only one user in db.但是,似乎我的 object 只添加了一次,因为无论我运行脚本( python3 testdb.py )多少次,它都表明数据库中只有一个用户。 What Im doing wrong?我做错了什么?

#!/usr/bin/env python3
import os
from flask import Flask, render_template, request, url_for, redirect
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import inspect
from sqlalchemy import create_engine
from sqlalchemy import Enum
from werkzeug.security import generate_password_hash

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

class Config(object):
    DEBUG = False
    TESTING = False
    CSRF_ENABLED = True
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_DATABASE_URI = "postgresql://brian:1234@127.0.0.1:5432/example_db"


app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)

class Users(db.Model):

    __tablename__ = 'users'

    user_id = db.Column(db.Integer, primary_key=True)
    login = db.Column(db.String(50), unique=True)
    password_hash = db.Column(db.String(128))
    role = db.Column(Enum("admin", "user", name="app_role", create_type=False))

    def __init__(self, login, password_hash, role):
        self.login = login
        self.password_hash = password_hash
        self.role = role

    @property
    def password(self):
        raise AttributeError('Password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def to_json(self):
        pass

    def is_administrator(self):
        pass

if __name__ == '__main__':

    u1 = Users('brian', '2345643245', 'admin')
    db.create_all()
    db.session.add(u1)
    db.session.add(u1)
    db.session.add(u1)
    db.session.flush()
    
    users1 = Users.query.all()
    for user in users1:
        print(user.login, user.password_hash, user.role)

You are entering 3 times a record that has the exact same value for a field defined as UNIQUE .您正在输入 3 次记录,该记录对于定义为UNIQUE的字段具有完全相同的值。 This is not allowed to do it at the database level, try to enter 3 different users with 3 different values for the login field.这在数据库级别是不允许的,尝试为login字段输入 3 个不同的用户和 3 个不同的值。

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

相关问题 Python Flask仅运行一次代码 - Python Flask Only Run Code Once Python Flask SqlAlchemy 在循环中动态添加数据库 ZA559B87068921EEC05086CE5485E97 名称 - Python Flask SqlAlchemy Add Database Model Name dynamically in For Loop 泄漏的数据库连接:PostgreSQL、SQLAlchemy、Flask - Leaking database connections: PostgreSQL, SQLAlchemy, Flask 如何使用 SQLAlchemy 在 Flask 应用程序中初始化 Postgresql 数据库 - How to initialize a Postgresql database in a Flask app with SQLAlchemy 使用 SQLalchemy 写入 Python 中的 PostgreSQL 数据库 - Writing to PostgreSQL database in Python with SQLalchemy 在Python SQLAlchemy中使用数据库模型对象,而不会干扰数据库事务 - Use a database model object in Python SQLAlchemy without interfering with database transactions Python SQLAlchemy - 如何使用 object 中的 object 通过方法 aD98C53 更新数据库 - Python SQLAlchemy - How to update database using object within model by a method? Python Flask SQLAlchemy-将模型加载到视图中 - Python Flask SQLAlchemy - loading a model into the view Python Flask SQLAlchemy 不提交对数据库的更改 - Python Flask SQLAlchemy not commiting changes to the database SQLAlchemy对象已经连接到会话,然后刷新时出现DetachedInstanceError,仍然添加到数据库中 - SQLAlchemy Object is already attached to session, then DetachedInstanceError on refresh, still adds to database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM