4

I've started my application by using the Flask tutorial : unfortunately for me, they used all technology that I would use for my project except database, which is SQLite. I would like to use PostgreSQL, notably for its better performance and safety save provided, but I don't know how to convert my code to work with PostgreSQL instead of SQLite.

I don't care to lose my data (just a bunch of random data - like uzcvbuyz for a name you know what I mean), how can I convert that code below?

This is the lonely file that use sqlite3 library, named db.py :

import sqlite3

import click
from flask import current_app, g
from flask.cli import with_appcontext

def init_app(app):
    app.teardown_appcontext(close_db)
    app.cli.add_command(init_db_command)

def init_db():
    db = get_db()
    with current_app.open_resource('schema.sql') as d:
        db.executescript(d.read().decode('utf8'))

@click.command('init-db')
@with_appcontext
def init_db_command():
    """Clear the existing data and create new tables."""
    init_db()
    click.echo('Initialized the database.')

def get_db():
    if 'db' not in g:
        g.db = sqlite3.connect(
            current_app.config['DATABASE'],
            detect_types=sqlite3.PARSE_DECLTYPES
        )
        g.db.row_factory = sqlite3.Row
    return g.db

def close_db(e=None):
    db = g.pop('db', None)
    if db is not None:
        db.close()  

If there is any other steps to do (I work with Ubuntu 18.04, so command line won't be hard for me), please let me know. And remember that I don't care of losing data, I had previously documented myself about this migration with links on this comment or using that tutorial on realpython website.

I also try to convert that using psycopg2 libraries, but I wasn't able to do it well (if not, I won't ask this question ;)

halfer
  • 19,824
  • 17
  • 99
  • 186
damadam
  • 330
  • 4
  • 17
  • In relation to converting this code, what are you stuck on in particular? "All of it" would make this question rather too broad for Stack Overflow, unfortunately. – halfer Oct 23 '19 at 16:04
  • @roganjosh at part 4, at **Flask-SQLAlchemy Configuration**, he says `During development, I'm going to use a SQLite database` – damadam Oct 24 '19 at 10:08
  • @halfer just converting the `get_db()` definition isn't suffisant with `psycopg2` packages? I had read that `psycopg2` also had a `connect` object, but I don't find which one would replace the `sqlite3.Row` :/ – damadam Oct 24 '19 at 10:11

0 Answers0