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.
You might also like...
AWS Interactive CLI - Allows you to execute a complex AWS commands by chaining one or more other AWS CLI dependency

AWS Interactive CLI - Allows you to execute a complex AWS commands by chaining one or more other AWS CLI dependency

Python-Stock-Info-CLI: Get stock info through CLI by passing stock ticker.
Python-Stock-Info-CLI: Get stock info through CLI by passing stock ticker.

Python-Stock-Info-CLI Get stock info through CLI by passing stock ticker. Installation Use the following command to install the required modules at on

Yts-cli-streamer - A CLI movie streaming client which works on yts.mx API written in python
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

[WIP]An ani-cli like cli tool for movies and webseries

mov-cli A cli to browse and watch movies. Installation This project is a work in progress. However, you can try it out python git clone https://github

gget is a free and open-source command-line tool and Python package that enables efficient querying of genomic databases.
gget is a free and open-source command-line tool and Python package that enables efficient querying of genomic databases.

gget is a free and open-source command-line tool and Python package that enables efficient querying of genomic databases. gget consists of a collection of separate but interoperable modules, each designed to facilitate one type of database querying in a single line of code.

cmsis-pack-manager is a python module, Rust crate and command line utility for managing current device information that is stored in many CMSIS PACKs

cmsis-pack-manager cmsis-pack-manager is a python module, Rust crate and command line utility for managing current device information that is stored i

💻VIEN is a command-line tool for managing Python Virtual Environments.

vien VIEN is a command-line tool for managing Python Virtual Environments. It provides one-line shortcuts for: creating and deleting environments runn

Command-line program for organizing and managing ebook collections
Command-line program for organizing and managing ebook collections

Command-line program for organizing and managing ebook collections. It is a Python port from the original shell scripts ebook-tools

Comments
  • add db templates; add rich-click as optional

    add db templates; add rich-click as optional

    Choice of default behavior for Rich-Click:

    I entertained the idea of: if you have Rich-Click in the environment, then just use it. This can make sense if you explicitly installed it yourself as a little shortcut.

    However, if you pip install [somepackage] other than Rich-Click, and it includes Rich-Click as a dependency, it would violate the principle of least surprise for flask psql --help to change its output based on a pip install of another package. Therefore, the default behavior of not using Rich-Click is more intuitive.

    opened by dwreeves 0
  • [BUG] allow extended scheme

    [BUG] allow extended scheme

    Ran into an issue messing around with a URI that had a scheme of postgres+psycopg2://. That should be considered valid and I shouldn't bug the user about it.

    opened by dwreeves 0
Owner
Daniel Reeves
🐍 Python. 🏦 Economics & Finance. 🧮 Risk.
Daniel Reeves
Postgres CLI with autocompletion and syntax highlighting

A REPL for Postgres This is a postgres client that does auto-completion and syntax highlighting. Home Page: http://pgcli.com MySQL Equivalent: http://

dbcli 10.8k Jan 2, 2023
CLI utility for updating the EVE Online static data export in a postgres database

EVE SDE Postgres updater CLI utility for updating the EVE Online static data export postgres database. This has been tested with the Fuzzwork postgres

Markus Juopperi 1 Oct 29, 2021
Proman is a simple tool for managing projects through cli.

proman proman is a project manager. It helps you manage your projects from a terminal. The features are listed below. Installation Step 1: Download or

Arjun Somvanshi 2 Dec 6, 2021
CLI for SQLite Databases with auto-completion and syntax highlighting

litecli Docs A command-line client for SQLite databases that has auto-completion and syntax highlighting. Installation If you already know how to inst

dbcli 1.8k Dec 31, 2022
Python CLI utility and library for manipulating SQLite databases

sqlite-utils Python CLI utility and library for manipulating SQLite databases. Some feature highlights Pipe JSON (or CSV or TSV) directly into a new S

Simon Willison 1.1k Jan 4, 2023
Python Library and CLI for exporting MySQL databases

expdb Python library and CLI for exporting MySQL databases Installation Pre-requisites MySQL server Python 3.9+ Using git Clone the repository to your

Devansh Singh 1 Nov 29, 2021
Pymongo based CLI client, to run operation on existing databases and collections

Mongodb-Operations-Console Pymongo based CLI client, to run operation on existing databases and collections Program developed by Gustavo Wydler Azuaga

Gus 1 Dec 1, 2021
A simple CLI based any Download Tool, that find files and let you stream or download thorugh WebTorrent CLI or Aria or any command tool

Privateer A simple CLI based any Download Tool, that find files and let you stream or download thorugh WebTorrent CLI or Aria or any command tool How

Shreyash Chavan 2 Apr 4, 2022
Sink is a CLI tool that allows users to synchronize their local folders to their Google Drives. It is similar to the Git CLI and allows fast and reliable syncs with the drive.

Sink is a CLI synchronisation tool that enables a user to synchronise local system files and folders with their Google Drives. It follows a git C

Yash Thakre 16 May 29, 2022
flora-dev-cli (fd-cli) is command line interface software to interact with flora blockchain.

Install git clone https://github.com/Flora-Network/fd-cli.git cd fd-cli python3 -m venv venv source venv/bin/activate pip install -e . --extra-index-u

null 14 Sep 11, 2022