Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
flask-sqlalchemy
  • Loading branch information
mjhea0 committed Jun 18, 2014
1 parent ce730c4 commit 60a71e8
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 18 deletions.
28 changes: 11 additions & 17 deletions app.py
@@ -1,15 +1,22 @@
# import the Flask class from the flask module
from flask import Flask, render_template, redirect, \
url_for, request, session, flash, g
url_for, request, session, flash
from functools import wraps
from flask.ext.sqlalchemy import SQLAlchemy
import sqlite3

# create the application object
app = Flask(__name__)

# config
app.secret_key = 'my precious'
app.database = 'sample.db'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'

# create the sqlalchemy object
db = SQLAlchemy(app)

# import db schema
from models import *


# login required decorator
Expand All @@ -29,20 +36,7 @@ def wrap(*args, **kwargs):
@login_required
def home():
# return "Hello, World!" # return a string
posts = []
try:
g.db = connect_db()
cur = g.db.execute('select * from posts')

for row in cur.fetchall():
posts.append(dict(title=row[0], description=row[1]))

# posts = [dict(title=row[0],
# description=row[1]) for row in cur.fetchall()]

g.db.close()
except sqlite3.OperationalError:
flash('Missing the DB!')
posts = db.session.query(BlogPost).all()
return render_template('index.html', posts=posts) # render a template


Expand Down Expand Up @@ -76,7 +70,7 @@ def logout():

# connect to database
def connect_db():
return sqlite3.connect(app.database)
return sqlite3.connect('posts.db')


# start the server with the 'run()' method
Expand Down
14 changes: 14 additions & 0 deletions db_create.py
@@ -0,0 +1,14 @@
from app import db
from models import BlogPost

# create the database and the db table
db.create_all()

# insert data
db.session.add(BlogPost("Good", "I\'m good."))
db.session.add(BlogPost("Well", "I\'m well."))
db.session.add(BlogPost("Excellent", "I\'m excellent."))
db.session.add(BlogPost("Okay", "I\'m okay."))

# commit the changes
db.session.commit()
17 changes: 17 additions & 0 deletions models.py
@@ -0,0 +1,17 @@
from app import db


class BlogPost(db.Model):

__tablename__ = "posts"

id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String, nullable=False)
description = db.Column(db.String, nullable=False)

def __init__(self, title, description):
self.title = title
self.description = description

def __repr__(self):
return '<title {}'.format(self.title)
2 changes: 1 addition & 1 deletion sql.py
Expand Up @@ -10,7 +10,7 @@
c = connection.cursor()

# create the table
c.execute('CREATE TABLE posts(title TEXT, details TEXT)')
c.execute('CREATE TABLE posts(title TEXT, description TEXT)')

# insert dummy data into the table
c.execute('INSERT INTO posts VALUES("Good", "I\'m good.")')
Expand Down

0 comments on commit 60a71e8

Please sign in to comment.