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 ;)