我正在尝试在SQLite数据库中创建查询,但由于错误而无法创建会话:
name 'Session' is not defined
我在同一环境中安装了SQLAlchemy,Flask-SQLAlchemy和棉花糖。我也导入了sessionmaker库,但是我不知道错误的原因。
我阅读了the SQLAlchemy documentation关于会话的信息,但无法解决该错误。
我有以下代码:
from flask import Flask, request, jsonify
from sqlalchemy import Column, ForeignKey, Float, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine
import os
import sys
import random
Base = declarative_base()
app = Flask(__name__)
class TransAccount(Base):
__tablename__ = 'Transaccount'
number_acc = Column(String(50), primary_key = True)
number_t = Column(Integer, primary_key = True)
destiny = Column(String(50))
type_t = Column(String(50))
description_t = Column(String(100))
class BankAccount(Base):
__tablename__ = 'Bankaccount'
number_acc = Column(String(50), primary_key = True)
owner_acc = Column(String(50))
bank_name = Column(String(50))
amount_acc = Column(Float)
description_acc = Column(String(100))
transferbanks = relationship('TransferBank', secondary = TransAccount,
backref = 'BankAccount')
class TransferBank(Base):
__tablename__ = 'Transferbank'
number_t = Column(Integer, primary_key = True)
quantity_t = Column(Float)
owner_t = Column(String(50))
bankaccounts = relationship('BankAccount', secondary = TransAccount,
backref = 'TransferBank')
engine = create_engine('sqlite:///clients.db')
sm = sessionmaker()
sm.configure(bind = engine)
session = Session()
Base.metadata.create_all(engine)
def transfer():
if request.json['quantity_t'] <= 2000:
if request.json['quantity_t'] > 0 and amount >
request.json['quantity_t']:
BankAccount.number_acc = request.json['source']
Transaccount.destiny = request.json['destination']
Transferbank.quantity_t = request.json['amount']
BankAccount.amount_acc = BankAccount.amount_acc -
Transferbank.quantity_t - 2.5
Transaccount.description_t = request.json['info']
Transferbank.number_t = random.random()*1000
Transaccount.number_t = Transferbank.number_t
Transaccount.type_t = 'intra-bank'
return jsonify({'message' : 'Transfer succeed!'})
else:
return jsonify({'message' : 'Account without enough funds'})
else:
return jsonify({'message' : 'Transfer is higher than 2000€'})
def addfunds(account_id):
account = session.query(BankAccount).filter(BankAccount.number_acc ==
account_id).one()
if account:
return jsonify({'message' : 'Account already exists'})
else:
BankAccount.amount_acc = request.json['amount']
BankAccount.bank_name = request.json['src_bank']
BankAccount.description_acc = request.json['info']
session.close()
return jsonify({'message' : 'Funds transferred successfully!'})
if __name__ == '__main__':
app.run(debug = True)
如何创建会话?
谢谢
答案 0 :(得分:1)
替换
engine = create_engine('sqlite:///clients.db')
sm = sessionmaker()
sm.configure(bind = engine)
session = Session()
打开
engine = create_engine('sqlite:///clients.db')
Session = sessionmaker(bind=engine)
session = Session()