Questions tagged [sqlalchemy]

SQLAlchemy, a robust Python SQL toolkit and Object Relational Mapper, empowers application developers with unparalleled flexibility and control over their databases.

Converting python sqlalchemy queries to SQL syntax

Currently, I'm involved in an assignment that requires the management of a collection of PostgreSQL databases related to a school district. One of my tasks is to update the new field student_gpas, which is an array designed to store unique student GPAs. To ...

Ways to retrieve the values from a collection of objects inside a Model using Python

In my system, there are two modes available: User and Friends. This represents a one-to-many relationship. My goal is to retrieve the values in the following manner: record = User.query.filter_by(id=7).first() Below are the methods and properties associ ...

SQLAlchemy - restricting the joined-loaded results

Database Structure: class Team(Base): id = Column(Integer, primary_key=True) name = Column(String, nullable=False) players = relationship("Player", backref="team") class Player(Base): id = Column(Integer, primary_key=T ...

Transforming JSON into a Python dictionary after importing Postgresql data using SQLAlchemy

I'm facing a challenging issue with converting JSON strings to Python data dictionaries for analysis in Pandas. Despite researching other solutions, I haven't found one that works for my specific case. In the past, I relied on CSVs and the read_ ...

Incorporate logical operators (along with partial expressions) as function arguments in Python

Using SQLAlchemy, you can achieve something like the following: mytable.query.filter(mytable.some_col < 5).all() I am looking to implement a similar functionality where developer users can pass logical operations to a function. Here is an example: cl ...

What is the best way to insert a list of objects from a BaseModel class into a database using SQL Alchemy and FastApi?

I am looking to dynamically insert rows into a table named "computers" for some of its columns, with the column names not known in advance hence the need for dynamic insertion. To achieve this, I have created a BaseModel class called "ColumnIn" that consi ...

Can a unique and optional attribute be defined for a class model in (Flask) SQLAlchemy?

I am looking to define a unique and optional attribute in Python Sql Alchemy with Flask and Flask-SQLAlchemy. Is this achievable? membership_number = db.Column(db.String(120), unique=True) ...

sqlalchemy: establish MySQL connection without requiring password

I am facing an issue with accessing my MySQL database "test" using SQLAlchemy. The root user has no password, and I can log in without any problems. mysql -uroot test # all fine I have tried various URLs to access the database with SQLAlchemy: mysql+mys ...

Python and SQLAlchemy tutorial: Establishing a connection to a MySQL server with Cleartext Authentication enabled

Seeking assistance in accessing a MySQL server that only allows mysql_clear_password setup. I have successfully connected using the --enable-cleartext-plugin option through the command line: >> mysql --port NNN -u my_user -h DB.host.com --enable-cle ...

Creating a Deduplication Database Schema Using SQLAlchemy: How to Define a Group Using Object-Relational Mapping (ORM) Principles

Currently, I am working on creating a simplified model for entity deduplication in MySQL and using SQLAlchemy for programmatic access. My goal is to achieve a specific effect that involves what seems like a self-referential query. In my setup, there is an ...

What is the correct way to bind pairs (arrays of tuples or multidimensional arrays) in SQLAlchemy?

Can you show me an example of constructing a MySQL query with SQLAlchemy? SELECT * FROM table WHERE (key->>"$.k1", key->>"$.k2") IN ((1, "string1"), (2, "string2")) I attempted to use the text method but encountered an issue: select([table.c ...

Do we really need to use Flask-Marshmallow's init_app() function?

Upon reviewing the Flask-Marshmallow documentation, it states that Marshmallow.init_app() initializes the application with the extension. The code snippet linked in the documentation appears to play a significant role in managing SQLAlchemy sessions: ...

Failed attempts to retrieve the binary large object (BLOB) from SQLite using Flask SQLAlchemy results in a null

I'm facing an issue while attempting to retrieve a BLOB (LargeBinary) object from SQLite using Flask-SQLAlchemy. The error message I'm encountering is: TypeError: must be string or read-only buffer, not None. This is the code snippet that I am working wit ...

Error Message: The code is throwing an AttributeError because a boolean object does not contain the attribute '_sa_instance_state' when attempting to verify its presence in the database

Recently diving into Flask and SQLA, I am in the process of building a compact educational platform where individuals can explore US national parks (leveraging the National Park Service API). I aim to provide registered users with the capability to bookmar ...

How can I nicely display a SQLAlchemy database with models and relationships in an organized manner?

Looking to visualize the structure of my database in a more comprehensive way. Using Flask-SQLAlchemy as an example, with various models and relationships sourced from SQLAlchemy Docs. class IDModel(db.Model): __abstract__ = True id = db.Column(db.Int ...

Combining JSON data within a MySQL column efficiently with the power of SQLAlchemy

Is there a way to consolidate JSON data that is spread out over multiple rows in a MySQL column using the Python SQLAlchemy library? I tried using json_merge_preserve but encountered difficulties applying it to an entire column. This was the code snippet ...

Tips for optimizing session.add with various relationships to improve performance

Below is the model structure of my source code, represented as an array in a dictionary format. # data structure user_list = [{user_name: 'A', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8feeeeeecfe ...

Incorporating a custom image in a tkinter interface using PIL

I am attempting to utilize a tkinter button in order to display an ERD diagram using sqlalchemy and PIL. I have successfully achieved this by saving the generated image to a file and then reopening that file to display it in a label. Is there a method to ...

Tips for narrowing down a sqlalchemy query based on a specific field within the most recent child entry

My current database structure consists of two tables that are roughly described in SQLAlchemy mapping as follows: class Parent(Base): __tablename__ = "parent" parent_id = Column(Integer, primary_key=True) class Child(Base): __tablename__ = " ...

Start fresh by clearing out postgresql and alembic and beginning anew

I have researched extensively and found that the information available on this topic is inaccurate or incomplete. I am now seeking guidance on how to achieve the following tasks: Clean out all data in my postgresql database Remove all alembic revisions ...

Using timedelta to filter data when a field may be missing

I'm attempting to develop a function within the PlayerAt table to retrieve records from a PlayerOc table based on a filter that utilizes the timedelta feature. Below is an abbreviated version of the class: class PlayerAt(Base): id_ = sa.Column(sa ...

SQLAlchemy is unable to generate relational column connections

Thank you in advance. I'm currently working on an application using Flask and SQLAlchemy. When I first started, I initialized the database by running flask db init. $ flask db init Creating directory /Users/xxxx/app/migrations ... done Creating dire ...

Leveraging SQL Server File Streaming with Python

My goal is to utilize SQL Server 2017 filestream in a Python environment. Since I rely heavily on SQLAlchemy for functionality, I am seeking a way to integrate filestream support into my workflow. Despite searching, I have not come across any implementatio ...

Converting SQL code to SQLAlchemy mappings

I have an unusual query that aims to retrieve all items from a parent table that do not have corresponding matches in its child table. If possible, I would like to convert this into an SQLAlchemy query. However, I am unsure of how to proceed as my experie ...

Exploring the use of the IN operator in SQLAlchemy when querying a list of datetime values in Python

My goal is to filter data using a list of timestamps. In SQL, the syntax would look like this: SELECT * FROM TABLE WHERE TABLE.QueryTimestamp IN ("2017-10-20 23:20:00", "2017-10-10 23:20:00") The column QueryTimestamp stores datetime values in Python. I ...

What is the best way to retrieve the most recent information from APScheduler using sqlalchemy?

I am working on using Advanced Python Scheduler to access data from a MySql database using Flask SQLAlchemy every five seconds. However, despite my efforts, I am facing an issue where I am unable to retrieve the latest modified data from APScheduler throu ...

What are some effective strategies for protecting against SQL injections in Flask-SQLAlchemy? Are there more efficient methods for importing data from CSV files?

I am currently working on a project that involves loading data from the internet into a table using Flask, SQLAlchemy with PostgreSQL/psycopg2. I find myself in a disagreement with one of my colleagues, whom I will refer to as "Dad." Dad insists that execu ...

Utilizing Pylons to Enable Cross-Library Sharing of MySQL Connections with SQLAlchemy

Currently, my setup involves running Pylons with SQLAlchemy to connect to MySQL. In order to utilize a database connection in a controller, I typically do the following: from myapp.model.meta import Session class SomeController(BaseController): def i ...

Implementing a primary key into an already established MySQL table using alembic

Attempting to add a primary key column with an 'id' identifier to an existing MySQL table using alembic. The process involved the following steps... op.add_column('mytable', sa.Column('id', sa.Integer(), nullable=False)) op.a ...

Using an HTML form to gather data, you can store the information in a SQL database using SQLAlchemy in a

Struggling to extract a list of values from an HTML form using Flask and store them in a database column. Attempted to use getlist() method but unsure about the correct way to implement it. Database: association_table = Table('association', Bas ...

Using SQLAlchemy connection pooling with multiple concurrent threads

To start off, I am creating a basic table structure: import threading from sqlalchemy import create_engine from sqlalchemy import Column, Integer, Float, String, Date, DateTime, Boolean, select from sqlalchemy.ext.declarative import declarative_base from ...

SQLAlchemy: Understanding how to use getter and setter methods within a declarative mixin class

In an attempt to create basic getter and setter methods for a mixin class that will be utilized in my database schema, I am facing the following challenge: from sqlalchemy import Column, Integer, create_engine from sqlalchemy.orm import synonym, scoped_se ...

SQLAlchemy: Sorting data based on the result of a different order by query

I have a table called Fulfillment with two columns: status and creation date. My goal is to display the data in descending order by creation date if the status is 'open', and ascending order by creation date if the status is 'closed'. Additionally, I want ...

Ways to resolve issues with multiple foreign keys

Having trouble setting up multiple foreign keys and encountering errors from flask_sqlalchemy import SQLAlchemy sql= SQLAlchemy(app) app.secret_key = os.urandom(24) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql:///test' app.config['SECERET ...

Using Bloodhound with a JSON generated using Flask's jsonify function is a seamless process

Recently, I have been exploring the Bloodhound typeahead feature to implement database search functionality in my Flask application. I found a helpful guide on how to set this up at: Twiiter Typeahead Custom Templates - Getting Default Example Working $(d ...

Persistence of Flask-SQLAlchemy changes does not apply

Building a web application where user actions can impact bar graphs, some changes are not saved. Reloading the page sometimes shows the updated bar graphs, indicating that the user's actions were saved. However, upon further reloads, the changes may or may ...

Transmitting JSON data to a Flask template

I struggled to figure out how to retrieve JSON data from my search results, but I've managed to solve that issue. Now, the challenge is updating my jinja template with the data I fetched. Despite attempting various methods, my lack of experience with ...

Executing cursor.callproc does not produce any results

Here is a method that I have: from app.database import db def get_channels_list(user_token): data = jwt.decode(user_token, app.config.get('JWT_SECRET')) connection = db.engine.raw_connection() try: cursor = connection.cursor ...

Locate specific data in PostgreSQL using SQLAlchemy's primary key search feature - Deprecated notification

When trying to find an object by primary key using the code below, a warning message about deprecated features is displayed. What changes can be made to this query to resolve the deprecated feature warning? Code: def locate_by_primary_key(self, obj_id) ...

Using Sqlalchemy to apply a filter on an object

I am currently working on a script that will test various conditions of objects within a SQLAlachemy ORM driven database. The dynamic nature of this process has presented some challenges for me. My goal is to query the minimum number of objects for all te ...