Example #1
1
def create_app():
    """
    Creates the Flask app instance

    @return: Flask app
    @rtype: flask.Flask
    """
    from flask import Flask

    app = Flask(__name__)
    # set debug to true so we see error dumps in the browser
    app.debug = settings.APP_DEBUG
    app.secret_key = settings.APP_SECRET_KEY
    app.config["SQLALCHEMY_DATABASE_URI"] = settings.DATABASE[env]["uri"]
    app.config["BASE_URL"] = settings.BASE_URL
    app.config["SQLALCHEMY_ECHO"] = settings.DATABASE[env]["echo"]
    app.config["RECAPTCHA_PUBLIC_KEY"] = settings.RECAPTCHA_PUBLIC_KEY
    app.config["RECAPTCHA_PRIVATE_KEY"] = settings.RECAPTCHA_PRIVATE_KEY
    app.config["SERVER_NAME"] = settings.BASE_URL

    app.jinja_options["extensions"].append("jinja2.ext.loopcontrols")
    my_loader = jinja2.ChoiceLoader(
        [app.jinja_loader, jinja2.FileSystemLoader([os.path.dirname(os.path.abspath(__file__)) + "/static"])]
    )
    app.jinja_loader = my_loader

    return app
Example #2
1
def app_error_handler(request):
    """Flask app error handler fixture."""
    app = Flask("myapp")

    # Creation of a fake theme error template file.
    temp_dir = tempfile.mkdtemp()
    invenio_theme_dir = os.path.join(temp_dir, "invenio_theme")
    os.mkdir(invenio_theme_dir)
    fake_file = open(os.path.join(invenio_theme_dir, "fake.html"), "w+")
    fake_file.write("{# -*- coding: utf-8 -*- -#}" "<!DOCTYPE html>{% block message %}" "{% endblock message %}")
    fake_file.close()

    # Adding the temporal path to jinja engine.
    app.jinja_loader = jinja2.ChoiceLoader([jinja2.FileSystemLoader(temp_dir), app.jinja_loader])

    # Setting by default fake.html as a THEME_ERROR_TEMPLATE
    app.config["THEME_ERROR_TEMPLATE"] = "invenio_theme/fake.html"

    # Tear down method to clean the temp directory.
    def tear_down():
        shutil.rmtree(temp_dir)

    request.addfinalizer(tear_down)

    app.testing = True
    Babel(app)
    InvenioTheme(app)
    return app
