Example #1
1
def create_app(settings_override=None):
    """Returns a :class:`Flask` application instance.
    :param settings_override: a dictionary of settings to override.
    :return: Flask application instance.
    """
    app = Flask(__name__, instance_relative_config=True)
    app.json_encoder = JSONEncoder
    app.config.from_object("tcc3sso.settings")
    app.config.from_object(settings_override)

    # something need init
    db.init_app(app)
    lm.init_app(app)
    Bootstrap(app)

    @lm.user_loader
    def load_user(user_id):
        user = UserProfile.objects.get(id=user_id)
        return user

    app.register_blueprint(bp_main)
    app.register_blueprint(bp_sso)
    app.register_blueprint(bp_api)
    app.register_blueprint(bp_api_1_0)

    for e in [500, 404]:
        app.errorhandler(e)(handle_error)

    return app
Example #2
1
def create_app():
    """Create an application instance."""
    cfg = (
        os.path.join(os.getcwd(), "config.py")
        if os.path.exists("config.py")
        else os.path.join(os.getcwd(), "mopa/config.py")
    )

    app = Flask(__name__)
    app.json_encoder = CustomJSONEncoder
    app.config["JSON_PRETTYPRINT_REGULAR"] = False
    app.config.from_pyfile(cfg)
    setup_logging(app)

    # initialize extensions
    db.init_app(app)
    reggie.init_app(app)
    # cors.init_app(app, resources={r"/api/*": {"origins": "*"}})

    # One line of code to cut our Flask page load times by 60%
    # https://blog.socratic.org/the-one-weird-trick-that-cut-our-flask-page-load-time-by-70-87145335f679#.8r14wvy5w
    app.jinja_env.cache = {}

    # register blueprints
    from .views import bp as api_blueprint

    app.register_blueprint(api_blueprint)

    from .tasks import bp as tasks_blueprint

    app.register_blueprint(tasks_blueprint, url_prefix="/tasks")

    return app
Example #3
1
    def test_custom_json_encoder(self):
        from datetime import datetime
        from flask.json import JSONEncoder

        class JsonEncoder(JSONEncoder):
            def default(self, obj):
                if hasattr(obj, "__json__"):
                    return obj.__json__()
                if isinstance(obj, datetime):
                    return obj.isoformat()
                return super(JsonEncoder, self).default(obj)

        class Custom:
            def __init__(self, custom):
                self.custom = custom

            def __json__(self):
                return dict(custom=self.custom)

        date = datetime(2014, 5, 26, 23, 59, 59)

        class DateResource(flask_restful.Resource):
            def get(self):
                return Custom(date)

        app = Flask(__name__)
        app.json_encoder = JsonEncoder
        api = flask_restful.Api(app)
        api.add_resource(DateResource, "/date")
        client = app.test_client()
        resp = client.get("/date")
        self.assertEquals(resp.data.decode(), '{"custom": "2014-05-26T23:59:59"}')
Example #4
1
def create_app():
    app = Flask(__name__, static_folder="static", static_url_path="")  # FIXME: is it correct name?

    app.config.from_object(config)

    for blueprint in blueprints:
        app.register_blueprint(blueprint)

    db.init()

    app.json_encoder = AdvancedJSONEncoder

    login_manager.login_view = "user.login"

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(id)

    login_manager.init_app(app)

    @app.teardown_appcontext
    def teardown_db(exception=None):
        db.teardown()

    return app
Example #5
1
def create_api_app(config=None):
    app = Flask(__name__)

    if config:
        app.config.from_pyfile(config)

    app.config["JSONSCHEMA_DIR"] = os.path.abspath("doorbot/views/api/schemas")

    app.url_map.strict_slashes = False

    jsonschema.init_app(app)
    db.init_app(app)

    from .container import container

    container.init_app(app)

    from .views.api import account, auth, devices, doors, integrations, notifications, people
    from .views.api.lib.json_serializer import ApiJsonEncoder

    app.json_encoder = ApiJsonEncoder
    app.register_blueprint(auth)
    app.register_blueprint(account)
    app.register_blueprint(devices)
    app.register_blueprint(doors)
    app.register_blueprint(integrations)
    app.register_blueprint(notifications)
    app.register_blueprint(people)

    return app
