title: SQLite to PostgreSQL on python code using Flask
body: <p>I've started my application by using the <a href="https://flask.palletsprojects.com/en/1.1.x/tutorial/" rel="nofollow noreferrer">Flask tutorial</a> : 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.</p>
  
  <p>I don't care to lose my data (just a bunch of random data - like <em>uzcvbuyz</em> for a name <em>you know what I mean</em>), how can I convert that code below?</p>
  
  <p>This is the lonely file that use <code>sqlite3</code> library, named <strong>db.py</strong> :</p>
  
  <pre><code>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()  
  </code></pre>
  
  <p>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 <strong>don't care</strong> of losing data, I had previously documented myself about this migration with links on this <a href="https://stackoverflow.com/questions/48820336/transform-flask-with-sqlite-to-flask-with-postgres#comment84648589_48820336">comment</a> or using that <a href="https://realpython.com/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/" rel="nofollow noreferrer">tutorial on realpython website</a>.</p>
  
  <p>I also try to convert that using <code>psycopg2</code> <a href="http://initd.org/psycopg/docs/" rel="nofollow noreferrer">libraries</a>, but I wasn't able to do it well (if not, I won't ask this question ;)</p>