Proper usage of flask blueprints with flask-SQLAlchemy
- From:
- VDziubak
- Date:
- 2012-01-27 @ 08:39
Hello!
I am new to flask, but i liked it and i have encountered the next problem:
I liked the concept of blueprints and also want to use flask-SQLAlchemy
to add some database-functionality to the site. But what is the best way
to do that?
For now have written something like this (and, surprisingly, it works! =) )
my folder structure:
templates/
static/
static_page/
__init__.py
models.py
views.py
config.py
runserver.py
test.db
files:
/*#config.py*
/from os import path
DATABASE = 'flaskr.db'
DEBUG = True
SECRET_KEY = 'key'
SQLALCHEMY_DATABASE_URI = 'sqlite:///%s/test.db' %
path.dirname(path.abspath(__file__))
*/#runserver.py/*
from flask import Flask
from flaskext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)
/# import blueprints/
from static_page.views import page
app.register_blueprint(page)
@app.template_filter('datetimeformat')
def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
return value.strftime(format)
if __name__ == '__main__':
app.run()
*/#static_page/views.py/*
from flask import Blueprint, render_template
page = Blueprint('page', __name__)
from static_page.models import Article
@page.route('/', defaults={'alias':'index'})
@page.route('/<alias>/')
def show_page(alias):
article = Article.query.filter_by(alias = alias).first_or_404()
return render_template("page.html", article=article)
*/#static_page/models.py
/*from datetime import datetime
from runserver import db
class Article(db.Model):
__tablename__ = 'articles'
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(20), unique = True)
text = db.Column(db.Text)
mod_date = db.Column(db.DateTime)
alias = db.Column(db.String(20), unique = True)
def __init__(self, title, text, alias):
self.mod_date = datetime.utcnow()
self.title = title
self.text = text;
self.alias = alias;
def __repr__(self):
return "<%s at %s>" % (self.title, self.alias)
*static_page/__init__.py* is empt/y
/
But i think that there must be something better than this. In one of the
topics I have seen next:
It's better to also couple that with blueprints, then you don't have to
create the views in a function:
db = SQLAlchemy()
frontend = Blueprint('frontend', __name__)
@frontend.route('/')
def index():
...
def create_app(config):
app = Flask(__name__)
app.config.update(config)
app.register_blueprint(frontend)
db.init_app(app)
return app
Could somebody, please, explain me where should i put this last
create_app function and how (and where) should I use it?
Sorry for grammar (and, perhaps, spelling) errors,
best regards,
V.Dzyubak