Kokas
Kokas

Reputation: 131

Working with a sql script in a Flask application

I have created a structure of a basic Flask application and I need guidance with executing a sql script. My folder structure is this:

-simpleblog (name of app)

  flask (contains the virtual environment, 3 folders)
  app
    static (css, js)
    templates (html)
    __init__.py
  config.py
  run.py

I have a sql script with the definition of one table, and I don't know where to place it and how to execute it. I know sqlite3 is part of python, but must I install anything else?

Upvotes: 3

Views: 3301

Answers (1)

codegeek
codegeek

Reputation: 33299

Look at this tutorial from flask website that explains how to use a sqllite database and execute sql scripts along with a suggested folder structure. Usually, you can create a schema.sql file and put it in the main app folder. In your example, you can put it as:

app
    static (css, js)
    templates (html)
    __init__.py
    config.py
    run.py
    schema.sql # your sql script

http://flask.pocoo.org/docs/tutorial/schema/#tutorial-schema

To create the initial database, use this. But you do need to install sqllite3 first.

http://flask.pocoo.org/docs/tutorial/dbinit/#tutorial-dbinit

Basically, it lets you create your initial database by running the following command:

sqlite3 /tmp/flaskr.db < schema.sql

Lets understand the above command. we have the database creation scripts (CREATE,DROP etc.) in schema.sql. We take that as a input to the sqlite3 executable and create the database at /tmp/flaskr.db. Note: you might need to run the following command first to generate a blank flaskr.db file

touch /tmp/flaskr.db

Upvotes: 1

Related Questions