Example #3
1
def create_app(package_name="ticketting_system"):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the korath platform.

    :param package_name: application package name
    :param package_path: application package path
    :param config_name: can have one of [production, development, testing]
    """
    global app, admin
    app = Flask(package_name, instance_relative_config=True)

    config_name = os.environ.get("ticketting_system_CONFIG_NAME", "Production")

    app.config.from_object("configurations.%s" % config_name.title())

    app.jinja_loader = jinja2.ChoiceLoader([app.jinja_loader, jinja2.FileSystemLoader("ticketting_system/templates/")])

    db.init_app(app)
    admin = Admin(app, "Ticketing System Admin Panel")

    from . import views
    from views import api_blueprint

    app.register_blueprint(api_blueprint)

    from . import models

    # for admin panel
    from . import admin_panel

    return app
Example #4
1
def app():
    app = Flask(__name__)
    app.jinja_loader = FunctionLoader(load_template)

    Obscurity(app)

    return app
Example #5
1
def init_flaskadmin(urlprefix="", secret="fKY7kJ2xSrbPC5yieEjV", override_admin=None, override_flaskadminapp=None):
    global flaskadminapp, admin

    if not override_flaskadminapp:
        flaskadminapp = Flask(__name__)
        flaskadminapp.debug = True
        flaskadminapp.secret_key = secret
        flaskadminapp.config.update(dict(PREFERRED_URL_SCHEME="https"))
    else:
        flaskadminapp = override_flaskadminapp

        # lets add our template directory
        my_loader = jinja2.ChoiceLoader(
            [flaskadminapp.jinja_loader, jinja2.FileSystemLoader(resole_uri("gengine:templates"))]
        )
        flaskadminapp.jinja_loader = my_loader

    flaskadminapp.add_url_rule(
        "/static_gengine/<path:filename>",
        endpoint="static_gengine",
        view_func=get_static_view("gengine:flask_static", flaskadminapp),
    )

    @flaskadminapp.context_processor
    def inject_version():
        return {"gamification_engine_version": pkg_resources.get_distribution("gamification-engine").version}

    if not override_admin:
        admin = Admin(
            flaskadminapp,
            name="Gamification Engine - Admin Control Panel",
            base_template="admin_layout.html",
            url=urlprefix + "/admin",
        )
    else:
        admin = override_admin

    admin.add_view(ModelViewAchievement(DBSession, category="Rules"))
    admin.add_view(ModelViewGoal(DBSession, category="Rules"))
    admin.add_view(
        ModelView(AchievementAchievementProperty, DBSession, category="Rules", name="Achievement Property Values")
    )
    admin.add_view(ModelView(AchievementReward, DBSession, category="Rules", name="Achievement Reward Values"))
    admin.add_view(ModelView(GoalGoalProperty, DBSession, category="Rules", name="Goal Property Values"))
    admin.add_view(ModelViewTranslationVariable(DBSession, category="Rules"))
    admin.add_view(ModelView(Translation, DBSession, category="Rules"))

    admin.add_view(ModelViewAchievementCategory(DBSession, category="Settings"))
    admin.add_view(ModelViewVariable(DBSession, category="Settings"))
    admin.add_view(ModelViewAchievementProperty(DBSession, category="Settings", name="Achievement Property Types"))
    admin.add_view(ModelViewReward(DBSession, category="Settings", name="Achievement Reward Types"))
    admin.add_view(ModelViewGoalProperty(DBSession, category="Settings", name="Goal Property Types"))
    admin.add_view(ModelView(Language, DBSession, category="Settings"))
    admin.add_view(MaintenanceView(name="Maintenance", category="Settings", url="maintenance"))

    admin.add_view(ModelViewValue(DBSession, category="Debug"))
    admin.add_view(ModelViewGoalEvaluationCache(DBSession, category="Debug"))
    admin.add_view(ModelViewUser(DBSession, category="Debug"))
    admin.add_view(ModelView(AchievementUser, DBSession, category="Debug"))
Example #6
1
    def _create_app(self):
        app = Flask(__name__)
        app.debug = self.conf.FLASK_DEBUG

        if not self.conf.STATIC_RESOURCE:
            raise Exception("STATIC_RESOURCE setting not configured.")
        if not self.conf.TEMPLATE_RESOURCE:
            raise Exception("TEMPLATE_RESOURCE setting not configured.")

        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {"/": self.conf.STATIC_RESOURCE})
        if type(self.conf.TEMPLATE_RESOURCE) == tuple:  # package, not filepath
            app.jinja_loader = PackageLoader(*self.conf.TEMPLATE_RESOURCE)
        else:
            app.jinja_loader = FileSystemLoader(self.conf.TEMPLATE_RESOURCE)
        if self.conf.ALLOW_DEFERREDS:
            self._enable_deferreds(app)
        return app
Example #7
1
def create_app():
    """Create the Flask app."""

    app = Flask("modelconvert", static_folder=None)

    app.config.from_object("modelconvert.settings")
    app.config.from_envvar("MODELCONVERT_SETTINGS", silent=True)

    # configure custom static path for serving files during
    # development
    app.static_folder = app.config["STATIC_PATH"]
    app.add_url_rule("/static/<path:filename>", endpoint="static", view_func=app.send_static_file)

    # custom template path, fall back to default
    jinja_loader = jinja2.ChoiceLoader([jinja2.FileSystemLoader(app.config["TEMPLATE_PATH"]), app.jinja_loader])
    app.jinja_loader = jinja_loader

    configure_logging(app)

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

    celery.add_defaults(app.config)

    # configure error handlers
    @app.errorhandler(403)
    def forbidden_page(error):
        return render_template("403.html"), 403

    # FIXME adapt this for json requests http://flask.pocoo.org/snippets/83/
    @app.errorhandler(404)
    def page_not_found(error):
        if request.headers["Content-Type"] == "application/json":
            message = {"status": 404, "detail": "Not Found: " + request.url}
            resp = jsonify(message)
            resp.status_code = 404
            return resp
        else:
            return render_template("404.html"), 404

    @app.errorhandler(500)
    def server_error_page(error):
        return render_template("500.html"), 500

    if app.config["DEBUG"]:
        from werkzeug.wsgi import SharedDataMiddleware

        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {"/preview": app.config["DOWNLOAD_PATH"]})

    return app
Example #8
0
 def make_app(self):
     app = Flask("clay", static_folder=None, template_folder=self.source_dir)
     app.jinja_loader = self.get_jinja_loader()
     app.jinja_options = self.get_jinja_options()
     app.debug = True
     self.set_template_context_processors(app)
     self.set_urls(app)
     return app
Example #9
0
def create_app():
    application = Flask(__name__, static_folder=EG_STATIC_FOLDER)
    my_loader = jinja2.ChoiceLoader([application.jinja_loader, jinja2.FileSystemLoader(EG_SYSTEM_TEMPLATE_FOLDER)])

    application.jinja_loader = my_loader
    application.secret_key = APP_SECRET_KEY
    application.config.from_object("config")

    # Initialize Babel
    Babel(application)
    application.config["BABEL_DEFAULT_LOCALE"] = BABEL_DEFAULT_LOCALE

    return application
Example #10
0
def create_app(object_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. appname.settings.ProdConfig
    """
    app = Flask(__name__)

    app.config.from_object(object_name)
    if os.environ.get("KAKU_SETTINGS", None) is not None:
        app.config.from_envvar("KAKU_SETTINGS")

    if not app.debug:
        handler = logging.handlers.RotatingFileHandler(app.config["LOG_FILE"], maxBytes=100000000, backupCount=9)
        formatter = logging.Formatter("%(asctime)s %(levelname)s %(pathname)s:%(lineno)d -- %(message)s")
        handler.setFormatter(formatter)
        handler.setLevel(logging.DEBUG)

        app.logger.addHandler(handler)
        app.logger.setLevel(logging.DEBUG)

        wzlog = logging.getLogger("werkzeug")
        wzlog.setLevel(logging.DEBUG)
        wzlog.addHandler(handler)

    if app.config["SITE_TEMPLATES"] is not None:
        app.jinja_loader = jinja2.FileSystemLoader(app.config["SITE_TEMPLATES"])

    # initialize the cache
    cache.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    app.dbRedis = FlaskRedis.from_custom_provider(StrictRedis, app)

    # register our blueprints
    app.register_blueprint(main)
    app.register_blueprint(auth)

    app.logger.info("Flask app [%s] created" % __name__)

    return app