Example #6
1
def create_app(package_name, package_path, settings_override=None, register_security_blueprint=True):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the Tcc3Portal platform.

    :param package_name: application package name.
    :param package_path: application package path.
    :param settings_override: a dictionary of settings to override.
    :param register_security_blueprint: flag to specify if the Flask-Security
                                        Blueprint should be registered. Defaults
                                        to `True`.
    :return: Flask application instance.
    """
    app = Flask(package_name, instance_relative_config=True)

    app.json_encoder = JSONEncoder
    app.config.from_object("tcc3portal.settings")
    app.config.from_pyfile("settings.cfg", silent=True)
    app.config.from_object(settings_override)

    # something need init
    # security.init_app(app, None, register_blueprint=register_security_blueprint)
    db.init_app(app)
    bootstrap.init_app(app)
    lm.init_app(app)
    babel.init_app(app)
    sso_client.init_app(app, lm)
    TccFrontend(app)

    register_blueprints(app, package_name, package_path)

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    return app
Example #7
1
def create_app(config):

    """A factory that returns an application object from the passed config.

    The factory accepts further configuration from ENV variables. Some simple
    checks for core configuration settings are made to raise errors early
    if vital information is missing.

    """

    import os
    from flask import Flask
    from flask.ext.babel import Babel
    from flask.ext.cors import CORS
    from flask.ext.markdown import Markdown

    #    from flask.ext.assets import Environment, Bundle
    from .components import api, pages
    from .components.commons import context_processors, encoders

    app_label = "web"

    # Get the static and template folder for the passed theme
    static_folder = os.path.join("theme", "static")
    template_folder = os.path.join("theme", "templates")

    # Construct app and service objects
    app = Flask(app_label, template_folder=template_folder, static_folder=static_folder, static_url_path="/static")
    trans = Babel()
    cors = CORS(resources=r"/api/*", allow_headers="Content-Type")
    #    assets = Environment()

    # Configure the app with defaults
    app.config.from_object(config)

    # Set app core services
    trans.init_app(app)
    cors.init_app(app)
    #    assets.init_app(app)
    Markdown(app)

    # Register routable components
    app.register_blueprint(api.blueprint)
    app.register_blueprint(pages.blueprint)

    # Set additional jinja2 extensions
    app.jinja_env.add_extension("jinja2.ext.do")

    # Set custom context processors
    app.context_processor(context_processors.inject_app_data)

    # Set custom encoders
    app.json_encoder = encoders.JSONEncoder

    # Register webassets bundles
    #    sass = Bundle('css/base.scss', filters='pyscss', output='css/base.css')
    #    assets.register('sass', sass)

    return app
Example #8
0
def create_base_app(config):
    """Init configuration and extensions"""
    app = Flask(__name__)
    app.config.from_object(config)
    config.init_app(app)

    app._logger = init_logger(syslogtag=app.config["LOGGER_SYSLOGTAG"], logger_name=app.config["LOGGER_NAME"])

    db.init_app(app)
    bcrypt.init_app(app)

    if app.config["DEBUG"]:
        admin_extension.init_app(app)
        debug_toolbar.init_app(app)

    login_manager.init_app(app)
    login_manager.anonymous_user = Anonymous
    # Change these views to fit your app
    login_manager.login_view = "auth.login"
    login_manager.refresh_view = "auth.login"
    login_manager.login_message = "You do not have access to that page."
    login_manager.user_loader(load_user)

    app.json_encoder = CustomJSONEncoder

    return app
Example #9
0
def create_app(config_name):

    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.json_encoder = CustomJSONEncoder
    config[config_name].init_app(app)

    db.init_app(app)
    csrf.init_app(app)
    babel.init_app(app)
    mail.init_app(app)
    breadcrumbs.init_app(app)
    moment.init_app(app)
    login_manager.init_app(app)

    if not app.debug and not app.config["SSL_DISABLE"]:
        from flask.ext.sslify import SSLify

        SSLify(app)

    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint

    app.register_blueprint(auth_blueprint)

    from .api import api as api_blueprint

    app.register_blueprint(api_blueprint, url_prefix="/api")

    return app
Example #10
0
def create_base_app(config):
    """Init configuration and extensions"""
    app = Flask(__name__)
    app.config.from_object(config)
    config.init_app(app)

    file_handler = SysLogHandler()
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

    db.init_app(app)
    bcrypt.init_app(app)

    if app.config["DEBUG"]:
        admin_extension.init_app(app)
        debug_toolbar.init_app(app)

    login_manager.init_app(app)
    login_manager.anonymous_user = Anonymous
    # Change these views to fit your app
    login_manager.login_view = "auth.login"
    login_manager.refresh_view = "auth.login"
    login_manager.login_message = "You do not have access to that page."
    login_manager.user_loader(load_user)

    app.json_encoder = CustomJSONEncoder

    return app
Example #11
0
    def create_app(self):
        app = Flask(__name__)
        app.json_encoder = _JSONEncoder
        app.secret_key = "secret"

        @app.route("/", methods=("GET", "POST"))
        def index():

            form = MyForm()
            if form.validate_on_submit():
                name = form.name.data.upper()
            else:
                name = ""

            return render_template("index.html", form=form, name=name)

        @app.route("/simple/", methods=("POST",))
        def simple():
            form = SimpleForm()
            form.validate()
            assert form.csrf_enabled
            assert not form.validate()
            return "OK"

        @app.route("/two_forms/", methods=("POST",))
        def two_forms():
            form = SimpleForm()
            assert form.csrf_enabled
            assert form.validate()
            assert form.validate()
            form2 = SimpleForm()
            assert form2.csrf_enabled
            assert form2.validate()
            return "OK"

        @app.route("/hidden/")
        def hidden():

            form = HiddenFieldsForm()
            return render_template("hidden.html", form=form)

        @app.route("/ajax/", methods=("POST",))
        def ajax_submit():
            form = MyForm()
            if form.validate_on_submit():
                return jsonify(name=form.name.data, success=True, errors=None)

            return jsonify(name=None, errors=form.errors, success=False)

        return app
def create_app(_config="development"):
    app = Flask(__name__)

    CORS(app)

    app.config.from_object(config[_config])
    app.json_encoder = MyJSONEncoder

    from app.inventory import views
    from app.cart import views
    from app import views

    app.register_blueprint(api)

    return app
Example #13
0
def create_app(config_from_object=None, config_from_env=None):
    """A factory function to produce a Flask application instance

  This will create the one true application, in a flexible and extensible way.
  The app is being created via a factory function in order to facilitate custom
  or manual configurations.  In this fashion, the app could be configured
  automatically by the Flask-Script file ``manage.py`` during development using
  an environment variable on a local workstation prescribing a
  ``DevelopmentConfig``, while on the production machine, it will resolve to a
  ``ProductionConfig``, or manually specified in the tests directory during set-
  up as ``TestingConfig`` as defined in the :mod:`foodtruck.config` module.

  The app will register the :mod:`foodtruck.backend` module at the endpoint
  specified by``API_ENDPOINT`` using a Flask blueprint in a self-contained
  backend sub-package, demonstrating the flexibility Flask provides.

  Args:
    config_from_object (str, optional): A string representing the name of an
      object to import
    config_from_env  (str, optional): A string representing the name of the
      environment variable to pull the name of the object to import

  Note:
    While both arguments are optional, at least **one** is mandatory.
    Otherwise, where will we get our configs??
  """
    setup_log()
    log = logging.getLogger(__name__)

    app = Flask(__name__)

    if config_from_env:
        app.config.from_object(os.environ[config_from_env])
    # While the ENVIRONMENT configures first, the config object can be used to
    # merge and overwrite settings, providing additional flexibility
    if config_from_object:
        app.config.from_object(config_from_object)

    # We'll be mounting our API right on this endpoint here:
    app.register_blueprint(api_blueprint, url_prefix="/" + app.config["API_ENDPOINT"])
    app.register_blueprint(frontend_blueprint)

    # Register our JSON encoder too
    app.json_encoder = UltraJSONEncoder

    db.init_app(app)

    return app
Example #14
0
def create_app(config_object=ProdConfig):
    """An application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

  :param config_object: The configuration object to use.
  """
    app = Flask(__name__)
    app.config.from_object(config_object)
    app.json_encoder = JSONEncoder
    register_extensions(app)
    register_blueprints(app)
    register_errorhandlers(app)

    if app.config["ADMIN_ENABLED"]:
        register_admin_interface(app)

    return app
Example #15
0
def create_app():
    app = Flask(__name__)
    app.config.from_object("mblog_web.config")
    db_utils.init_db(app)

    if not app.debug:
        app.logger.setLevel(logging.DEBUG)
        del app.logger.handlers[:]
        handler = logging.StreamHandler()
        handler.setFormatter(logging.Formatter("[%(asctime)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S"))
        app.logger.addHandler(handler)

    app.secret_key = "verysecretkey"
    app.register_blueprint(main_views)
    app.json_encoder = json_utils.MyJsonEncoder

    print("Created app")
    return app
Example #16
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    mongo_db.init_app(app)
    assets.init_app(app)
    assets.register("js_all", javascript.js_all)

    from api import api as api_blueprint

    app.register_blueprint(api_blueprint)

    from public import public as public_blueprint

    app.register_blueprint(public_blueprint)

    app.json_encoder = MongoEngineJSONEncoder

    return app
Example #17
0
def create_app(testing=False):
    app = Flask(__name__)

    try:
        app.config.from_object("config")
    except:
        app.config.from_object("configdist")
    if testing:
        app.config["TESTING"] = True
        app.config["WTF_CSRF_ENABLED"] = False

    app.json_encoder = ExtensibleJSONEncoder
    app.secret_key = app.config["SECRET_KEY"]
    app.register_blueprint(user_bp)

    csrf = CsrfProtect()
    csrf.init_app(app)

    # Initialize login manager
    login_manager.init_app(app)

    # Assets bundles: js, jsx, css
    env = Environment(app)
    root = os.path.dirname(os.path.abspath(__file__)) + "/../"
    env.load_path = [root + "node_modules", root + "client/style"]
    env.register("css", css)

    @app.teardown_appcontext
    def shutdown_session(response):
        database.session.remove()

    @app.route("/")
    @app.route("/<path:path>")
    def index(path=None):
        """Main route for the single page app"""
        data = dict(user=anonymous_user_data, alerts=[])
        if current_user.is_authenticated():
            data["user"] = current_user
        return render_template("index.html", app_data=dumps(data))

    return app
Example #18
0
File: ello.py Project: hann2/terra
def create_app(debug=False):
    app = Flask(__name__)
    app.debug = debug
    app.secret_key = "this is a secret"
    app.json_encoder = Jsonifier

    app.file_root = os.path.abspath(os.path.dirname(__file__))

    # app.before_request(before_request)
    # app.after_request(after_request)
    # app.context_processor(context_processor)

    # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'

    # db.init_app(app)
    # with app.app_context():
    #     init_all()
    app.register_blueprint(homepage_app, url_prefix="/")
    app.register_blueprint(terrain_app, url_prefix="/terrain")

    return app
Example #19
0
def create_app(config_override=None):

    app = Flask(__name__)
    app.json_encoder = JSONEncoder
    app.config.from_object(config)
    app.config.from_object(config_override)

    FlaskJSON(app)

    _api_version_prefix = "/api/{}".format(app.config["API_VERSION"] or "v1.0").rstrip("/")
    api = Api(app, prefix=_api_version_prefix, catch_all_404s=True)

    db.init_app(app)

    redis_client.init_app(app)

    # TODO register more resources here ...

    api.add_resource(DateScheduleList, "/schedules/<string:date>/<string:plan_or_real>", endpoint="schedule.all.list")
    api.add_resource(
        ScheduleList, "/schedules/<string:date>/<string:line_no>/<string:plan_or_real>", endpoint="schedule.line.list"
    )
    api.add_resource(
        Schedule,
        "/schedules/<string:date>/<string:line_no>/<string:plan_or_real>/<string:trip>",
        endpoint="schedule.line.trip",
    )

    api.add_resource(LineConfigList, "/configs/lines", endpoint="configs.lines")
    api.add_resource(LineConfig, "/configs/lines/<string:line_no>", endpoint="configs.line")

    api.add_resource(
        SectionTripCounterResource,
        "/sections/<string:line_no>/<string:date>/<string:direction>",
        endpoint="sections.line",
    )

    init_app_index(app, api)

    return app
Example #20
0
def create_app(config=None, app_name=None, blueprints=None):
    """Create a Flask app."""

    if app_name is None:
        app_name = DefaultConfig.PROJECT
    if blueprints is None:
        blueprints = DEFAULT_BLUEPRINTS

    app = Flask(app_name, instance_relative_config=True)
    app.json_encoder = CustomJSONEncoder

    configure_app(app, config)
    configure_hook(app)
    configure_logging(app)
    configure_blueprints(app, blueprints)
    configure_extensions(app)
    configure_messenger(app)
    configure_template_filters(app)
    configure_error_handlers(app)
    app.logger.info("application started")

    return app
Example #21
0
class MyJSONEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime("%Y-%m-%dT%H:%M:%SZ")
        elif isinstance(obj, date):
            return obj.strftime("%Y-%m-%d")
        elif isinstance(obj, decimal.Decimal):
            return float(obj)
        elif isinstance(obj, (set, frozenset)):
            return list(obj)
        # Let the base class default method raise the TypeError
        return JSONEncoder.default(self, obj)


app.json_encoder = MyJSONEncoder


@app.template_filter("to_json")
def to_json(json_object):
    return Markup(json.dumps(json_object, sort_keys=True, indent=4, separators=(",", ": "), cls=MyJSONEncoder))


@app.template_filter("pp")
def pretty_print(json_object):
    # This filter is used only for debugging purposes
    from pygments import highlight
    from pygments.lexers import get_lexer_by_name
    from pygments.formatters import HtmlFormatter

    json_dump = to_json(json_object)
Example #22
0
import os
import sys
import logging

from flask import Flask
from flask_cors import CORS

from alerta.app.alert import DateEncoder

LOG_FORMAT = "%(asctime)s - %(name)s[%(process)d]: %(levelname)s - %(message)s [in %(pathname)s:%(lineno)d]"

app = Flask(__name__, static_url_path="")

app.json_encoder = DateEncoder

app.config.from_object("alerta.settings")
app.config.from_pyfile("/etc/alertad.conf", silent=True)
app.config.from_envvar("ALERTA_SVR_CONF_FILE", silent=True)

if "DEBUG" in os.environ:
    app.debug = True

if "BASE_URL" in os.environ:
    app.config["BASE_URL"] = os.environ["BASE_URL"]

if "SECRET_KEY" in os.environ:
    app.config["SECRET_KEY"] = os.environ["SECRET_KEY"]

if "AUTH_REQUIRED" in os.environ:
    app.config["AUTH_REQUIRED"] = True if os.environ["AUTH_REQUIRED"] == "True" else False
import os
from flask import Flask
from ooi_executive.shared import MyEncoder

__author__ = "petercable"

CONFIG_ENV_VAR = "MSNEXEC_CONFIG"

app = Flask(__name__)
app.json_encoder = MyEncoder
app.config.from_object("ooi_executive.default_config")
if CONFIG_ENV_VAR in os.environ:
    app.config.from_envvar(CONFIG_ENV_VAR)
Example #24
0
assets = Environment(app)
assets.directory = "eheritage/static/"
assets.url = "/static/"
assets.debug = True

js = Bundle("app.js", filters="jsmin", output="gen/packed.js")
assets.register("js_all", js)

# scss = Bundle('*.scss', filters='scss', output='gen/scss.css')
# css = Bundle('style.css', # scss,
#     filters='pyscss,cssmin', output='gen/style.css')

# assets.register('css_all', css)


app.json_encoder = IterableAwareEncoder


# Absolute filesystem path to the secret file which holds this project's
# SECRET_KEY. Will be auto-generated the first time this file is interpreted.
# SECRET_FILE = os.path.normpath(os.path.join(DJANGO_ROOT, 'deploy', 'SECRET'))
SECRET_FILE = "SECRET"

########## KEY CONFIGURATION
# Try to load the SECRET_KEY from our SECRET_FILE. If that fails, then generate
# a random SECRET_KEY and save it into our SECRET_FILE for future loading. If
# everything fails, then just raise an exception.
try:
    app.secret_key = open(SECRET_FILE).read().strip()
except IOError:
    try:
Example #25
0
from accounting.exceptions import AccountingException, TransactionNotFound
from accounting.decorators import jsonify_exceptions, cors


app = Flask("accounting")
app.config.from_pyfile("config.py")

app.ledger = Storage()


def init_ledger():
    app.ledger = Ledger(app)


# These will convert output from our internal classes to JSON and back
app.json_encoder = AccountingEncoder
app.json_decoder = AccountingDecoder


@app.route("/")
def index():
    """ Hello World! """
    return "Hello World!"


@app.route("/client")
def client():
    return render_template("client.html")


@app.route("/transaction", methods=["OPTIONS"])
Example #26
0
import datetime
import traceback
import copy
from oauth2client.client import flow_from_clientsecrets
import httplib2
from db import db
import re
from functools import wraps

app = Flask(__name__)
app.config.update(**flask_config.config)
if not app.debug:
    mail = Mail(app)

# change the default JSON encoder to handle datetime's properly
app.json_encoder = flask_config.ISO8601Encoder

with open("data/capacity_group.json") as json_data:
    FULL_CAP_DATA = json.load(json_data)["data"]

CU_EMAIL_REGEX = r"^(?P<uni>[a-z\d]+)@.*(columbia|barnard)\.edu$"
request_date_format = "%Y-%m-%d"

# create a pool of postgres connections
pg_pool = psycopg2.pool.SimpleConnectionPool(
    5,  # min connections
    20,  # max connections
    database=app.config["PG_DB"],
    user=app.config["PG_USER"],
    password=app.config["PG_PASSWORD"],
    host=app.config["PG_HOST"],
Example #27
0
# Create dummy secrey key so we can use sessions
app.config["SECRET_KEY"] = "123456790"
app.config["MONGODB_SETTINGS"] = {
    "db": "ai-aggregator",
    "host": os.environ.get("MONGODB_URL", "mongodb://localhost:27017/ai-aggregator"),
}
app.config.update(
    CELERY_BROKER_URL=os.environ.get("REDIS_URL", "redis://localhost:6379/0"),
    CELERY_RESULT_BACKEND=os.environ.get("REDIS_URL", "redis://localhost:6379/0"),
)

# Create models
db = MongoEngine()
db.init_app(app)
login_manager.init_app(app)
app.json_encoder = JSONEncoder


# Create user loader function
@login_manager.user_loader
def load_user(user_id):
    try:
        User.objects.get(id=user_id)
    except User.DoesNotExist:
        return AnonymousUserMixin()


# Create user model.
class User(db.Document):
    id = db.IntField()
    first_name = db.StringField()
Example #28
0
class CustomJSONEncoder(JSONEncoder):
    """This class adds support for lazy translation texts to Flask's
    JSON encoder. This is necessary when flashing translated texts."""

    def default(self, obj):
        from speaklater import is_lazy_string

        if is_lazy_string(obj):
            try:
                return unicode(obj)  # python 2
            except NameError:
                return str(obj)  # python 3
        return super(CustomJSONEncoder, self).default(obj)


app.json_encoder = CustomJSONEncoder


class Test(Resource):
    def get(selfself):
        return {"hello": "Smart Medical Search Engine"}


class Search(Resource):
    def get(self, query, page_num=1):
        page_size = int(POSTS_PER_PAGE)
        max_records = int(MAX_SEARCH_RESULTS)
        if max_records <= 0:
            max_records = 50
        max_pages = int((max_records - 1) / page_size) + 1
Example #29
0
from _15thnight.api import account_api, alert_api, category_api, need_api, response_api, service_api, user_api
from _15thnight.email import mailer
from _15thnight.forms import csrf_protect
from _15thnight.models import User
from _15thnight.util import ExtensibleJSONEncoder


app = Flask(__name__)

try:
    app.config.from_object("config")
except:
    app.config.from_object("configdist")

app.secret_key = app.config["SECRET_KEY"]
app.json_encoder = ExtensibleJSONEncoder

app.register_blueprint(alert_api, url_prefix="/api/v1/alert")
app.register_blueprint(account_api, url_prefix="/api/v1/account")
app.register_blueprint(category_api, url_prefix="/api/v1/category")
app.register_blueprint(need_api, url_prefix="/api/v1/need")
app.register_blueprint(response_api, url_prefix="/api/v1/response")
app.register_blueprint(service_api, url_prefix="/api/v1/service")
app.register_blueprint(user_api, url_prefix="/api/v1/user")

queue.init_app(app)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
Example #30
0
            try:
                iterable = iter(obj)
            except TypeError:
                pass
            else:
                return list(iterable)

        return JSONEncoder.default(self, obj)


# App Configuration
# http://stackoverflow.com/a/14826195
UPLOAD_FOLDER = "catalog/static/images"
ALLOWED_EXTENSIONS = ["png", "jpg"]
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
APP_STATIC = os.path.join(APP_ROOT, "static")
APP_IMAGES = os.path.join(APP_STATIC, "images")
APP_CLIENT_SECRET = os.path.join(APP_ROOT, "client_secret.json")
APP_DATABASE = "sqlite:///catalog/catalog.db"


app.config["APP_IMAGES"] = APP_IMAGES
app.config["APP_STATIC"] = APP_STATIC
app.config["APP_ROOT"] = APP_ROOT
app.config["APP_DATABASE"] = APP_DATABASE
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
app.config["ALLOWED_EXTENSIONS"] = ALLOWED_EXTENSIONS
app.config["APP_CLIENT_SECRET"] = APP_CLIENT_SECRET
app.json_encoder = ModelsEncoder