Issue
I would like to get the row with is id
, and update it's value with other values, but i can't launch filter query anyone can help me?
I have periodic class element and the element is stored on a sqlite3 database
I'm creating an rest api, which you can modify, add and delete an periodic element in flask
and sqlalchemy
from asyncio.windows_events import NULL
from enum import auto
from itertools import cycle
import json
from random import weibullvariate
from sqlite3 import dbapi2
from traceback import print_tb
from tracemalloc import start
from unicodedata import name
from flask import *
from flask_sqlalchemy import SQLAlchemy
from matplotlib.font_manager import json_dump
from sqlalchemy import Float, Identity, create_engine, ForeignKey, false, null, select
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.sql import select
engine = create_engine(
'sqlite:///dati.db', connect_args={"check_same_thread": False}, echo=True,)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class Periodic_element(Base):
__tablename__ = "dati"
id = Column(Integer, Identity(start=1, cycle=True),
primary_key=True, nullable=True)
name = Column(String)
weight = Column(Float)
symbol = Column(String)
def __init__(self, id, name, weight, symbol):
self.id = None
self.name = name
self.weight = weight
self.symbol = symbol
def __repr__(self):
return '<User %r>' % (self.name)
def toJson(self):
json = {
"id": self.id,
"name": self.name,
"weight": self.weight,
"symbol": self.symbol
}
return json
def add_record(id, name, symbol, weight):
record = Periodic_element(id=None, name=name, symbol=symbol, weight=weight)
session.add(record)
session.commit()
def serve_record():
x = session.query(Periodic_element).all()
final_json = "["
# session.commit()
for element in x:
final_json = final_json + json.dumps(element.toJson()) + ","
final_json = final_json[:-1] + "]"
print("Json is served")
return final_json
def change_record():
x = session.query(Periodic_element).filter(
Periodic_element.name == "prova")
change_record()
Base.metadata.create_all(bind=engine)
This code return me this error:
File "c:\Users\user\Desktop\Esercizi Lavoro\back-end\database.py", line 27, in <module>
Base.query = session.query_property()
AttributeError: 'Session' object has no attribute 'query_property'
PS C:\Users\user\Desktop\Esercizi Lavoro\back-end> & "C:/Users/user/AppData/Local/Programs/Python/Python310/python.exe" "c:/Users/user/Desktop/Esercizi Lavoro/back-end/database.py"
2022-09-30 08:58:13,638 INFO sqlalchemy.engine.Engine SELECT dati.id AS dati_PS C:\Users\user\Desktop\Esercizi Lavoro\back-end> & "C:/Users/user/AppData/Local/Programs/Python/Python310/python.exe" "c:/Users/user/Desktop/Esercizi Lavoro/back-end/database.py"
2022-09-30 09:02:50,688 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2022-09-30 09:02:50,691 INFO sqlalchemy.engine.Engine SELECT dati.id AS dati_id, dati.name AS dati_name, dati.weight AS dati_weight, dati.symbol AS dati_symbol
FROM dati
WHERE dati.name = ?
2022-09-30 09:02:50,691 INFO sqlalchemy.engine.Engine [generated in 0.00025s] ('prova',)
1
2022-09-30 09:02:50,693 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2022-09-30 09:02:50,693 INFO sqlalchemy.engine.Engine PRAGMA main.table_info("dati")
2022-09-30 09:02:50,693 INFO sqlalchemy.engine.Engine [raw sql] ()
2022-09-30 09:02:50,695 INFO sqlalchemy.engine.Engine COMMIT
Solution
The code you have outputted works totally fine. The execution context might be wrong. I made executable python script that you can just run on localhost to see the outcomes by just python3 <whateveryounamedit>.py
import json
from sqlalchemy import Float, Identity, create_engine
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine(
'sqlite:///dati.db', connect_args={"check_same_thread": False}, echo=True,)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class Periodic_element(Base):
__tablename__ = "dati"
id = Column(Integer, Identity(start=1, cycle=True),
primary_key=True, nullable=True)
name = Column(String)
weight = Column(Float)
symbol = Column(String)
def __init__(self, id, name, weight, symbol):
self.id = None
self.name = name
self.weight = weight
self.symbol = symbol
def __repr__(self):
return '<User %r>' % (self.name)
def toJson(self):
response = {}
for column in self.__table__.columns.keys():
response[column] = getattr(self, column)
return response
def add_record(id, name, symbol, weight):
record = Periodic_element(id=None, name=name, symbol=symbol, weight=weight)
session.add(record)
session.commit()
def serve_record():
records = session.query(Periodic_element).all()
return json.dumps([record.toJson() for record in records])
Base.metadata.create_all(bind=engine)
if __name__ == "__main__":
add_record(1, 'foo', 'bar', 12)
print(serve_record())
Answered By - matleh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.