Example #11
0
    def app(self):
        """ derive flask app based on the combination of command-line
            options and the contents of the .ini files
        """

        ## set flask specific things that are non-optional
        error = (
            lambda k: 'Fatal: You need to specify a "flask" section '
            + 'with an entry like  "'
            + k
            + '=..." in your .ini file'
        )
        try:
            app_name = self["flask.app"]
        except KeyError:
            raise SystemExit(error("app"))
        try:
            secret_key = self["flask.secret_key"]
        except KeyError:
            raise SystemExit(error("secret_key"))
        app = Flask(app_name)
        app.secret_key = secret_key

        ## set flask specific things that are optional
        if "flask.template_path" in self:
            app.jinja_loader = FileSystemLoader(self["template_path"])
        if "flask.before_request" in self:
            before_request = self["flask.before_request"]
            before_request = namedAny(before_request)
            app.before_request(before_request)
        if "flask.after_request" in self:
            after_request = self["flask.after_request"]
            after_request = namedAny(after_request)
            app.after_request(after_request)

        ## setup views
        try:
            view_holder = self["corkscrew.views"]
        except KeyError:
            error = 'Fatal: could not "view=<dotpath>" entry in your .ini file'
            raise SystemExit(error)
        else:
            view_list = namedAny(view_holder)
            [v(app=app, settings=self) for v in view_list]

            return app
Example #12
0
def create_app():
    """Create the Flask app."""

    app = Flask("modelconvert", static_folder=None)

    app.config.from_object("modelconvert.settings")
    app.config.from_envvar("MODELCONVERT_SETTINGS", silent=True)

    # configure custom static path for serving files during
    # development
    app.static_folder = app.config["STATIC_PATH"]
    app.add_url_rule("/static/<path:filename>", endpoint="static", view_func=app.send_static_file)

    # custom template path, fall back to default
    jinja_loader = jinja2.ChoiceLoader([jinja2.FileSystemLoader(app.config["TEMPLATE_PATH"]), app.jinja_loader])
    app.jinja_loader = jinja_loader

    configure_logging(app)

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

    celery.add_defaults(app.config)

    # configure error handlers
    @app.errorhandler(403)
    def forbidden_page(error):
        return render_template("403.html"), 403

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template("404.html"), 404

    @app.errorhandler(500)
    def server_error_page(error):
        return render_template("500.html"), 500

    if app.config["DEBUG"]:
        from werkzeug.wsgi import SharedDataMiddleware

        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {"/preview": app.config["DOWNLOAD_PATH"]})

    return app
Example #13
0
def create_app():
    application = Flask(__name__, static_folder=EG_STATIC_FOLDER)
    my_loader = jinja2.ChoiceLoader([application.jinja_loader, jinja2.FileSystemLoader(EG_SYSTEM_TEMPLATE_FOLDER)])

    application.jinja_loader = my_loader
    application.secret_key = APP_SECRET_KEY
    application.config.from_object("config")

    application.jinja_env.filters["date"] = datetime_filter

    # Initialize Babel
    Babel(application)
    application.config["BABEL_DEFAULT_LOCALE"] = BABEL_DEFAULT_LOCALE

    # Initialize database
    from therm.models import db

    db.init_app(application)

    return application
