Criando e Conectando Banco de Dados

Primeiro iremos criar um arquivo schema.sql contendo a estrura do banco de dados. Depois disso criaremos um arquivo init.db.py para criar a conexão com o banco e rodar o banco.

import sqlite3

connection = sqlite3.connect('database.db')

with open('schema.sql') as f:
  connection.executescript(f.read())

cur = connection.cursor()

cur.execute("INSERT INTO posts(title, content) VALUES(?, ?)", ('First Post', 'Content for the first post'))
cur.execute("INSERT INTO posts(title, content) VALUES(?, ?)", ('Second Post', 'Content for the second post'))

connection.commit()
connection.close()

Com o código completo, basta abrir o terminal e rodar o comando

python init.db.py

Consumindo Dados

No arquivo app.py:

from flask import Flask, render_template
import os, detetime
import sqlite3
from flask_sqlalchemy import SQLAlchemy

project_dir = os.path.dirname(os.path.abspath(__file__))
database_file = "sqlite:///{}".format(os.path.join(project_dir, 'database.db'))

app = Flask('__name__')

app.config['SECRET_KEY'] = 'your secret key'
app.config['SQLALCHEMY_DATABASE_URI'] = database_file
db = SQLAlchemy(app)

class Posts(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
  title = db.Column(db.String(80), nullable=False)
  content = db.Column(db.String(200), nullable=False)

@app.route('/')
def index():
  return  render_template('index.html')