Also I'm using the following trick for generating create table/index queries: I point my application to brand new database, enable logging of sqlalchemy queries and run metadata.createall - so in logs (or STDOUT) I see create query generated by sqlalchemy. Depending on the database system you are using index creation query will be little. This is the cheat-sheet I put together for using the Ally Financial API to collect the following: Time and Sales for Stocks; Options Market Depth; Options Extended Quote; If you’re not familiar with an API, check out some of these resources. It is possible to automate trades through their API, but I never got that far into it. Python Pandas Cheat Sheet Last updated on Feb 16, 2021 Import required packages. You will need the sqlalchemy and psycopg2 Python packages.

Github README.md

I spent the first couple hours of today writing README files (explanatory text to accompany the repository) for all of my Github repositories that didn’t get have them. I searched for some advice on what to include/how to format the READMEs and also looked up information on the markdown that Github uses in order to format. (Here’s a helpful Github markdown cheat-sheet I found.) All of my READMEs are pretty brief, but I think that they’ll help make the differences between and the purposes of the files in the repositories more clear.

SQLAlchemy

After spending the majority of yesterday researching SQL, I think I have a much better handle on how it operates and how write statements to query and effect a database. Returning to the SQLAlchemy documentation now to try to understand how to use it in my flask application, I’m able to understand more than before; however, I still find that I don’t have a great conceptual understanding of SQLAlchemy, for example I’m still hazy on the difference between the ORM and the Expression Language of SQLAlchemy.

And so I’m going to spend the rest of today focused on trying to understand SQLAlchemy better and then I’ll return to the mock “final project” for the Udacity course that I was working on two days ago. I’m starting with the creator of SQLAlchemy, Mike Bayer’s, 3-hour tutorial available here.

SQLAlchemy Core

I started by watching the first hour and twenty minutes of Mike Bayer’s Introduction to SQLAlchemy, in which he talks about the most fundamental layers of SQLAlchemy, the engine and metadata elements and Expression Language all contained by the SQLAlchmey Core. I learned about some general topics in programming such as database schema and metadata and also saw useful examples of how to use the Expression Language. There were certainly aspects of the tutorial that I couldn’t understand, but for the most part I was able to follow along after the research on SQL that I did yesterday and with my basic knowledge of python. After watching this first half of the talk, before Bayer turned to the ORM portion, I then spent time back in the SQLAlchemy documentation. In particular, looking at the SQL Expression Language Tutorial docs. After that, I finished watching the second hour and a half of the video, the portion in which Bayer discusses the Object Relational Mapper (ORM). I worked through part of the Object Relational Tutorial in the SQLAlchemy docs, and then before bed I spent a little bit of time looking at the stuff that had been stumping me two nights ago when I was working on the “final project” for the Udacity Full Stack Foundations course. Though I’m still not hugely confident with SQLAlchemy, I was able to fix a couple of the things that I had spent hours fruitlessly trying to manipulate the other night. And I think that when I spend some more time with it in the next couple days, I’ll be able to make the basic queries, inserts, and deletes work in my website.

Flask and SQLAlchemy

In this post, we will build a very simple application using flask, sqlalchemy and postgres. The app will display a simple greeting by retrieving a value that is stored inside persons table. We will be using SQLAlchemy-ORM to define a model - which will create the persons table for us, and then, insert a row manually into the table, and finally retrieve the value from the table to display it.

Next, we will also learn how to run in an interactive mode which is very useful for debugging. Finally, I will provide an overview of querying the model object.

To get started, from your conda environment, install flask and flask-sqlalchemy.

  • pip3 install flask
  • pip3 install flask-sqlalchemy
Cheat

Flask Sqlalchemy Cheat Sheet

Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. It aims to simplify using SQLAlchemy with Flask by providing useful defaults and extra helpers that make it easier to accomplish common tasks.