Example #14
0
def init(cfg):
    from yaml import load as yaml_load
    from jinja2 import FileSystemLoader
    from os.path import join as path_join, exists
    from hicode import setting
    from pygments.lexers import get_all_lexers
    from pygments.styles import get_all_styles

    if exists(cfg):
        users = yaml_load(file(cfg).read())
        setting.update(users)

    setting["styles"] = list(get_all_styles())
    setting["langs"] = dict(map(lambda x: (x[0], x[1]), get_all_lexers()))

    app = Flask("hicode")
    app.jinja_loader = FileSystemLoader(setting["template_directory"])
    app.debug = setting["debug"]

    return app
Example #15
0
def serve(py_exec=None):
    log_set_up(DEBUG)
    parser = argparse.ArgumentParser()
    parser.add_argument("--python", default="python2")
    args = parser.parse_args()

    py_exec = args.python

    app = Flask("touchandgo")
    template_path = join(dirname(__file__), "templates")
    app.jinja_loader = FileSystemLoader(template_path)

    def get_torrent(name, season=None, episode=None):
        interface = get_interface()
        path = abspath(__file__)
        dir_path = dirname(path)
        exec_ = join(dir_path, "__init__.py")
        command = '%s %s "%s" ' % (py_exec, exec_, name)
        if season is not None:
            command += "%s %s " % (season, episode)
        lock = Lock(LOCKFILE)
        if lock.is_same_file(name, season, episode) and is_process_running(lock.get_pid()):
            data = lock._get_file_data()
            port = data[4]
        else:
            port = get_free_port()
            command += "--daemon --port %s " % port
            log.debug(command)
            process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
            sleep(1)

        redirect_url = "http://%s:%s" % (interface, port)
        serving = False
        while not serving:
            try:
                req = requests.get("%s/status" % redirect_url)
                serving = True
            except requests.ConnectionError, e:
                sleep(1)
        log.info("redirecting to %s" % redirect_url)
        return redirect(redirect_url)
Example #16
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 #17
0
    "username": os.getenv("MONGODB_USER", ""),
    "password": os.getenv("MONGODB_PASS", ""),
}

client = MongoClient(host=MONGODB_SETTINGS["host"], port=int(MONGODB_SETTINGS["port"]))
db = client[MONGODB_SETTINGS["db"]]

db.authenticate(MONGODB_SETTINGS["username"], MONGODB_SETTINGS["password"])

fs = GridFS(db)

blocks = db.blocks

app = Flask(__name__)

app.jinja_loader = jinja2.ChoiceLoader([app.jinja_loader, MongoLoader(fs)])


@app.template_filter("markdown")
def render_markdown(text):
    return jinja2.Markup(markdown.markdown(text))


@app.route("/", methods=["GET"])
def index():
    recent_blocks = list(blocks.find(sort=[("timestamp", -1)], limit=20))
    return render_template("index.html", blocks=recent_blocks)


@app.route("/pregame/<google_drive_id>/render/", methods=["GET"])
def pregame(google_drive_id):
Example #18
0
@app.route("/food")
@login_required
def food():
    return render_template("food.html")


@app.route("/devices")
@login_required
def device():
    return render_template("devices.html")


@login_manager.user_loader
def load_user(user_id):
    u = auth.models.User(user_id)
    if u:
        return u
    else:
        return None


from views.order_views import *
from views.sanitation_views import *
from views.home_views import *
from views.device_views import *

static = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
app.jinja_loader = jinja2.FileSystemLoader(static)
template = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates")
app.jinja_loader = jinja2.FileSystemLoader(template)
Example #19
0
app.config["VERSION"] = os.environ.get("CURRENT_SHA", None)
app.config["X-HOSTNAME"] = os.environ.get("X_HOSTNAME", socket.gethostname())
app.config["BIND_INTERFACE"] = os.environ.get("BIND_INTERFACE", "127.0.0.1")
app.config["LOG_LEVEL"] = os.environ.get("LOG_LEVEL", "INFO")
app.config["USER_HEADER_NAME"] = os.environ.get("USER_HEADER_NAME", "Uid")
app.config["ROOT_STORAGE_PATH"] = os.environ.get("ROOT_STORAGE_PATH", "./storage")
app.config["CACHE_ROOT"] = os.environ.get("CACHE_ROOT", "%s/cache" % (app.config["ROOT_STORAGE_PATH"]))
app.config["USE_RELOADER"] = os.environ.get("USE_RELOADER", "True")
app.config["TEMPLATE_DIR"] = TEMPLATE_DIR
app.config["SUBMOUNT_PATH"] = os.environ.get("SUBMOUNT_PATH", None)
# this is to be a comman delimited list of sources for which events will be emitted
# this of course depends on the system supporting events for those sources
app.config["LOCAL_EVENT_SOURCES"] = frozenset(os.environ.get("LOCAL_EVENT_SOURCES", "").split(","))

