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

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.

Related

does anyone know how history mapper works in python?

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

Django models datetime with timezone UTC+1 saved as UTC+0

In my django project i have a model where i store data (in my read_date field) with a DateTime field for storing date (with timezone):
class Results(models.Model):
id = models.AutoField(primary_key=True)
device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL)
proj_code = models.CharField(max_length=400)
res_key = models.SlugField(max_length=80, verbose_name="Message unique key", unique=True)
read_date = models.DateTimeField(verbose_name="Datetime of vals readings")
unit = models.ForeignKey(ModbusDevice, null=True, on_delete=models.SET_NULL)
i setted in settings.py file using timezone:
TIME_ZONE = 'UTC+1'
USE_TZ = True
So, the problem is, when i pass a corrected formatted ditetime with UTC+1 timezone as:
2021-11-12 10:39:59.495396+01:00
in my db i get:
2021-11-12 9:39:59.495396+00
Why my stored value is UTC+0 instead using timezone passed?
So many thanks in advance
All the date-times are stored in the UTC.
It's not a bug it's a feature. The database needs one format to process the DateTime data when sorting, selecting, filtering, etc. So when you are making some SQL requests you can pass a needed timezone for auto converting. For example, your first user in the UTC+1 and you can make requests using this parameter, your another user UTC-9, and the results could be different.

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.

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