Example #1
1
def create_app(config_name):
    app = Flask(config_name)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    app_admin.init_app(app)
    babel.init_app(app)
    celery.init_app(app)
    bootstrap.init_app(app)

    db.init_app(app)
    with app.app_context():
        print current_app.name
        db.create_all()
    login_manager.init_app(app)

    app_admin.base_template = "layout.html"

    from main import main as main_blueprint
    from admin import admin as admin_blueprint
    from auth import auth as auth_blueprint

    app.register_blueprint(main_blueprint)
    app.register_blueprint(auth_blueprint, url_prefix="/auth")

    import os.path

    _dir = os.path.dirname(os.path.abspath(__file__))
    app.template_folder = os.path.join(_dir, "templates")
    app.static_folder = os.path.join(_dir, "static")

    return app
Example #2
1
 def test_renderer(self, **kwargs):
     app = Flask(__name__)
     app.template_folder = os.path.join(self.root, "templates")
     app.config.update(MAKO_CACHE_DIR=os.path.join(self.root, "cache"), MAKO_CACHE_SIZE=10)
     app.config.update(kwargs)
     with app.test_request_context():
         yield app, MakoTemplates(app)
Example #3
1
def bootstrap_server():
    app = Flask("camrail")
    config = Config()
    app.config.from_object(config)
    app.template_folder = config.template_folder
    mako_templates = MakoTemplates(app)
    globals()["app"] = app
    globals()["mako_templates"] = mako_templates
Example #4
1
def create_app(config_name):
    app = Flask(config_name)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    Markdown(app)

    _dir = os.path.dirname(os.path.abspath(__file__))
    app.template_folder = os.path.join(_dir, "templates")
    app.static_folder = os.path.join(_dir, "static")

    return app
Example #5
1
def make_app(config="config.py"):

    app = Flask(__name__)

    # ----------------------------
    # helpers
    app.jinja_env.globals["icon"] = lambda x: "<i class='glyphicon glyphicon-%s'></i>" % x

    # todo: app.jinja_env.globals['_'] = _
    app.template_folder = "app"

    app.config.from_pyfile(config)
    return app
Example #6
1
def create_app(config=None, app_name=None):
    if app_name is None:
        app_name = DEFAULT_APP_NAME

    app = Flask(app_name)

    app.template_folder = os.path.join(os.path.dirname(__file__), "_templates")
    app.static_folder = os.path.join(os.path.dirname(__file__), "_static")

    configure_app(app, config)
    configure_extensions(app)
    configure_template_filters(app)
    configure_blue_print(app, DEFAULT_BLUEPRINTS)

    return app
Example #7
0
def create_app(environment="DEVELOPMENT"):
    """worldofsfx application factory.

    This function defines a re-usable pattern for instantiating and creating
    application objects.

    :param str environment: Specify the name of the configuration object used
                            to build this application object

    Usage::
        from worldofsfx import create_app
        from unittest import TestCase

        class MyTest(TestCase):

            def setUp(self):
                self.app = create_app(environment="TESTING")

    :returns: flask application
    :rtype: :obj:`flask.Flask`
    """
    if not environment:
        env_name = "DEVELOPMENT"
    else:
        env_name = environment.upper()
    app = Flask(__name__)
    env = Environments(app, default_env=env_name)
    env.from_object("worldofsfx.config")
    wos_privates = os.getenv("WOS_PRIVATES")
    if wos_privates:
        env.from_object(wos_privates)

    app.template_folder = app.config.get("TEMPLATE_FOLDER", "templates")

    app.register_blueprint(wos)
    app.register_blueprint(events)
    app.register_blueprint(buzz)
    app.register_blueprint(beatport)

    db.init_app(app)

    return app
