Структура проекта:
app/
static/
templates/
forms.py
models.py
views.py
migrations/
config.py
manage.py
tests.py
# tests.py import unittest from app import create_app, db from flask import current_app class TestCase(unittest.TestCase): def setUp(self): self.app = create_app('test_config') self.app_context = self.app.app_context() self.app_context.push() db.create_all() self.client = self.app.test_client() def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def test_app_exists(self): self.assertFalse(current_app is None) def test_hello(self): response = self.client.get('/') self.assertEqual(response.status_code, 200)
# config.py class Config(object): SECRET_KEY = os.environ.get('COURSES_PROJECT_SECRET_KEY') SQL_COMMIT_ON_TEARDOWN = True @staticmethod def init_app(app): pass class DevConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = os.environ.get('COURSES_PROJECT_DATABASE') class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_COURSES_PROJECT_DATABASE') CSRF_ENABLED = False config = {'default': DevConfig, 'dev_config': DevConfig, 'test_config': TestingConfig}
# app/__init__.py from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from config import config db = SQLAlchemy() def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) return app app = create_app('default') from . import views