Skip to content

Using PostgreSQL instead of Sqlite

brandon flowers edited this page May 28, 2019 · 7 revisions

A Walkthrough of how I replaced Sqlite with PostgreSQL for Development & Production

Step 1/4

In the app folder, find the requirements.txt and add:

psycopg2==2.8.2

Step 2/4

In the root direction, find local_config.py.template and rename it to local_config.py

Next, find config.py and edit it to reflect postgresql instead of sqlite. I added settings for my local Postgres db used in development and the Postgres db that I'll be using remotely in production.

Step 3/4

Within the app folder, find the extensions folder then find flask_sqlalchemy. Edit the init.py so that it picks up postgresql instead of sqlite. I had to hack this step since I didn't get how it was reading the env and simply commented out the sqlite stuff and used a postgres connection instead. I'll revisit this step when I learn the right way or feel free to edit this step.

My hack - this does work but I'm sure there is a much better way involving the config instance instead

    def init_app(self, app):
        super(SQLAlchemy, self).init_app(app)

        DB_USER = 'my-user-name'
        DB_PASSWORD = 'my-password'
        DB_NAME = 'restplusdb'
        DB_HOST = 'localhost'
        DB_PORT = 5432
        SQLALCHEMY_DATABASE_URI = 'postgresql://{user}:{password}@{host}:{port}/{name}'.format(
            user=DB_USER,
            password=DB_PASSWORD,
            host=DB_HOST,
            port=DB_PORT,
            name=DB_NAME,
        )

        database_uri = SQLALCHEMY_DATABASE_URI

        # assert database_uri, "SQLALCHEMY_DATABASE_URI must be configured!"
        # if database_uri.startswith('sqlite:'):
        #    self.event.listens_for(engine.Engine, "connect")(set_sqlite_pragma)

        app.extensions['migrate'] = AlembicDatabaseMigrationConfig(self, compare_type=True)

Step 4/4

Make sure you have installed invoke

I created a virtual environment called teams

$ python3 -m venv teams
$ source teams/bin/activate
$ invoke app.run 

Then you should be see the demo in the browser

http://127.0.0.1:5000/api/v1/

In order to test the endpoints, we need click the authorize button on top right.

Authorize

Username: root
Password: q 

From the drop down select "Basic Auth" which will reveal 2 more fields:

clientID: documentation
Secret: KQ()SWK)SQK)QWSKQW(SKQ)S(QWSQW(SJ*HQ&HQW*SQ*^SSQWSGQSG

If you only see Cancel, scroll down and click the Authorize button

The screen will flash, if you are connected, instead of Authorize, you should now see Logout. Also now you will be able to test the endpoints.

Clone this wiki locally