How to delete or modify a database table using Flask-SQLAlchemy? - python

Is there a way to delete or modify a table using flask-sqlalchemy?
I am working on a Flask-based web app. I switched to flask-sqlalchemy as my project is on Heroku and I had to connect my table to Heroku PostgreSQL. I made a flask-sqlalchemy table and created it using the db.create_all() command.
Now, for my app to fulfill its purpose, it is of utmost importance to save images, the best way of which I found to be to add them to the database.
Now, I want to change the particular table class to store a column called image as image = db.Column(db.Text, nullable=False) but I cannot. The former schema is unchanged and it gives me an error signifying that the column image does not exist every time I try to access or add something to the table.
How to do this?

You can use drop()
from sqlalchemy import create_engine
engine = create_engine("...")
my_table.__table__.drop(engine)

Related

Creating Hypertables through SQL Alchemy

Our current project relies heavily on SQL Alchemy for table creation/data insertion. We would like to switch to timescaledb's hypertables, but it seems the recommended way to create hypertables is by executing a
create_hypertable
command. I need to be able to dynamically create tables, and so manually doing this for every table created is not really an option. One way of handling the conversion is to run a python script sending psycopg2 commands to convert all newly-created tables into hypertables, but this seems a little clumsy. Does timescaledb offer any integration with SQL Alchemy with regards to creating hypertables?
We currently do not offer any specific integrations with SQL Alchemy (broadly or specifically for creating hypertables). We are always interested in hearing new feature requests, so if you wanted to post your issue/use case on our Github it would help us keep better track of it for future work.
One thing that might work for your use case is to create an event trigger that executes on table creation. You'd have to check that it's in the correct schema since TimescaleDB creates its own chunk tables dynamically and you don't want to have them converted to hypertables.
See this answer for more info on event triggers:
execute a trigger when I create a table
Here is a practical example of using event trigger to create a hyper table:
from sqlalchemy import Column, Integer, DateTime, event, DDL, orm
Base = orm.declarative_base()
class ExampleModel(Base):
__tablename__ = 'example_model'
id = Column(Integer, primary_key=True)
time = Column(DateTime)
event.listen(
ExampleModel.__table__,
'after_create',
DDL(f"SELECT create_hypertable('{ExampleModel.__tablename__}', 'time');")
)

How to insert 100s of values to a db if I am using sqlalchemy and mysql for python flask?

I am new to flask. So I came to know about sql alchemy. Can someone explain me how to use it properly?
Is it like, we need to create a Mysql db first and connect to flask or is everything done through sqlalchemy?
or whatever be the tables in mysql,same have to be represented in models.py???
I tried many tutorials but nothing explains the same.
Thanks in advnce
For your use case, to insert 100s of value a once use BULK operations like add_all (http://docs.sqlalchemy.org/en/rel_1_0/orm/persistence_techniques.html#bulk-operations)
If you don't know Sqlalchemy go here http://docs.sqlalchemy.org/en/latest/orm/tutorial.html
from app import session
from models import User
objects = [User(name="u1"), User(name="u2"), User(name="u3")]
session.add_all(objects)
session.commit()

Sqlalchemy create a database table manually

Is there a way to create a table without using Base.metadata.create_all(). I'm looking for something like Mytable.create() which should create only its corresponding table.
The reason I want to do so is because i'm using Postgres schemas for a multi-tenant web app and I want to create the public tables(Useretc) separately and the user specific(each having a separate schema, ex. Blog,Post) tables when the user signs up. However all the definitions lie in the same file and it seems that create_all creates all the tables defined in the file.
Please read documentation Creating and Dropping Database Tables.
You can do user_table.create(engine), or if you are using declarative extension: User.__table__.create(engine).

django postgresql query not working

I have a postgreSQL database that has a table foo that I've created outside of django. I used manage.py inspectdb to build the model for table foo for me. This technique worked fine when I was using MySQL but with PostgreSQL it is failing MISERABLY. The table is multiple gigabytes and I build it from a text file with PostgreSQL 'COPY'.
I can run raw queries on table foo and everything executes and expected.
For example
foo.objects.raw('bar_sql')
executes as expected.
But running queries like:
foo.objects.get(bar=bar)
throw
ProgrammingError column foo.id does not exist LINE 1: SELECT "foo"."id", "foo"."bar1", "all_...
foo doesn't innately have an id field. As I understand it django is suppose to create one. Have I some how subverted this step when creating the tables outside of django?
Queries run on models whose table was populated threw django run as expected in all cases.
I'm missing something very basic here and any help would be appreciated.
I'm using django 1.6 with postgreSQL 9.3.
Django doesn't modify your existing database tables. It only creates new tables. If you have existing tables, it usually doesn't touch them at all.
"As I understand it django is suppose to create one." --> It only adds a primary key to a table when it creates it, which means you don't need to specify that explicitly in your model, but it won't do anything to an existing table.
So if for example you later on decide to add fields to your models, you have to update your databases manually.
What you need to do in your case is that by doing manual database administration make sure that your table has a primary key, and also that the name of the primary key is "id" (although I am not sure if this is necessary, it is better to do it.) So use a database administration tool, modify your table and add the primary key, and name it id. Then it should start working.

Flask-SQLAlchemy - When are the tables/databases created and destroyed?

I am a little confused with the topic alluded to in the title.
So, when a Flask app is started, does the SQLAlchemy search theSQLALCHEMY_DATABASE_URI for the correct, in my case, MySQL database. Then, does it create the tables if they do not exist already?
What if the database that is programmed into theSQLALCHEMY_DATABASE_URI variable in the config.py file does not exist?
What if that database exists, and only a few of the tables exist (There are more tables coded into the SQLAlchemy code than exist in the actual MySQL database)? Does it erase those tables and then create new tables with the current specs?
And what if those tables do all exist? Do they get erased and re-created?
I am trying to understand how the entire process works so that I (1) Don't lose database information when changes are made to the schema, and (2) can write the necessary code to completely manage how and when the SQLAlchemy talks to the actual Database.
Tables are not created automatically; you need to call the SQLAlchemy.create_all() method to explicitly to have it create tables for you:
db = SQLAlchemy(app)
db.create_all()
You can do this with command-line utility, for example. Or, if you deploy to a PaaS such as Google App Engine, a dedicated admin-only view.
The same applies for database table destruction; use the SQLAlchemy.drop_all() method.
See the Creating and Dropping tables chapter of the documentation, or take a look at the database chapter of the Mega Flask Tutorial.
You can also delegate this task to Flask-Migrate or similar schema versioning tools. These help you record and edit schema creation and migration steps; the database schema of real-life projects is never static and you would want to be able to move existing data between versions or the schema. Creating the initial schema is then just the first step.

Categories