Basic structure of a flask app

  1. app = Flask(__name__) sets the name of your app to the name of your module (“app” if “app.py” is the name of your file).
  2. Using @app.route: In this case, @app.route is a Python decorator. Decorators take functions and returns another function, usually extending the input function with additional (“decorated”) functionality. @app.route is a decorator that takes an input function index() as the callback that gets invoked when a request to route / comes in from a client.
  3. Running a flask app: FLASK_APP=app.py FLASK_DEBUG=true flask run

Alternative approach to run a Flask app using __main__:

Instead of using flask run, we could have also defined a method

Connecting to the database

Start postgres locally, and get the string postgresql://shravan:shravan@localhost:5432/interview

Configure your app

Use the db.Model - which lets you create and manipulate models. Or use the db.session to create and manipulate transactions.

Models which are defined as classes are mapped to tables within our database.

Given an instance of the SQLAlchemy class from Flask-SQLAlchemy db = SQLAlchemy(app):

  • db is an interface for interacting with our database
  • db.Model lets us create and manipulate data models
  • db.session lets us create and manipulate database transactions in the context of a session.

Code for app.py:

The next thing we need to do is to actually create the tables in our database for all the models that we have declared using db.Model. In order to do this, we need to introduce db.create_all()

db.create_alldetects models for us and creates tables for them, if those tables do not exist. If the tables do exist, then db.create_all doesn’t do anything for us.

This is important to know, since we will be calling db.create_all() multiple times within our Flask application.

From here, we can run our Flask application and expect to see that the model has been declared and also the tables for it has been created for.

Insert a row

Retrieve the value

By default, SQLAlchemy will create a table based on the class name, by making it lowercase. You can specify a different name using the __tablename__ attribute.

Running SQLAlchemy interactively for debugging

We can experiment with our app using the interactive mode of the Python interpreter.

Adding a __repr__ to the model will print the values

Now when you run the app interactively, you can see the values inside those objects.

Inserting rows using db.session.add()

There’s another way of inserting records into our database, rather than entering a client like psql and using INSERT INTO SQL commands: we can call db.session from SQLAlchemy to create records using instances of our defined SQLAlchemy models.

Flask Cheat Sheet

In interactive mode, import db and your Person model. Then, create an instance of a Person, setting its attributes, and setting it equal to a variable person. We’re going to call db.session.add(), a method on the Session interface in SQLAlchemy, to add this object to a session, this will queue up a INSERT INTO persons (name) VALUES ('Veyd'); statement in a transaction that is managed by db.session.

We can then call db.session.commit()

and that person record will now exist in our persons table, within our database! You can double-check this in psql by running a SELECT * from persons; command from psql.

So, in summary, we can insert new records into the database using SQLAlchemy by running:

which will build a transaction for inserting in a person instance in our model/table, and persist it to the database upon calling commit().

Inserting multiple rows using db.session.add_all()

Model.query is the SELECT of SQL.

db.Model.query offers us the Query object. The Query object lets us generate SELECT statements that let us query and return slices of data from our database.

Query has method chaining. You can chain one query method to another (indefinitely), getting back more query objects, until you chain it with a terminal method that returns a non-query object like count(), all(), first(), delete(), etc.

The Query object can be accessed on a model using either:

  • MyModel.query directly on the model, or
  • db.session.query(Model) using db.session.query instead.

The most relevant and commonly used methods on the query:

Flask Sqlalchemy Cheat Sheet Pdf

The only thing here that needs a little explaining is the difference between filter_by and filter.

Sqlalchemy Dynamic Create Table

  • MyModel.query.filter_by(my_table_attribute='some value')
  • MyModel.query.filter(MyOtherModel.some_attr='some value')

filter is similar to filter_by, but instead, you specify attributes on a given Model. It is more flexible than using filter_by itself, and is especially useful when querying from a joined table where you want to filter by attributes that span across multiple models.

Sqlalchemy Cheat Sheet Example

Here’s quick reference that is useful SQLAlchemy Cheat Sheet