Example #8
0
    def create(self):
        flask = Flask(__name__)
        flask.config.from_pyfile(os.path.join(flask.root_path, self.root.config.get("web_conf")))
        for error in range(400, 420) + range(500, 506):
            flask.error_handler_spec[None][error] = self.generic_error_handler

        if flask.config["TEMPLATE_DIR"]:
            flask.template_folder = flask.config["TEMPLATE_DIR"]

        if flask.config["AUTOINDEX_ITEMS"]:
            self.register_auto_index_items(flask)

        if flask.config["AUTOINDEX_LOGS"]:
            self.register_auto_index_logs(flask)

        Bootstrap(flask)

        @flask.route("/")
        def index():
            return render_template("index.html", page_title="Home", jobs=self.get_jobs())

        @flask.route("/spiders")
        def projects():
            project_spiders = []
            scrapyd_error = None
            for project in self.root.scheduler.list_projects():
                if project is ".DS_Store":
                    pass
                try:
                    project_spiders.append(
                        {"name": project, "spiders": get_spider_list(project, runner=self.root.runner)}
                    )
                except RuntimeError, e:
                    scrapyd_error = "%s: %s" % (project, e.message)

            return render_template(
                "spiders.html", page_title="Spiders", project_spiders=project_spiders, error=scrapyd_error
            )
Example #9
0
def http_worker(lock):
    """The Flask application"""
    app = Flask("cloud_xfd")

    # noinspection PyUnusedLocal
    @app.route("/")
    def index():
        with lock:
            url = get_url()
        return render_template("index.html", url=url)

    # noinspection PyUnusedLocal
    @app.route("/update", methods=["POST"])
    def update():
        address = request.form["url"]
        with lock:
            put_url(address)

        flash("The URL has been successfully updated")
        return redirect(url_for("index"))

    app.template_folder = "/home/pi/extremefeedbacklamp/templates"
    app.secret_key = "notreallyasecret"
    app.run("0.0.0.0")
import logging
import tempfile

from flask import Flask
from flask.ext import restful
from flask.ext.sqlalchemy import SQLAlchemy

from config import config_by_name

# Specify Environment via "export DEMO_ENV=<environment_name>"
env = os.getenv("DEMO_ENV") or "dev"

app = Flask(__name__)
app.config.from_object(config_by_name[env])
app.static_folder = app.config.get("STATIC_FOLDER", "")
app.template_folder = app.config.get("TEMPLATES_FOLDER", "")

# Change tmp dir when uploading
# comment this if you want the default one /tmp in linux
tempfile.tempdir = app.config.get("TMP_DIR", "")

# global SQLAlchemy instance
db = SQLAlchemy(app)

# Config for Logging
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s - %(filename)s %(funcName)s: %(message)s"))
stdout_handler.setLevel(logging.DEBUG)
app.logger.addHandler(stdout_handler)
app.logger.setLevel(logging.DEBUG)
Example #11
0
    def init(cls, flask_or_import_name, project=None, directory=None, config=None, compress_html=True):
        """
        Allow to register all subclasses of WebPortfolio at once

        If a class doesn't have a route base, it will create a dasherize version
        of the class name.

        So we call it once initiating
        :param flask_or_import_name: Flask instance or import name -> __name__
        :param project: name of the project. If the directory and config is empty, it will guess them from here
        :param directory: The directory containing your project's Views, Templates and Static
        :param config: string of config object. ie: "app.config.Dev"
        :param compress_html: bool - If true it will use the plugin "jinja2htmlcompress"
                to remove white spaces off the html resul
        """

        if isinstance(flask_or_import_name, Flask):
            app = flask_or_import_name
        else:
            app = Flask(flask_or_import_name)

        app.wsgi_app = ProxyFix(app.wsgi_app)

        app.url_map.converters["regex"] = RegexConverter

        if not directory:
            directory = "application/%s" % project if project else "."

        if not config:
            config = "application.config.%s" % get_env()

        app.config.from_object(config)

        cls._setup_logger(app)

        if directory:
            app.template_folder = directory + "/templates"
            app.static_folder = directory + "/static"

        cls._add_asset_bundle(app.static_folder)

        # Extensions to remove extra white spaces in html
        if compress_html:
            app.jinja_env.add_extension("webportfolio.jinja2htmlcompress.HTMLCompress")

        cls._app = app

        # Flask Assets
        cls.assets = Environment(cls._app)

        # Register templates
        if cls._template_paths:
            loader = [cls._app.jinja_loader] + list(cls._template_paths)
            cls._app.jinja_loader = jinja2.ChoiceLoader(loader)

        # Register static
        if cls._static_paths:
            loader = [cls._app.static_folder] + list(cls._static_paths)
            cls.assets.load_path = loader

        # init_app
        for _app in cls._init_apps:
            _app(cls._app)

        # Register all views
        for subcls in cls.__subclasses__():
            route_base = subcls.route_base
            if not route_base:
                route_base = utils.dasherize(utils.underscore(subcls.__name__))
            subcls.register(cls._app, route_base=route_base)

        # Load all bundles
        [cls.assets.from_yaml(a) for a in cls._asset_bundles]

        @cls._app.after_request
        def _after_request_cleanup(response):
            cls._global["PAGE_META"] = cls._default_page_meta
            cls._global["PAGE_META"]["site_name"] = cls._app.config.get("APPLICATION_NAME", "")
            return response

        return cls._app