app.config["_CACHE"] = FileSystemCache(app.config["CACHE_ROOT"])
app.jinja_loader = ChoiceLoader([FileSystemLoader("./templates"), FileSystemLoader("./pyserver/templates")])

logging.basicConfig(format="%(asctime)s [%(levelname)s]: %(message)s", stream=sys.stderr, level=app.config["LOG_LEVEL"])

process_start_time = datetime.datetime.now()


def emit_local_message(source, message=None):
    if source in app.config["LOCAL_EVENT_SOURCES"]:
        wrapped = json.dumps(dict(source=source, message=message, user_token=g.user_token))
        messages.send(wrapped, messages.LOCAL_PUBLISH)


def get_storage_location(named):
    return path.abspath(path.join(app.config["ROOT_STORAGE_PATH"], named))
Example #20
0
# -*- coding: utf-8 -*-

from flask import Flask
from application.handlers.view.admin import admin_view
from application.handlers.view.author import author_view
from application.handlers.view.kit import kit_view
from application.handlers.view.category import category_view
from jinja2 import FileSystemLoader

app = Flask(__name__)

app.jinja_loader = FileSystemLoader("application/templates")
app.register_module(admin_view)
app.register_module(author_view)
app.register_module(kit_view)
# app.register_module(call_center_api)
app.register_module(category_view)

if __name__ == "__main__":
    app.run()
Example #21
0
def create_app(config="/config.yml", celery=False):
    # initialize our flask application
    app = Flask(__name__, static_folder="../static", static_url_path="/static")

    # set our template path and configs
    app.jinja_loader = FileSystemLoader(os.path.join(root, "templates"))
    config_vars = yaml.load(open(root + config))
    # inject all the yaml configs
    app.config.update(config_vars)
    app.logger.info(app.config)

    app.rpc_connection = AuthServiceProxy(
        "http://{0}:{1}@{2}:{3}/".format(
            app.config["coinserv"]["username"],
            app.config["coinserv"]["password"],
            app.config["coinserv"]["address"],
            app.config["coinserv"]["port"],
            pool_kwargs=dict(maxsize=app.config.get("maxsize", 10)),
        )
    )

    app.merge_rpc_connection = {}
    for cfg in app.config["merge"]:
        if not cfg["enabled"]:
            continue
        app.merge_rpc_connection[cfg["currency_name"]] = AuthServiceProxy(
            "http://{0}:{1}@{2}:{3}/".format(
                cfg["coinserv"]["username"],
                cfg["coinserv"]["password"],
                cfg["coinserv"]["address"],
                cfg["coinserv"]["port"],
                pool_kwargs=dict(maxsize=app.config.get("maxsize", 10)),
            )
        )

    # add the debug toolbar if we're in debug mode...
    if app.config["DEBUG"]:
        from flask_debugtoolbar import DebugToolbarExtension

        DebugToolbarExtension(app)
        app.logger.handlers[0].setFormatter(
            logging.Formatter("%(asctime)s %(levelname)s: %(message)s " "[in %(filename)s:%(lineno)d]")
        )

    # map all our merged coins into something indexed by type for convenience
    app.config["merged_cfg"] = {cfg["currency_name"]: cfg for cfg in app.config["merge"]}

    # register all our plugins
    db.init_app(app)
    cache_config = {"CACHE_TYPE": "redis"}
    cache_config.update(app.config.get("main_cache", {}))
    cache.init_app(app, config=cache_config)

    if not celery:
        hdlr = logging.FileHandler(app.config.get("log_file", "webserver.log"))
        formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
        hdlr.setFormatter(formatter)
        app.logger.addHandler(hdlr)
        app.logger.setLevel(logging.INFO)

        # try and fetch the git version information
        try:
            output = subprocess.check_output("git show -s --format='%ci %h'", shell=True).strip().rsplit(" ", 1)
            app.config["hash"] = output[1]
            app.config["revdate"] = output[0]
        # celery won't work with this, so set some default
        except Exception:
            app.config["hash"] = ""
            app.config["revdate"] = ""

    # filters for jinja
    @app.template_filter("fader")
    def fader(val, perc1, perc2, perc3, color1, color2, color3):
        """
        Accepts a decimal (0.1, 0.5, etc) and slots it into one of three categories based
        on the percentage.
        """
        if val > perc3:
            return color3
        if val > perc2:
            return color2
        return color1

    @app.template_filter("sig_round")
    def sig_round_call(*args, **kwargs):
        return sig_round(*args, **kwargs)

    @app.template_filter("duration")
    def time_format(seconds):
        # microseconds
        if seconds > 3600:
            return "{}".format(timedelta(seconds=seconds))
        if seconds > 60:
            return "{:,.2f} mins".format(seconds / 60.0)
        if seconds <= 1.0e-3:
            return "{:,.4f} us".format(seconds * 1000000.0)
        if seconds <= 1.0:
            return "{:,.4f} ms".format(seconds * 1000.0)
        return "{:,.4f} sec".format(seconds)

    @app.template_filter("time_ago")
    def pretty_date(time=False):
        """
        Get a datetime object or a int() Epoch timestamp and return a
        pretty string like 'an hour ago', 'Yesterday', '3 months ago',
        'just now', etc
        """

        now = datetime.utcnow()
        if type(time) is int:
            diff = now - datetime.utcfromtimestamp(time)
        elif isinstance(time, datetime):
            diff = now - time
        elif not time:
            diff = now - now
        second_diff = diff.seconds
        day_diff = diff.days

        if day_diff < 0:
            return ""

        if day_diff == 0:
            if second_diff < 60:
                return str(second_diff) + " seconds ago"
            if second_diff < 120:
                return "a minute ago"
            if second_diff < 3600:
                return str(second_diff / 60) + " minutes ago"
            if second_diff < 7200:
                return "an hour ago"
            if second_diff < 86400:
                return str(second_diff / 3600) + " hours ago"
        if day_diff == 1:
            return "Yesterday"
        if day_diff < 7:
            return str(day_diff) + " days ago"
        if day_diff < 31:
            return str(day_diff / 7) + " weeks ago"
        if day_diff < 365:
            return str(day_diff / 30) + " months ago"
        return str(day_diff / 365) + " years ago"

    from .tasks import celery

    celery.conf.update(app.config)

    # Route registration
    # =========================================================================
    from . import views, models, api, rpc_views

    app.register_blueprint(views.main)
    app.register_blueprint(api.api, url_prefix="/api")

    return app
