from flask import Flask, render_template
from . import settings
app = Flask(__name__)
app.config.from_object(settings)
@app.route('/')
def index():
return render_template('index.html')
flask_<ability>
from flask_sqlalchemy import SQLAlchemy
# from flask.ext.sqlalchemy import SQLAlchemy (preferred way)
...
db = SQLAlchemy(app)
app
# settings.py
SQLALCHEMY_SCHEMA_URI = 'postgresql://username:password@host:port/database'
# app.py
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
# models.py
from .app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True)
# settings.py
REDIS_URL = 'redis://localhost:6379/0'
# extensions.py
from flask.ext.redis import Redis
redis = Redis()
# app.py
from flask import Flask
from .extensions import redis
def create_app(name, ...):
app = Flask(name)
...
redis.init_app(app)
return app
# views.py
from flask import render_template
from .app import create_app
app = create_app('myapp')
@app.route('/')
def index():
redis = app.extensions['redis']
with redis.pipeline() as pipe:
...
return render_template('index.html', ...)
flask_<ability>
# flask_redis.py
from redis import StrictRedis
class Redis(object):
def __init__(self, app=None):
if app:
self.app = app
self.init_app(app)
def init_app(self, app):
url = app.config.get('REDIS_URL') or 'redis://localhost:6379/0'
connection = StrictRedis.from_url(url)
app.extensions['redis'] = connection
# commands.py
import logging
from flask import current_app
logger = logging.getLogger(__name__)
def stat(record):
redis = current_app.extensions.get('redis')
if not redis:
app_extensions = sorted(current_app.extensions.iterkeys())
logger.warning('No redis extension configured for app',
extra={'app': current_app,
'app_extensions': app_extensions})
return
with redis.pipeline() as pipe:
...
pipe.execute()
Extension.__init__(app=None)
Extension.init_app(app)
init_app
shouldn't assign app
to
self
language: python
python:
- 2.6
- 2.7
- 3.3
- pypy
env:
- FLASK_VERSION=0.8
- FLASK_VERSION=0.9
- FLASK_VERSION=0.10.1
install:
- pip install -e .
- pip install -I Flask==$FLASK_VERSION
- if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2; fi
script:
- python tests.py
- python setup.py test
matrix:
allow_failures:
- python: pypy
exclude:
- python: 3.3
env: FLASK_VERSION=0.8
- python: 3.3
env: FLASK_VERSION=0.9