Example #12
0
from flask import render_template
from flask import request

import json
import re
from time import strftime
from datetime import date, timedelta

from pymongo import MongoClient

import urllib2

import elasticsearch

app = Flask(__name__, static_folder="web/static", static_url_path="")
app.template_folder = "web"
app.debug = True

dbclient = MongoClient("mongodb://localhost:27017/")
db = dbclient["comidadb"]
collection = db["comida"]


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


@app.route("/stats")
def stats():
    return render_template("stats.html")
Example #13
0
from orbit.framing import TEXT
from flask import Flask, render_template, request, session
from orbit.server import WebSocketResource, WSGISiteResource
from orbit.transaction import Transaction, State, TransactionManager
from twisted.web.static import File
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource
from twisted.python import log
from twisted.web.resource import Resource
import cgi, urlparse, os, treq, sys

app = Flask(__name__)
app.root_path = os.path.join(os.path.dirname(__file__), "..")
app.static_folder = os.path.join(app.root_path, "static")
app.template_folder = os.path.join(app.root_path, "templates")
app.secret_key = "example-secret-key"

imgur_folder = os.path.join(app.static_folder, "imgur")

# The state is what holds all of the important data of our Transaction.
# In this case, the imgur filename to download.
class ImgurDownloadState(State):
    def __init__(self, imgur_filename):
        self.imgur_filename = imgur_filename.encode("utf8")  # for treq

    @inlineCallbacks
    def onNewConnection(self, ws):
        ws.opcode = TEXT
        local_file = os.path.join(imgur_folder, self.imgur_filename)
        # If we don't already have the image downloaded, we download it in a non-blocking manner with treq
Example #14
0
app.config["HTTP_BASIC_AUTH_REALM"] = "%s %s" % (prog, app.version)

# Define logging here to make it available in views
from synchrony.controllers import utils

log = utils.Log(prog, log_stdout=True)

from synchrony import streams
from synchrony.models import *
from synchrony.views import base
from synchrony.views.maps import maps
from synchrony.controllers.usergroups import init_user_groups

app.public = True
app.config.from_object("synchrony.config")
app.template_folder = os.path.join(os.path.dirname(__file__), "templates") + os.path.sep

app.default_network = "alpha"

# Keep a record of how much data we've served and received
app.bytes_sent = 0
app.bytes_received = 0


@app.before_request
def fence_internet_hosts():
    """
    Relegate hosts connecting over the internet to the /v1/peers endpoint.
    """
    if not request.path.startswith("/v1/peers") and not request.remote_addr[:3] in ["127", "10.", "192"]:
        log("%s tried to retrieve %s" % (request.remote_addr, request.path), "warning")
Example #15
0
# encoding: utf-8

import os
import sys


sys.path.insert(0, os.path.abspath("%s/../../" % os.path.abspath(os.path.dirname(__file__))))


from flask import Flask

from shark.app.routes import routes
from shark.app import config


app = Flask(__name__)

app.debug = True
app.template_folder = "%s/../templates" % app.root_path
app.static_folder = "%s/../static" % app.root_path
app.config.from_pyfile("config.py")

