Simple CLI for managing Postgres databases in Flask.

Overview


Overview

Simple CLI that provides the following commands:

  • flask psql create
  • flask psql init
  • flask psql drop
  • flask psql setup: create → init
  • flask psql reset: drop → create → init

These commands are available out of the box as long as you're using Flask-SQLAlchemy. Flask-Postgres finds your db instance for you, so it knows exactly how to create, initialize, and delete your database.

Why Use Flask-Postgres?

  • Simple to use.
  • Zero changes to your application code required! Just pip install flask-postgres and you're ready to go!
  • Great for small apps.
  • Great for speeding up development.
  • Great for Flask / web dev beginners.

Example

The below example shows an app with a custom init_db_callback, which is optional.

# app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_postgres import init_db_callback

app = Flask(__name__)

app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://localhost:5432/example"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)

class Pet(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.Text)

@init_db_callback
def init_db(app, db):
    db.create_all()

    # Add your first pet
    pet = Pet(name="Fido")
    db.session.add(pet)
    db.session.commit()

Now run in your terminal:

flask psql setup

And you'll have a Postgres database up and running with the initialized data.

Want to make a change, and don't mind starting everything over? Then run:

flask psql reset

Setup

pip install flask-postgres

Once you have installed Flask-Postgres, you should be ready to go assuming your code is already set up to use Flask-SQLAlchemy. Check that the commands are available here:

flask psql --help

Custom init Callback

Flask-Postgres does not require any more setup than this, unless you want to add a custom callback that runs when psql init is executed. The callback can take app and/or db args, or the function signature can be left blank:

from flask_postgres import init_db_callback

@init_db_callback
def init_db(app, db):
    db.create_all()

# alternatively...
@init_db_callback
def init_db(app):
    ...

# alternatively...
@init_db_callback
def init_db(db):
    ...

# alternatively...
@init_db_callback
def init_db():
    ...

Note that your init_db_callback will be run inside the application context.

By default, if you do not register a callback, then Flask-Postgres will run db.create_all() for you when initializing the database. So if all you need is db.create_all(), then you can let Flask-Postgres take care of it.

Config

For apps already setup to use Flask-SQLALchemy, all Flask-Postgres configuration is optional, and probably is not necessary for most users.

TLDR

Name Type Description
FLASK_POSTGRES_CLI_DISALLOWED_ENVS Sequence[str] (or str delimited by ;) List of environments where the flask psql CLI is disabled from running.

(Default behavior is the CLI is never disabled.)
FLASK_POSTGRES_TARGET_DATABASE_URI str URL for the Postgres database to be created / initialized / deleted.

(Default behavior is to use SQLALCHEMY_DATABASE_URI.)
FLASK_POSTGRES_ADMIN_DBNAME str Database name to use when connecting to the Postgres server to create or delete another database.

It's not recomended that you mess around with this unless you need to.

(Default behavior is to replace {dbname} with postgres.)

Database connection

By default, Flask-Postgres uses the SQLALCHEMY_DATABASE_URI as the database to be created / initialized / deleted. Flask-Postgres replaces the {dbname} in the URI with postgres to handle database administration.

  • If you don't want Flask-Postgres to use the SQLAlchemy hook, then you can use the variable FLASK_POSTGRES_TARGET_DATABASE_URI.
  • If you don't want to connect to create/delete via -d postgres, then set the FLASK_POSTGRES_ADMIN_DBNAME.

Disallowed environments

By default, flask psql can be run in any environment. If you want to restrict access to flask psql based on the FLASK_ENV, then you can set the config variable FLASK_POSTGRES_CLI_DISALLOWED_ENVS, which is a sequence of strings.

For example, if you don't want flask psql to run in production:

app.config["FLASK_POSTGRES_CLI_DISALLOWED_ENVS"] = ["production"]

This is not protection against malicious use-- anyone with access to a terminal in your production environment can do whatever they want. It is good enough protection against mistakes, though.

Environment variables

You can access all of the above config variables (including SQLALCHEMY_DATABASE_URI) through environment variables.

Flask-Postgres always prefers Flask app config variables to equivalently named environment variables. Additionally, Flask-Postgres always prefers FLASK_POSTGRES_* prefixed variables to using SQLALCHEMY_DATABASE_URI.

For example, if your environment variable is SQLALCHEMY_DATABASE_URI=foo, and your Flask app config variable is FLASK_POSTGRES_TARGET_DATABASE_URI=bar, then Flask-Postgres will use bar.

CLI Options

CLI options always override everything.

Caveat

This package is useful if:

  • You're a web development novice and are not familiar with / overwhelmed by Docker Compose and Alembic (or alternatives).
  • You know Docker Compose and Alembic (or alternatives), but don't want to bother with one or both. For example:
    • Working in a development environment.
    • Fun, minor side project you're hosting on Heroku.

Which is to say, this package is a lightweight alternative to setting up an application in a fully fledged production way.

For serious production stuff, look into Docker Compose (to create your database) and Alembic (to init your database).

