【发布时间】:2021-10-30 11:24:30
【问题描述】:
我正在尝试通过 python 3.8 创建两个 SQLite 数据库来存储用户信息。我有两个脚本定义数据库和一个用测试数据填充它。第一个数据库工作正常。它由脚本 create_logindb.py 定义:
from sqlalchemy import *
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
import bcrypt
engine = create_engine('sqlite:///upa.db', echo=True)
Base = declarative_base()
def create_hashed_password(plain_text_password):
# Hash a password for the first time
# (Using bcrypt, the salt is saved into the hash itself)
return bcrypt.hashpw(plain_text_password.encode('utf-8'), bcrypt.gensalt()).decode('utf8')
def check_hashed_password(plain_text_password, hashed_password):
# Check hashed password. Using bcrypt, the salt is saved into the hash itself
return bcrypt.checkpw(plain_text_password.encode('utf-8'), hashed_password.encode('utf-8'))
########################################################################
class User(Base):
""""""
def __init__(self, username, password, app_location):
self.username = username
self.password = password
self.app_location = app_location
__tablename__ = "users"
id = Column(Integer, primary_key=True)
username = Column(String)
password = Column(String)
app_location = Column(String)
#----------------------------------------------------------------------
Base.metadata.create_all(engine)
我有一个用 create_redirectauthdb 定义的类似数据库:
engine = create_engine('sqlite:////Users/rpfhome/Documents/POS II/log in/ra.db', echo=True)
Base = declarative_base()
########################################################################
class Redirected_User(Base):
""""""
def __init__(self, username, hash_time, hash_value,user_ip,user_store):
self.username = username
self.hash_time = hash_time
self.hash_value = hash_value
self.user_ip = user_ip#ip of user
self.user_store = user_store#location of user data
__tablename__ = "users"
id = Column(Integer, primary_key=True)
username = Column(String)
hash_time = Column(String)
hash_value = Column(String)
user_ip = Column(String)
user_store = Column(String)
#----------------------------------------------------------------------
# create tables
Base.metadata.create_all(engine)
我正在创建测试帐户:
import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from create_logindb import *
from create_redirectauthdb import *
import bcrypt
import random
engine = create_engine('sqlite:///upa.db', echo=True)
# def create_hashed_password(plain_text_password):
# # Hash a password for the first time
# # (Using bcrypt, the salt is saved into the hash itself)
# return bcrypt.hashpw(plain_text_password.encode('utf-8'), bcrypt.gensalt())
# create a Session
Session = sessionmaker(bind=engine)
session = Session()
user = User("admin", create_hashed_password("password"), 'localhost:8000')
session.add(user)
user = User("python", create_hashed_password("python"), 'localhost:8001')
session.add(user)
user = User("jumpiness", create_hashed_password("python"),'localhost:8002')
session.add(user)
# commit the record the database
session.commit()
engine2 = create_engine('sqlite:////Users/rpfhome/Documents/POS II/log in/ra.db', echo=True)
Session2 = sessionmaker(bind=engine2)
session2 = Session()
user = Redirected_User("admin", 'uninitialized_datetime', str('%032x' % random.getrandbits(128)), '0.0.0.0','$Home/Documents/POS II/log in/')
session2.add(user)
user = Redirected_User("python", 'uninitialized_datetime', str('%032x' % random.getrandbits(128)), '0.0.0.0','$Home/Documents/POS II/log in/')
session2.add(user)
user = Redirected_User("jumpiness", 'uninitialized_datetime', str('%032x' % random.getrandbits(128)), '0.0.0.0','$Home/Documents/POS II/log in/')
session2.add(user)
# commit the record the database
session2.commit()
这只是我开始使用的一个玩具示例。第一个数据库 upa.db 已创建并很好地填充。尝试创建第二个数据库会产生错误:
...
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) table users has no column named hash_time
[SQL: INSERT INTO users (username, hash_time, hash_value, user_ip, user_store) VALUES (?, ?, ?, ?, ?)]
[parameters: ('admin', 'uninitialized_datetime', '287cac9fcc2ab4760d8318190f182630', '0.0.0.0', '$Home/Documents/POS II/log in/')]
(Background on this error at: http://sqlalche.me/e/13/e3q8)
在这种情况下,错误的背景页面似乎没有多大帮助。我想知道为什么当数据库定义包含该列时,它说没有名为 hash_time 的列。我认为这可能与两个数据库都包含一个名为“users”的表有关,因此我在定义数据库的脚本中重命名了表“users2”,但随后出现错误,即在运行时没有名为 users2 的表用示例数据填充它的脚本。这对我来说也没有多大意义。我还尝试在第二个脚本中将 Base 的所有实例更改为 Base2 ,但这似乎没有效果。为什么脚本中用于填充示例数据的数据库似乎与创建它的脚本中定义的数据库结构不匹配?
【问题讨论】:
-
您是否直接连接到第二个数据库以检查创建的结构是否正确? (缩小问题范围 - 如果根本原因在创建过程中)
-
我已经测试了 ra 数据库的创建和插入。这对我来说可以。也许一开始 DB 的状态就搞砸了。
-
谢谢。在添加用户之前,我尝试将
q=engine2.execute('pragma table_info(users)').fetchall() for i in q: print(q) print('\n')添加到填充表格的脚本中并得到结果:[(0, 'id', 'INTEGER', 1, None, 1), (1, 'username', 'VARCHAR', 0, None, 0), (2, 'hash_time', 'VARCHAR', 0, None, 0), (3, 'hash_value', 'VARCHAR', 0, None, 0), (4, 'user_ip', 'VARCHAR', 0, None, 0), (5, 'user_store', 'VARCHAR', 0, None, 0)]。这似乎是正确的,但也许我没有正确理解它 -
我也直接用 SQLite3 连接到数据库并执行查询:
schema users CREATE TABLE users ( id INTEGER NOT NULL, username VARCHAR, hash_time VARCHAR, hash_value VARCHAR, user_ip VARCHAR, user_store VARCHAR, PRIMARY KEY (id) ); -
session2是从Session()而不是Session2()创建的(第 34 行)!
标签: python sql python-3.x sqlite sqlalchemy