does anyone know how history mapper works in python? - python-3.x

does anyone know how history mapper works in python?
Why are NOT all fields of the main table written to the history table?
example:
class TableNameOrm(DbNameMetaBase, MixinLocked, MixinCreatedAt, Versioned):
__tablename__ = 'table_name'
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(80), nullable=False)
image_type_code = Column(String(100), nullable=True)
TableNameHistoryOrm = TableNameOrm.__history_mapper__.class\_
when you update table TableNameOrm, all fields except image_type_code are written to history table TableNameHistoryOrm, it writes null.
What should I do so that image_type_code is also updated in the history?

In short, the project had routers to another project, which updated the history table by events

Related

colors = Color.query.all()

Hi I am trying to follow this tutorial to learn how to get pagination in my flask project.
https://betterprogramming.pub/simple-flask-pagination-example-4190b12c2e2e
I am having problems with the following line
"colors = Color.query.all()"
Where does "Color" come from ?
In all the tutorials I have read this form of variable appears but no explanation where it comes from
The Color class is a database model that was implemented with flask-SQLAlchemy. The class can be used to add, remove and query entries in a database table.
The definition of the model is as follows and contains three columns. The ID as a unique key for identification, the name of the color and a date when the database entry was added.
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
# ...
db = SQLAlchemy(app)
class Color(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False, unique=True, index=True)
created_at = db.Column(db.DateTime(timezone=True),
nullable=False, unique=False, index=False,
default=datetime.utcnow)
# ...
To use the database you have to create the necessary tables either via the flask shell or within your code like here.
with app.app_context():
db.create_all()
The flask-SQLAlchemy introductory example and the SQLAlchemy documentation explain more.
I also recommend this series of articles as a good tutorial for flask.
Have fun.

Many to Many relationship Flask sqlalchemy and marshmallow

Suppose i have 2 tables , Table 1 consist of users info and Table 2 consist of Branch info.
table 1 and table 2 is related to each other by many to many relationship.
e.g 1 user can work in multiple branches and 1 branch can have multiple users.
so here there's no parent child concept. i was wondering if i have to create another table with schema and relate it to user and branch table using foreign key or shall i create an association table.
I have done this :
class UserBranchMap(db.Model):
id = db.Column(db.Integer, primary_key=True)
branch_id = db.Column(db.Integer,db.ForeignKey('branch.id'))
branch = db.relationship("Branch", backref=db.backref("UBMbranch", lazy="dynamic"))
user_id = db.Column(db.Integer,db.ForeignKey('user.id'))
user = db.relationship("User", backref=db.backref("UBMuser", lazy="dynamic"))
created_at = db.Column(db.VARCHAR(20), nullable = False)
created_by = db.Column(db.VARCHAR(20), nullable = False)
class UserBranchMapSchema(ma.Schema):
branch = fields.Nested(branch_schema)
user = fields.Nested(user_schema)
class Meta:
fields = ('branch_id','user_id','created_at','created_by')
userbranchmap_schema = UserBranchMapSchema()
userbranchmaps_schema = UserBranchMapSchema(many = True)
what's the difference between association table and this mapping table ?
If I understand you correctly, you're asking about the difference between an association table
UserBranches = db.Table(
'user_branches',
db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True),
db.Column('branch_id', db.Integer, db.ForeignKey('branch.id'), primary_key=True)
)
and a mapping table
class UserBranch(db.Model):
id = db.Column(db.Integer, primary_key=True)
user = db.relationship("User", backref=db.backref("UBMuser", lazy="dynamic"))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
branch = db.relationship("Branch", backref=db.backref("UBMbranch", lazy="dynamic"))
branch_id = db.Column(db.Integer, db.ForeignKey('branch.id'))
On a database level, there is no real difference between them. If you only want to have a strict Many To Many relationship between two tables, just use an association table. Because of SQLAlchemy, you never have to do anything with it, because joining through this table happens automatically, as soon as you join Users to Branches or the reverse.
If, however, you want to do more, like have it actually denote a relationship, then the mapping table like you wrote it the way to go, because it behaves exactly like a normal table. This means you can use it like UserBranch.created_at or even query it directly if you want.

How do I use flask-sqlalchemy to pass a date and time into a Postgres table

I am using flask-sqlalchemy and flask-wtforms to ask a user to pick a date and time. I then want to pass this date and time as UTC into my PostgreSQL database using flask-sqlalchemy.
My main problem is that I cannot find the documentation that helps me understand the process of the fields I need in my events table and the format I need to pass from my wtform. I have used a .datetimepicker in my HTML and my form.py line looks like this.
eventstart = DateTime('Event Start', validators=[DataRequired()])
I have followed a few examples but if anyone can point me in the right direction, I would be very grateful.
__tablename__ = 'events'
id = db.Column(db.Integer, primary_key=True)
eventname = db.Column(db.String(64), unique=True, index=True)
eventstart = db.Column(db.DateTime, nullable=False)
eventstop = db.Column(db.DateTime, nullable=False)
timeblock = db.Column(db.Integer)
The fields for DateTime are correctly defined in your DB table 'events'.
The format for storing the datetime should be like 2022-03-21 19:04:14.
You can get eventstart into this format or can also use pandas.to_datetime to reformat it which can be stored into the table.

Change SQLAlchemy __tablename__

I am using SQLAlchemy to handle requests from an API endpoint; my database tables (I have hundreds) are differentiated via a unique string (e.g. test_table_123)...
In the code below, __tablename__ is static. If possible, I would like that to change based on the specific table I would like to retrieve, as it would be tedious to write several hundred unique classes.
from config import db, ma # SQLAlchemy is init'd and tied to Flask in this config module
class specific_table(db.Model):
__tablename__ = 'test_table_123'
var1 = db.Column(db.Integer, primary_key=True)
var2 = db.Column(db.String, index=True)
var3 = db.Column(db.String)
class whole_table_schema(ma.ModelSchema):
class Meta:
model = specific_table
sqla_session = db.session
def single_table(table_name):
# collect the data from the unique table
my_data = specific_table().query.order_by(specific_table.level_0).all()
Thank you very much for your time in advance.
You can use reflect feature of SQLAlchemy.
engine = db.engine
metadata = MetaData()
metadata.reflect(bind=engine)
and finally
db.session.query(metadata.tables[table_name])
If you want smoother experience with querying, as previous solution cannot offer one, you might declare and map your tables: tables = {table_name: create_table(table_name) for table_name in table_names}, where create_table constructs models with different __tablename__. Instead of creating all tables at once, you can create them on demand.

How to query just one or two column from a Table in flask-sqlalchemy?

I have a table say CATEGORY, and one of its column is CATEGORY_NAME.
I want to query all the category_names from the table.
In SQL I would do-
SELECT CATEGORY_NAME FROM CATEGORY;
How can I do this in flask-sqlalchemy?
My model is:
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
category_name = db.Column(db.String(64), index=True, unique=True)
I read we can do this with with_entities, but it didn't work.
It worked this way with with_entities:
cat_names = Category.query.with_entities(Category.category_name).all()

Resources