for url, view in routes:
    app.add_url_rule(url, view_func=view)

if __name__ == "__main__":
    app.run()
Example #16
0
import datetime
import os
import random
import sys

from flask import Flask, render_template, request, abort

import utils

app = Flask(__name__)
app.template_folder = os.path.join(os.path.dirname(sys.argv[0]), "templates")

app.static_folder = os.path.join(os.path.dirname(sys.argv[0]), "static")


@app.route("/compliments")
def compliment():
    """Compliments as a service (for my magic mirror)"""
    random_compliments = [
        "You look lovely today!",
        "Hey, good lookin'!",
        "Your smile is contagious.",
        "You should be proud of yourself.",
        "On a scale from 1 to 10, you're an 11.",
        "You're wonderful.",
        "Your hair looks stunning.",
        "You're gorgeous",
    ]
    return str(random.choice(random_compliments))

Example #17
0
#!/usr/bin/env python
# -*- coding: utf8 -*-

from flask import Flask
from flask import abort, render_template, request, send_from_directory
from flask.ext.assets import Environment
from unipath import Path

app = Flask(__name__)
app.template_folder = Path(Path(__file__).parent, "templates/default")

assets = Environment(app)
assets.register("css", Path(app.template_folder, "static/style.css"), output="inupypi.css", filters="cssmin")

import inupypi.views
Example #18
0
from flask import Flask
from promua_test_app.views import *
from flask_wtf import CsrfProtect

import __config as config

app = Flask(__name__)
# configure app
app.config.from_object(config)
# setup extensions
csrf_protect = CsrfProtect()
# init extensions
csrf_protect.init_app(app)
login_manager.init_app(app)
# setup static and templates
app.template_folder = "promua_test_app/templates"
app.static_folder = "promua_test_app/static"
# register handlers
app.before_request(before_request)
app.teardown_appcontext(teardown_app_context)
# register views
IndexView.register(app)
UserView.register(app)

if __name__ == "__main__":
    app.run()
Example #19
0
File: api.py Project: mazurekm/miob
    BrowseControllerList,
    GenoController,
    GenoControllerList,
    BrowseControllerPage,
    DownloadPool,
    DownloadGeno,
    GenoControllerListPage,
    SubmitController,
    BrowseController,
    BrowseControllerListPage,
]

app = Flask(__name__, static_folder=os.path.join("views", "static"))
app.secret_key = "super secret key"
app.config["SESSION_TYPE"] = "filesystem"
app.template_folder = "views"

api = Api(app)

for el in controller_list:

    if el.id is None:
        if el.page is not None:
            api.add_resource(el, "/{0}/page/<{1}>".format(el.endpoint, el.page))
        else:
            api.add_resource(el, "/{0}/".format(el.endpoint))

    else:
        if el.page is not None:
            api.add_resource(el, "/{0}/<{1}>/page/<{2}>".format(el.endpoint, el.id, el.page))
        else:
Example #20
0
@app.route("/GroupTwo/")
def group_two():
    return "Welcome group two, develop here"


@app.route("/GroupThree/")
def group_three():
    return "Welcome group three, develop here"


@app.route("/GroupFour/")
def group_four():
    return "Welcome group four, develop here"


@app.route("/GroupFive/")
def group_five():
    return "Welcome group five, develop here"


if __name__ == "__main__":
    """Start the server
    host  -- (default '127.0.0.1')
    port  -- (default 5000)
    debug -- set to True to reload every time a change is detected: very useful! (default False)

    """
    app.run(host="localhost", port=5000, debug=True)
    app.template_folder = templates
    app.add_url_rule("/favicon.ico/", redirect_to=url_for("static", filename="favicon.ico"))
Example #21
0
        return Response(bson2json(router, sort_keys=True, indent=4), mimetype="application/json")
    else:
        return render_template("router.html", router=router, tileurls=tileurls)