Example #22
0
import os
from flask import Flask, render_template
from jinja2 import FileSystemLoader
import sqlite3

app = Flask(__name__)

app.jinja_loader = FileSystemLoader(os.path.join(os.path.abspath(os.path.dirname(__file__)), "app_templates"))


@app.route("/", methods=["GET"])
def index():
    item_connect = sqlite3.connect("item.db")

    search_result = []

    search_result = item_connect.execute(u"select * from lists;")

    data = search_result.fetchall()
    cnt = len(data)

    return render_template("index.html", result=data, count=cnt)


@app.route("/register", methods=["GET"])
def register():
    return render_template("register.html")


if __name__ == "__main__":
    app.run()
Example #23
0
from flask import Flask, render_template, session, request, redirect, url_for, flash, abort, send_from_directory
from models import *
import jinja2
from forms import *
from flask.ext.mail import Message, Mail
from datetime import datetime
from flask.ext.mysqldb import MySQL
from werkzeug import secure_filename
import os

UPLOAD_FOLDER = "/home/tkstman/Web/final/finalproj/intro_to_flask/static/img"
ALLOWED_EXTENSIONS = set(["png", "PNG", "jpg", "JPG", "jpeg", "JPEG", "gif", "GIF"])


app = Flask(__name__, template_folder="templates")
app.jinja_loader = jinja2.FileSystemLoader("templates")

app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER

app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+mysqldb://root:root@localhost/finalproject"

db.init_app(app)

app.secret_key = "tkssmartkodecodeWorldProdigy232323421@1127@6206birthd#2342)2**("


mail = Mail()
app.config["MAIL_SERVER"] = "smtp.live.com"
app.config["MAIL_PORT"] = 587
app.config["MAIL_USE_SSL"] = True
app.config["MAIL_USERNAME"] = "uwimonaevals@outlook.com"
Example #24
0
import jinja2
from datetime import datetime

app = Flask(__name__)
app.config.from_object("config")

# Include docs folder in templates
my_loader = jinja2.ChoiceLoader(
    [
        app.jinja_loader,
        jinja2.FileSystemLoader(
            ["sni/templates/", "sni/templates/blog/", "sni/templates/docs/", "sni/templates/podcast/"]
        ),
    ]
)
app.jinja_loader = my_loader

db = SQLAlchemy(app)
migrate = Migrate(app, db)

