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
pwy - A simple weather tool.

A simple weather tool. I made this as a way for me to learn Python, API, and PyPi packaging. Name changed from wwy to pwy.

Clint 105 Dec 31, 2022
A linux-like remote terminal for Micropython

A linux-like remote terminal for Micropython

Christian Köver - Draxl 2 Nov 14, 2021
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
Open a file in your locally running Visual Studio Code instance from arbitrary terminal connections.

code-connect Open a file in your locally running Visual Studio Code instance from arbitrary terminal connections. Motivation VS Code supports opening

Christian Volkmann 56 Nov 19, 2022
A communist shell written in Python

kash A communist shell written in Python It doesn't support escapes, quotes, comment lines, |, &&, , or similar yet. If you need help, get it from

Çınar Yılmaz 1 Dec 10, 2021
CLI/GUI Math commands based on python 3

PyMath Commands Syntax Installation Commands: pymath add: usage: pymath add 12.5 12.5 sub: usage: pymath sub 25 12.5 div: usage: pymath div 144 12 mul

eggsnham07 0 Nov 22, 2021
Rdwcli - Car list cli app with python

Rdwcli - Car list cli app with python

Arie Twigt 1 Feb 02, 2022
Dart Version Manager CLI implemented with Python and Typer.

Dart Version Manager Dart Version Manager CLI implemented with Python and Typer Usage: $ dvm [OPTIONS] COMMAND [ARGS]... Options: --install-completion

EducUp 6 Jun 26, 2022
Jupyter notebook client in neovim

🪐 Jupyter-Nvim Read jupyter notebooks in neovim Note: The plugin is still in alpha stage 👾 Usage Just open any *.ipynb file and voila! ✨ Contributin

Ahmed Khalf 85 Dec 29, 2022
split-manga-pages: a command line utility written in Python that converts your double-page layout manga to single-page layout.

split-manga-pages split-manga-pages is a command line utility written in Python that converts your double-page layout manga (or any images in double p

Christoffer Aakre 3 May 24, 2022
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
A tool to manage the study of courses at the university.

todo-cli A tool to manage the study of courses at the university

Quentin 6 Aug 01, 2022
Amazon Scraper: A command-line tool for scraping Amazon product data

Amazon Product Scraper: 2021 Description A command-line tool for scraping Amazon product data to CSV or JSON format(s). Requirements Python 3 pip3 Ins

49 Nov 15, 2021
Joji convert a text to corresponding emoji if emoji is available

Joji Joji convert a text to corresponding emoji if emoji is available How it Works ? 1. There is a json file with emoji names as keys and correspondin

Gopikrishnan Sasikumar 28 Nov 26, 2022
A Tempmail Tool for Terminal and Termux.

A Tempmail Tool for Terminal and Termux.

MAO-COMMUNITY 8 Oct 19, 2022
A dashboard for your Terminal written in the Python 3 language,

termDash is a handy little program, written in the Python 3 language, and is a small little dashboard for your terminal, designed to be a utility to help people, as well as helping new users get used

Rebecca White 2 Dec 03, 2021
A webmining CLI tool & library for python.

minet is a webmining command line tool & library for python (= 3.6) that can be used to collect and extract data from a large variety of web sources

médialab Sciences Po 165 Dec 17, 2022
Ros command - Unifying the ROS command line tools

Unifying the ROS command line tools One impairment to ROS 2 adoption is that all

37 Dec 15, 2022
This is a repository for collecting global custom management extensions for the Django Framework.

Django Extensions Django Extensions is a collection of custom extensions for the Django Framework. Getting Started The easiest way to figure out what

Django Extensions 6k Jan 03, 2023
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