@app.route("/statistics")
def global_statistics():
    hoods = stattools.hoods()
    return render_template(
        "statistics.html",
        stats=db.stats.find({}, {"_id": 0}),
        clients=stattools.total_clients(),
        router_status=stattools.router_status(),
        router_models=stattools.router_models(),
        router_firmwares=stattools.router_firmwares(),
        hoods=hoods,
        hoods_sum=stattools.hoods_sum(),
        newest_routers=db.routers.find({}, {"hostname": 1, "hood": 1, "created": 1})
        .sort("created", pymongo.DESCENDING)
        .limit(len(hoods) + 1),
    )


app.secret_key = os.urandom(24)

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)
else:
    app.template_folder = "/usr/share/ffmap/templates"
    app.static_folder = "/usr/share/ffmap/static"
    # app.debug = True
Example #22
0
File: app.py Project: nuty/xiaer
import sys
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from config import Configuration

app = Flask("xiaer")
app.config.from_object(Configuration)
app.template_folder = Configuration.APP_ROOT + "/templates"
app.static_folder = Configuration.APP_ROOT + "/static"

app.debug = True

app.config["SECRET_KEY"] = Configuration.SECRET_KEY

db = SQLAlchemy(app)


# def init_db(db):
#     """Add a save() function to db.Model"""
#     def save(model):
#         db.session.add(model)
#         db.session.commit()
#         db.Model.save = save


# db = SQLAlchemy()
# init_db(db)


def init_db():
    from collection import models
Example #23
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json

from os.path import dirname
from os.path import join
from flask import Flask

app = Flask(__name__)
app.template_folder = join(dirname(__file__), "templates")
app.static_folder = join(dirname(__file__), "static")


class UserConfig(dict):
    """ loads the json configuration file """

    def _string_decode_hook(self, data):
        rv = {}
        for key, value in data.iteritems():
            if isinstance(key, unicode):
                key = key.encode("utf-8")
            if isinstance(value, unicode):
                value = value.encode("utf-8")
            rv[key] = value
        return rv

    def __init__(self):
        dict.__init__(self)
        configfile = join(dirname(dirname(__file__)), "config.json")
        self.update(json.load(open(configfile), object_hook=self._string_decode_hook))
Example #24
0
# -*- coding: utf-8 -*-
from flask import Flask
from config.appconfig import Config
from flask import session
import hashlib
import json


app = Flask(__name__)
app.config.from_object(Config)
app.template_folder = app.config["TEMPLATE_FOLDER"]
app.static_folder = app.config["STATIC_PATH"]
__all__ = ["index", "admin"]


def is_login():
    if not session.get("uid") or not session.get("logged"):
        return False
    else:
        uid = session.get("uid")
        logged = session.get("logged")
        if uid == hashlib.md5(app.config["ADMIN_USER"]).hexdigest() and logged == 1:
            return True
        else:
            return False


def do_signin(username, password):
    if username != "" and username == app.config["ADMIN_USER"]:
        if password != "" and password == app.config["ADMIN_PWD"]:
            return json.dumps({"status": True, "msg": "登录成功"})
Example #25
0
import os
import xbmcaddon
from flask import Flask

__addonpath__ = xbmcaddon.Addon(id="script.webui").getAddonInfo("path")
app = Flask(__name__)

app.root_path = __addonpath__
app.static_path = "/static"
app.static_folder = os.path.join(__addonpath__, "resources", "static")
app.template_folder = os.path.join(__addonpath__, "resources", "templates")
app.add_url_rule(app.static_path + "/<path:filename>", endpoint="static", view_func=app.send_static_file)

from jinja2 import FileSystemLoader