Markdown(app)

manager = Manager(app)
manager.add_command("db", MigrateCommand)

cache = Cache(app, config={"CACHE_TYPE": "simple"})

from models import DonationAddress


@app.context_processor
Example #25
0
# -*- coding: utf-8 -*-

import config_import as ci
import log_control
from flask import Flask, render_template, request, redirect, url_for
from item_search import ItemSearch
from sqlite_query import SqlQuery
from jinja2 import FileSystemLoader

# Run Flask
app = Flask(__name__, static_folder=ci.flask_static_path)
app.jinja_loader = FileSystemLoader(ci.flask_templates_path)

# Import base URL for Kindle item
base_url = ci.base_url

# Routing
@app.route("/kindle_sale/")
def index():

    log_control.logging.debug("/.index: Started.")

    pagetitle = "Kindleセール通知 管理画面"
    text = "Kindleセール通知 管理画面"
    item_list_msg = "セール通知済みアイテム"

    # 登録済みアイテムを格納する変数を用意
    item_list = ""

    # SQLite実行用のインスタンスを生成
    sql = SqlQuery()
Example #26
0
    except OSError as e:
        if e.errno == EEXIST and isdir(path):
            pass
        else:
            raise RuntimeError("{0} exists and is not a directory".format(path))


# get confs
app = Flask(__name__)
try:
    app.config.from_envvar("TM_SETTINGS")
except:
    exit("Error loading TM_SETTINGS, is such variable defined?")

# setup the loader so that if finds the templates also in the zip file
app.jinja_loader = PackageLoader("tm", "client")

# make UPLOAD_DIR resolved and absolute
app.config["UPLOAD_DIR"] = abspath(expandvars(expanduser(app.config["UPLOAD_DIR"])))
safe_makedirs(app.config["UPLOAD_DIR"])

# compute a digest of TAR_DATA to show at root URL
app.config["TAR_DIGEST"] = mac(app.config["SECRET_KEY"], app.config["TAR_DATA"], sha256).hexdigest()

# setup logging
if not app.debug:
    sh = StreamHandler()
    sh.setLevel(INFO)
    f = Formatter(
        "%(asctime)s [%(process)s] [%(levelname)s] Flask: %(name)s [in %(pathname)s:%(lineno)d] %(message)s",
        "%Y-%m-%d %H:%M:%S",
Example #27
0

def check_env():
    required_env = ["DRADIS_API_KEY", "DRADIS_SQL", "RECORDS_ROOT", "MEDIA_ROOT", "MEDIA_URL"]

    for key in required_env:
        if key not in os.environ:
            print("ERROR: Environment variable {} is required to run Dradis.".format(key), file=sys.stderr)
            sys.exit(1)


load_env(dradis_root)
check_env()

app = Flask("dradis.workers.webserver")
app.jinja_loader = jinja2.FileSystemLoader(os.path.join(dradis_root, "templates"))

app.config.update(
    DRADIS_API_KEY=os.environ["DRADIS_API_KEY"],
    DRADIS_ROOT=dradis_root,
    RECORDS_ROOT=os.environ["RECORDS_ROOT"],
    RECORDS_URL=os.environ["RECORDS_URL"],
    MEDIA_ROOT=os.environ["MEDIA_ROOT"],
    MEDIA_URL=os.environ["MEDIA_URL"],
    SQLALCHEMY_DATABASE_URI=os.environ["DRADIS_SQL"],
    SQLALCHEMY_ECHO=False,
)


assets = Environment(app)
assets.debug = True
Example #28
0
# The following if statement is a workaround that is allowing us to run this
# in debug mode, rather than a hard coded location.

tmpl_dir = os.path.join(base_dir, "listener", "templates")
if not os.path.isdir(tmpl_dir):
    tmpl_dir = os.path.join(base_dir, "agent", "listener", "templates")

stat_dir = os.path.join(base_dir, "listener", "static")
if not os.path.isdir(stat_dir):
    stat_dir = os.path.join(base_dir, "agent", "listener", "static")

if os.name == "nt":
    logging.info(u"Looking for templates at: %s", tmpl_dir)
    listener = Flask(__name__, template_folder=tmpl_dir, static_folder=stat_dir)
    listener.jinja_loader = jinja2.FileSystemLoader(tmpl_dir)
else:
    listener = Flask(__name__, template_folder=tmpl_dir, static_folder=stat_dir)

listener.jinja_env.line_statement_prefix = "#"


# ------------------------------
# Helper functions
# ------------------------------


# Get a configuration value or default
def get_config_value(section, option, default=None):
    try:
        value = listener.config["iconfig"].get(section, option)
Example #29
0
        )
    ),
    RECORDS_UI_DEFAULT_PERMISSION_FACTORY=None,
    SQLALCHEMY_DATABASE_URI=os.getenv("SQLALCHEMY_DATABASE_URI", "sqlite:///app.db"),
    SEARCH_UI_SEARCH_API="/deposits",
    SEARCH_UI_JSTEMPLATE_RESULTS="templates/app/deposit.html",
    DATADIR=join(dirname(__file__), "data/upload"),
    OAUTH2SERVER_CACHE_TYPE="simple",
    OAUTHLIB_INSECURE_TRANSPORT=True,
)

