Permalink
Browse files

flask-sqlalchemy

  • Loading branch information...
mjhea0 committed Jun 18, 2014
1 parent ce730c4 commit 60a71e868925d3a9dbdb93651ec4d83af7a20887
Showing with 43 additions and 18 deletions.
  1. +11 −17 app.py
  2. +14 −0 db_create.py
  3. +17 −0 models.py
  4. +1 −1 sql.py
View
28 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
@@ -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
@@ -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
View
@@ -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()
View
@@ -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)
View
2 sql.py
@@ -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.")')

0 comments on commit 60a71e8

Please sign in to comment.