app.jinja_loader = FileSystemLoader(os.path.join(__addonpath__, "resources", "templates"))
Example #26
0
"""

import os

from flask import Flask, jsonify, abort, make_response, render_template
from flask_httpauth import HTTPBasicAuth

app = Flask(__name__, static_url_path="")  # pylint: disable=invalid-name
app.config.from_object("config")
app.debug = True
auth = HTTPBasicAuth()  # pylint: disable=invalid-name

# This is the path to the upload directory
app.config["UPLOAD_FOLDER"] = "uploads"
# These are the extension that we are accepting to be uploaded
app.config["ALLOWED_EXTENSIONS"] = set(["txt", "pdf", "png", "jpg", "jpeg", "gif", "py"])
# create upload folder if not exist
if not os.path.exists(app.config["UPLOAD_FOLDER"]):
    os.makedirs(app.config["UPLOAD_FOLDER"])

# redefine jinja start/end string to avoid conflict with AngularJS
app.jinja_env.variable_start_string = "{[{ "
app.jinja_env.variable_end_string = " }]}"

# use different static/templates folder with different mode
if not app.debug:
    app.template_folder = "build/templates"
    app.static_folder = "build/static"
else:
    app.template_folder = "src/templates"
    app.static_folder = "src/static"
Example #27
0
File: run.py Project: Grub0/hflossk
"""
import os

from flask import Flask
from flask.ext.mako import MakoTemplates, render_template

import yaml
import feedparser
from datetime import datetime, timedelta
import time
import hashlib
import urllib2
import glob

app = Flask(__name__)
app.template_folder = "templates"
mako = MakoTemplates(app)


def gravatar(email):
    """ I wish I could use libravatar here, but honestly, the students
    will be better off using gravatar at this point (due to github
    integration :/) """

    slug = hashlib.md5(email.lower()).hexdigest()
    return "https://secure.gravatar.com/avatar/" + slug


yaml_dir = "scripts/people/"

Example #28
0
# gevent.monkey.patch_all()

import inspect
import os
import sys
from flask import Flask, Blueprint
from flask_sqlalchemy import SQLAlchemy
from comsvc.lib import models
from comsvc.lib import queue
from comsvc.lib import tasks

project_name = "comsvc"

path = os.path.dirname(__file__)
app = Flask(__name__)
app.template_folder = path + "/templates"
app.static_folder = path + "/static"
app.root_path = path
config = __import__("config")
app.config.from_object("config")
app.db = SQLAlchemy(app)
models.declare_models(app.db)
celery = app.celery = queue.init_app(app)
tasks.define_tasks(app.celery)

for blueprint_file in app.config["ENABLED_BLUEPRINTS"]:
    module_name = project_name + ".blueprints." + blueprint_file
    __import__(module_name)
    module = sys.modules[module_name]
    for name, obj in inspect.getmembers(module):
        if isinstance(obj, Blueprint):
Example #29
0
    def requires_auth(self, f):
        @wraps(f)
        def decorated(*args, **kwargs):
            request = flask.request
            if not self.isAuthenticated(request):
                return self.challenge()

            return f(*args, **kwargs)

        return decorated


app = Flask(__name__)
app.config["SECRET_KEY"] = startup_dict["SECRET_KEY"]
app.config["DEBUG"] = startup_dict["DEBUG"]
app.template_folder = None
app.static_folder = "static"

authDB = FlaskRealmDigestDB(startup_dict["RealmDigestDB"])
temp = json.loads(startup_dict["users"])
for i in temp:
    authDB.add_user(i["user"], i["password"])


class FlaskRealmDigestDB(authdigest.RealmDigestDB):
    def requires_auth(self, f):
        @wraps(f)
        def decorated(*args, **kwargs):
            request = flask.request
            if not self.isAuthenticated(request):
                return self.challenge()
Example #30
0
# from sqlite3 import dbapi2 as sqlite3

_app = Flask(__name__)
# _app.config.from_object(s)

# Load override configuration values into flask config
#
override = Path("config.py")
root = Path(_app.root_path)
if not override.exists():
    raise ValueError("No config file found")

_app.config.from_pyfile(str(override.abspath()))

_app.template_folder = _app.config["TEMPLATE_DIR"]
_app.static_folder = _app.config["STATIC_DIR"]


def connect_db(db_name):
    # return sqlite3.connect(_app.config['DATABASE'])
    couch = couchdb.Server(_app.config["DB_HOST"])
    couch.resource.credentials = _app.config["DB_AUTH"]
    return couch[db_name]


db = connect_db(_app.config["DB_NAME"])
settings = blogsettings.loadSettings(db)
for k, v in settings.iteritems():
    if k[0] == "_":
        continue