Release notes

  • 0.2.0: Broke the API in a few spots and made it more consistent.
    • dbname is the commonly used variable name.
    • Reorganized the config variables around.
    • Lots of refactoring to expose database operations: create_db and drop_db.
    • Added typo checking in the Click context.
    • Added more options: --force-disconnect and --overwrite.
    • Added more robust typing with PostgresUri. This builds and validates a Postgres URI, and provides helpful information to the user on why it's invalid. This is used both internally to make the code nicer + safer, and it's also as a click.ParamType.
  • 0.1.4: First real release.
Owner
Daniel Reeves
🐍 Python. 🏦 Economics & Finance. 🧮 Risk.
Daniel Reeves
A CLI/Shell supporting OpenRobot API and more!

A CLI/Shell supporting JeyyAPI, OpenRobot API and RePI API.

OpenRobot Packages 1 Jan 06, 2022
Un module simple pour demander l'accord de l'utilisateur dans une CLI.

Demande de confirmation utilisateur pour CLI Présentation ask_lib est un module pour le langage Python proposant une seule fonction; ask(). Le but pri

CallMePixelMan 7 May 09, 2022
Investing library and command-line interface inspired by the Bogleheads philosophy

Lakshmi (Screenshot of the lak command in action) Background This project is inspired by Bogleheads forum. Bogleheads focus on a simple but powerful p

Sarvjeet Singh 108 Dec 26, 2022
The command line interface for Gradient - Gradient is an an end-to-end MLOps platform

Gradient CLI Get started: Create Account • Install CLI • Tutorials • Docs Resources: Website • Blog • Support • Contact Sales Gradient is an an end-to

Paperspace 58 Dec 06, 2022
Python-based implementation and comparison of strategies to guess words at Wordle

Solver and comparison of strategies for Wordle Motivation The goal of this repository is to compare, in terms of performance, strategies that minimize

Ignacio L. Ibarra 4 Feb 16, 2022
A Tempmail Tool for Terminal and Termux.

A Tempmail Tool for Terminal and Termux.

MAO-COMMUNITY 8 Oct 19, 2022
CLI to show end-of-life dates for tools and technologies.

Python 3.9+ interface to endoflife.date to show end-of-life dates for tools and technologies.

Hugo van Kemenade 32 Jan 06, 2023
Alacritty terminal used with Bash, Tmux, Vim, Mutt, Lynx, etc. and the many different additions added to each configuration file

Alacritty terminal used with Bash, Tmux, Vim, Mutt, Lynx, etc. and the many different additions added to each configuration file

Carter 19 Aug 24, 2022
Todo - You could use terminal to set your todo

Python Tutorial You can learn how to build a terminal application(CLI applicatio

29 Jun 29, 2022
ghfetch is ai customizable CLI GitHub personal README generator.

ghfetch is ai customizable CLI GitHub personal README generator. Inspired by famous fetch such as screenfetch, neofetch and ufetch, the purpose of this tool is to introduce yourself as if you were a

Alessio Celentano 3 Sep 10, 2021
A basic molecule viewer written in Python, using curses; Thus, meant for linux terminals

asciiMOL A basic molecule viewer written in Python, using curses; Thus, meant for linux terminals. This is an alpha version, featuring: Opening defaul

Dominik Behrens 328 Dec 11, 2022
A selfbot made with DPY, doesn't have much commands but there's some useful commands to use.

Phantom Selfbot A selfbot made in DPY, made by Zenith. How to use Add your token in token = 'YOUR-MOMS-TOKEN-HERE' Change the prefix in prefix = If

[Ͼ⁴] Ƶephyr 2 Dec 02, 2021
Command-line interface to PyPI Stats API to get download stats for Python packages

pypistats Python 3.6+ interface to PyPI Stats API to get aggregate download statistics on Python packages on the Python Package Index without having t

Hugo van Kemenade 140 Jan 03, 2023
Project scoped command execution to just do your work

Judoka is a command line utility that lets you define project scoped commands and call them through their alias. It lets you just do (= judo) your work.

Eelke van den Bos 2 Dec 17, 2021
Lets you view, edit and execute Jupyter Notebooks in the terminal.

Lets you view, edit and execute Jupyter Notebooks in the terminal.

David Brochart 684 Dec 28, 2022
A Python module and command-line utility for converting .ANS format ANSI art to HTML

ansipants A Python module and command-line utility for converting .ANS format ANSI art to HTML. Installation pip install ansipants Command-line usage

4 Oct 16, 2022
Yts-cli-streamer - A CLI movie streaming client which works on yts.mx API written in python

YTSP It is a CLI movie streaming client which works on yts.mx API written in pyt

1 Feb 05, 2022
A startpage configured aesthetically with terminal-esque link formatting

Terminal-y Startpage Setup Clone the repository, then make an unformatted.txt file following the specifications in example.txt. Run format.py Open ind

belkarx 13 May 01, 2022
Simple CLI tool to track your cryptocurrency portfolio in real time.

Simple tool to track your crypto portfolio in realtime. It can be used to track any coin on the BNB network, even obscure coins that are not listed or trackable by major portfolio tracking applicatio

Trevor White 69 Oct 24, 2022
CLI utility to search and download torrents from major torrent sites

CLI Torrent Downloader About CLI Torrent Downloader provides convenient and quick way to search torrent magnet links (and to run associated torrent cl

x0r0x 86 Dec 19, 2022