Babel(app)

# Set jinja loader to first grab templates from the app's folder.
app.jinja_loader = jinja2.ChoiceLoader(
    [jinja2.FileSystemLoader(join(dirname(__file__), "templates")), app.jinja_loader]
)

app.url_map.converters["pid"] = PIDConverter

InvenioDB(app)
InvenioI18N(app)
InvenioTheme(app)
InvenioJSONSchemas(app)
InvenioAccounts(app)
InvenioAccess(app)
InvenioRecords(app)
InvenioRecordsUI(app)

InvenioRecordsREST(app)
InvenioDeposit(app)
Example #30
0
def create_app(config="/config.yml", celery=False):
    # initialize our flask application
    app = Flask(__name__, static_folder="../static", static_url_path="/static")

    # set our template path and configs
    app.jinja_loader = FileSystemLoader(os.path.join(root, "templates"))
    config_vars = yaml.load(open(root + config))
    # inject all the yaml configs
    app.config.update(config_vars)
    app.logger.info(app.config)

    app.rpc_connection = AuthServiceProxy(
        "http://{0}:{1}@{2}:{3}/".format(
            app.config["coinserv"]["username"],
            app.config["coinserv"]["password"],
            app.config["coinserv"]["address"],
            app.config["coinserv"]["port"],
            pool_kwargs=dict(maxsize=app.config.get("maxsize", 10)),
        )
    )

    # add the debug toolbar if we're in debug mode...
    if app.config["DEBUG"]:
        from flask_debugtoolbar import DebugToolbarExtension

        DebugToolbarExtension(app)
        app.logger.handlers[0].setFormatter(
            logging.Formatter("%(asctime)s %(levelname)s: %(message)s " "[in %(filename)s:%(lineno)d]")
        )

    # register all our plugins
    db.init_app(app)
    cache_config = {"CACHE_TYPE": "redis"}
    cache_config.update(app.config.get("main_cache", {}))
    cache.init_app(app, config=cache_config)

    if not celery:
        hdlr = logging.FileHandler(app.config.get("log_file", "webserver.log"))
        formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
        hdlr.setFormatter(formatter)
        app.logger.addHandler(hdlr)
        app.logger.setLevel(logging.INFO)

        # try and fetch the git version information
        try:
            output = subprocess.check_output("git show -s --format='%ci %h'", shell=True).strip().rsplit(" ", 1)
            app.config["hash"] = output[1]
            app.config["revdate"] = output[0]
        # celery won't work with this, so set some default
        except Exception:
            app.config["hash"] = ""
            app.config["revdate"] = ""

    # filters for jinja
    @app.template_filter("time_ago")
    def pretty_date(time=False):
        """
        Get a datetime object or a int() Epoch timestamp and return a
        pretty string like 'an hour ago', 'Yesterday', '3 months ago',
        'just now', etc
        """

        now = datetime.utcnow()
        if type(time) is int:
            diff = now - datetime.fromtimestamp(time)
        elif isinstance(time, datetime):
            diff = now - time
        elif not time:
            diff = now - now
        second_diff = diff.seconds
        day_diff = diff.days

        if day_diff < 0:
            return ""

        if day_diff == 0:
            if second_diff < 60:
                return str(second_diff) + " seconds ago"
            if second_diff < 120:
                return "a minute ago"
            if second_diff < 3600:
                return str(second_diff / 60) + " minutes ago"
            if second_diff < 7200:
                return "an hour ago"
            if second_diff < 86400:
                return str(second_diff / 3600) + " hours ago"
        if day_diff == 1:
            return "Yesterday"
        if day_diff < 7:
            return str(day_diff) + " days ago"
        if day_diff < 31:
            return str(day_diff / 7) + " weeks ago"
        if day_diff < 365:
            return str(day_diff / 30) + " months ago"
        return str(day_diff / 365) + " years ago"

    from .tasks import celery

    celery.conf.update(app.config)

    # Route registration
    # =========================================================================
    from . import views, models, api

    app.register_blueprint(views.main)
    app.register_blueprint(api.api, url_prefix="/api")

    return app