Beispiel #1
0
def create_app(config=config, app_name=None):
    """Create a Flask app."""

    if app_name is None:
        app_name = APP_NAME

    app = Flask(app_name)
    app.root_path = app.root_path + "/adsgut"
    _configure_app(app, config)
    _configure_logging(app)
    if not config.TESTING:
        _configure_wsgi_middleware(app)
    #    configure_hook(app)
    _configure_blueprints(app)
    _configure_extensions(app)
    # _configure_template_filters(app)
    # _configure_error_handlers(app)
    _configure_misc_handlers(app)
    _configure_global_variables(app)

    if config.DEBUG:
        from flask_debugtoolbar import DebugToolbarExtension

        toolbar = DebugToolbarExtension(app)

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

    return app
Beispiel #2
0
def create_app(app_state):
    app = Flask(__name__)
    app.debug = True

    if getattr(sys, "frozen", None):
        # set root_path to data dir from PyInstaller
        basedir = sys._MEIPASS
        app.root_path = os.path.join(basedir, os.path.join(*__name__.split(".")))

    app.config.geobox_state = app_state

    app.config["SECRET_KEY"] = app_state.config.get("web", "secret_key")

    from . import views

    app.register_blueprint(views.main)
    app.register_blueprint(views.editor)
    app.register_blueprint(views.tasks)
    app.register_blueprint(views.project)
    app.register_blueprint(views.admin)
    app.register_blueprint(views.vector)
    app.register_blueprint(views.downloads)
    app.register_blueprint(views.proxy)
    app.register_blueprint(views.boxes)
    app.register_blueprint(views.raster)

    @app.before_request
    def before_request():
        g.db = app_state.user_db_session()
        if request_for_static():
            return

        gbi_server = g.db.query(GBIServer).all()

        if len(gbi_server) == 0 and request.endpoint not in (
            "admin.initial_set_server",
            "admin.set_server",
            "admin.add_server",
        ):
            return redirect(url_for("admin.initial_set_server"))

    @app.teardown_request
    def teardown_request(exception):
        """Closes the database again at the end of the request."""
        if hasattr(g, "db"):
            g.db.close()

    from .helper import css_alert_category, add_auth_to_url
    import geobox.app

    app.jinja_env.globals.update(
        css_alert_category=css_alert_category,
        add_auth_to_url=add_auth_to_url,
        app_state=app_state,
        geobox_client_version=geobox.app.version,
    )

    configure_i18n(app, app_state.locale())
    configure_errorhandlers(app)
    return app
    def test_init_without_cache_folder(self):
        app = Flask(__name__)
        app.root_path = os.path.abspath(os.path.normpath(os.path.dirname(__file__) + "/../"))
        app.config["TESTING"] = True
        app.config["SERVER_NAME"] = "localhost"
        app.config["SECRET_KEY"] = "secret secret"

        app.config["IMAGINE_ADAPTER"] = {"name": "fs", "source_folder": "images"}

        imagine = Imagine(app)
        self.assertTrue(isinstance(imagine, Imagine))
Beispiel #4
0
def app(tmpdir):
    from flask import Flask

    root_path = tmpdir.ensure("test-proj", dir=True)

    tmpdir.ensure("test-proj/static/coffee", dir=True)
    p = tmpdir.join("test-proj/static/coffee", "Cakefile")
    p.write("")

    app = Flask(__name__)
    app.root_path = root_path.strpath
    return app
Beispiel #5
0
def create_app(app_state):
    app = Flask(__name__)
    app.debug = True

    if getattr(sys, "frozen", None):
        # set root_path to data dir from PyInstaller
        basedir = sys._MEIPASS
        app.root_path = os.path.join(basedir, os.path.join(*__name__.split(".")))

    app.config.geobox_state = app_state

    app.config["SECRET_KEY"] = app_state.config.get("web", "secret_key")

    from . import views

    app.register_blueprint(views.main)
    app.register_blueprint(views.map)
    app.register_blueprint(views.tasks)
    app.register_blueprint(views.project)
    app.register_blueprint(views.user)
    app.register_blueprint(views.admin)
    app.register_blueprint(views.vector)
    app.register_blueprint(views.downloads)

    @app.before_request
    def before_request():
        from helper import request_for_static

        g.db = app_state.user_db_session()
        if request_for_static():
            return

        username = session.get("username", False)
        if not username and request.endpoint != "user_view.login":
            abort(403)

    @app.teardown_request
    def teardown_request(exception):
        """Closes the database again at the end of the request."""
        if hasattr(g, "db"):
            g.db.close()

    from .helper import css_alert_category, add_auth_to_url

    app.jinja_env.globals.update(css_alert_category=css_alert_category, add_auth_to_url=add_auth_to_url)

    configure_i18n(app, app_state.locale())
    configure_errorhandlers(app)
    return app
Beispiel #6
0
pyximport.install()
from twisted.internet.defer import inlineCallbacks
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
Beispiel #7
0

root_path = os.path.dirname(__file__)


def root_join(*segs):
    return os.path.join(root_path, *segs)


sys.path.append(root_path)
sys.path.append(root_join(".."))


app = Flask(__name__)
app.root_join = root_join
app.root_path = root_path
app.config.from_pyfile("config.py")
db_engine = create_engine(app.config["DATABASE"], convert_unicode=True)
Session = sessionmaker(bind=db_engine, autocommit=False, autoflush=False)
BaseModel = declarative_base()


def objects(cls):
    return g.db.query(cls)


BaseModel.objects = classmethod(objects)


def objects_filter(cls, **filters):
    fs = []
Beispiel #8
0
import logging
import os, sys

support = WebSupport(serveconf.SRCDIR, serveconf.BUILDDIR)

#### flask part

from flask import Flask, render_template, abort, g, request, jsonify, redirect, url_for
from jinja2 import Environment, FileSystemLoader

app = Flask(__name__)
app.debug = True  # デバッグ用フラグ
app.jinja_env = Environment(
    loader=FileSystemLoader(os.path.abspath(serveconf.TEMPLATE_DIR) + "/"), extensions=["jinja2.ext.i18n"]
)
app.root_path = serveconf.BUILDDIR


# Via bzrlib.tests
class StringIOWrapper(object):
    """A wrapper around cStringIO which just adds an encoding attribute.

	Internally we can check sys.stdout to see what the output encoding
	should be. However, cStringIO has no encoding attribute that we can
	set. So we wrap it instead.
	"""

    encoding = "ascii"
    _cstring = None

    def __init__(self, s=None):
Beispiel #9
0
import ConfigParser
import os
import stat

from flask import Flask, g, redirect, url_for
from overview import CONF_DIR, DATA_DIR, ROOT_PATH, STATIC_DIR, TEMPLATE_DIR
from overview.module.jira.blueprint import jira
from overview.module.nagios.blueprint import nagios
from overview.module.rman.blueprint import rman
from overview.module.sqlrelay.blueprint import sqlrelay
from werkzeug.contrib.cache import FileSystemCache


# Create application
app = Flask(__name__, static_folder=STATIC_DIR, template_folder=TEMPLATE_DIR)
app.root_path = ROOT_PATH
app.debug = True

# Load configuration
file_path = os.path.join(CONF_DIR, "overview.conf")

if os.path.exists(file_path):
    # Check secret key file permissions
    mode = os.stat(file_path).st_mode

    if mode & stat.S_IRWXU != 384 or mode & stat.S_IRWXG != 0 or mode & stat.S_IRWXO != 0:
        raise Exception("%s file permissions should be 600\n" % file_path)

    parser = ConfigParser.ConfigParser()
    parser.read([file_path])
Beispiel #10
0
import constants
import db
import dictionary
import model
import segment
import utils


DEBUG = True
SECRET_KEY = "development key"
app = Flask(__name__)
app.config.from_object(__name__)

## this file is in serverside, but we need one directory up.
myfn = os.path.abspath(__file__)
app.root_path = os.path.dirname(os.path.dirname(myfn)) + os.path.sep
app.debug = DEBUG

app.config.update(
    PERSONA_JS="https://login.persona.org/include.js", PERSONA_VERIFIER="https://verifier.login.persona.org/verify"
)


@utils.nocache
@app.route("/")
def index():
    return send_from_directory(app.root_path + "app", "index.html")


@app.route("/upload", methods=["GET"])
def upload():
Beispiel #11
0
Application bootstrapping, config and routes.

"""

from flask import Flask, render_template, request
from jinja2 import FileSystemLoader
from .utils import curry
from .services import Service
from exceptions import ImportError
import os, sys


# Setup the app and load the settings
app = Flask(__name__)
app.config.from_envvar("NARCISSIST_SETTINGS")
app.root_path = app.config["ROOT_PATH"]

main_template_path = os.path.join(app.root_path, "themes")
app.jinja_loader = FileSystemLoader(main_template_path)

# We will hold the mapped URLS in config so we can access them in the templates
app.config["URLS"] = []


def _endpoint(service):
    """ Helper for XHR requests. If the request is XHR, omit the layout. """

    if request.is_xhr:
        return self.service.render()
    else:
        return render_template(
Beispiel #12
0
start = time.clock()

# Since the script has the same name as the module
# we must drop the current path from sys.path:

sys.path.pop(0)
from flaskyll.yamlpages import YamlPages


# Create the Flask application and configure it.
# Re-create the config after overriding root_path
# to be able to use relative paths:

app = Flask(__name__)
app.root_path = os.getcwd()

app.config = app.make_config()
app.config.update(
    {
        "DEBUG": True,
        "PORT": 8000,
        "FREEZER_DESTINATION": "build",
        "FREEZER_REMOVE_EXTRA_FILES": True,
        "MARKDOWN_EXTENSIONS": ["codehilite", "extra"],
        "PRUNNING": True,
        "VERBOSE": True,
    }
)

Beispiel #13
0
import os

from celery import Celery
from flask import Flask
from flask import send_from_directory
from flask.ext.cache import Cache
from flask.ext.pymongo import PyMongo

from app.celery import make_celery
from app.config import Config
from app.ext.session.redis import RedisSessionInterface


app = Flask(__name__)
app.session_interface = RedisSessionInterface()
app.config.from_object(config.Development)
app._static_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../static")
app.root_path = os.path.dirname(os.path.abspath(__file__ + "/../"))
print(app.root_path)

app.cache = Cache(app)
app.mongo = PyMongo(app)

celery = make_celery(app)


from teddy.views import teddy as teddy_blueprint


app.register_blueprint(teddy_blueprint, url_prefix="/teddy")
Beispiel #14
0
def run(config, run=True):

    appli = Flask("tracsearch", instance_relative_config=True)
    appli.root_path = "."
    if config.has_section("sentry"):
        from raven.contrib.flask import Sentry

        sentry = Sentry(appli, dsn=config.get("sentry", "dsn"))

    if config.has_section("statsd"):
        from statsd import StatsClient

        stats = StatsClient(config.get("statsd", "host"), 8125, prefix="tracsearch")
    else:
        stats = None

    es = Elasticsearch(hosts=config.get("elasticsearch", "url", "127.0.0.1:9200"))

    @appli.template_filter("nicedate")
    def nicedate(value):
        value = escape(value)
        year = value[0:4]
        month = value[4:6]
        day = value[6:8]
        time = value[9:17]
        return "%s-%s-%s %s" % (year, month, day, time)

    @appli.route("/components/<path:filename>")
    def components(filename):
        return send_from_directory("components", filename)

    @appli.route("/", methods=["GET"])
    def index():
        q = request.args.get("q", "")
        size = 20
        from_ = int(request.args.get("from", 0))
        facets = ["status", "user", "priority", "keywords", "component", "_type", "path", "domain"]
        selected = {}
        for facet in facets:
            a = request.args.get("facet_%s" % facet, "")
            if a != "":
                selected[facet] = a
        if q == "":
            context = {"results": None}
        else:
            # http://www.elasticsearch.org/guide/reference/query-dsl/query-string-query.html
            query = {
                "query": {"query_string": {"query": q, "default_operator": "AND"}},
                "facets": {"changetime": {"date_histogram": {"field": "changetime", "interval": "week"}}},
                "highlight": {
                    "pre_tags": ["<b>"],
                    "post_tags": ["</b>"],
                    "fields": {
                        "_all": {},
                        "comment.comment": {},
                        "description": {},
                        "summary": {},
                        "body": {},
                        "name": {},
                    },
                },
                "filter": {},
            }
            for facet in facets:
                query["facets"][facet] = {"terms": {"field": facet}}
                if selected != {}:
                    query["facets"][facet]["facet_filter"] = {"term": selected}

            if selected != {}:
                query["filter"] = {"term": selected}
                query["facets"]["changetime"]["facet_filter"] = {"term": selected}

            context = dict(q=q, facets=selected)
            start = request.args.get("start", "")
            end = request.args.get("end", "")
            if end != "":
                filter_ = {"changetime": {"from": int(start), "to": int(end)}}
                query["filter"]["range"] = filter_
                query["facets"]["changetime"]["facet_filter"] = {"range": filter_}
                context["start"] = start
                context["end"] = end

            tmp = request.args.copy()
            tmp["from"] = int(request.args.get("from", 0)) + 1
            context["next"] = urllib.urlencode(encode_dict(tmp))
            tmp["from"] = tmp["from"] - 2
            context["previous"] = urllib.urlencode(encode_dict(tmp))
            tmp["from"] = 0
            context["first"] = urllib.urlencode(encode_dict(tmp))
            print query
            context["from"] = from_
            context["size"] = size
            results = es.search(index="trac", size=size, body=query)
            if stats:
                stats.incr("query")
                stats.timing("query", results["took"])
            print results.keys()
            print results["hits"]
            context["results"] = results
        return render_template("index.html", **context)

    appli.debug = config.get("web", "debug", False)
    if run:
        appli.run(config.get("web", "host", "127.0.0.1"))
    else:
        return appli
Beispiel #15
0
from picamera.array import PiRGBArray
from picamera import PiCamera

# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
camera.rotation = 180
rawCapture = PiRGBArray(camera, size=(640, 480))

# allow the camera to warmup
time.sleep(0.1)


app = Flask(__name__)
app.root_path = abspath(dirname(__file__))


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


# def gen(camera):
#     for frame in camera.capture_continuous(rawCapture,
#                                           format="bgr",
#                                           use_video_port=True):
#         # grab the raw NumPy array representing the image, then
#         # initialize the timestamp
#         # and occupied/unoccupied text
#         img = frame.array
Beispiel #16
0
def initWebServer(myport):
    app = Flask(__name__, static_folder="html", template_folder="html/templates")
    app.root_path = os.getcwd()
    logging.config.fileConfig(app.root_path + "/python/" + "logging.conf")
    logger = logging.getLogger("simple")

    @app.route("/")
    def send_1():
        user, priv = proc_jwt(request.cookies.get("jwt"))
        if priv == "JWTError":
            return redirect("login.html")
        return redirect("dashboard.html")

    @app.route("/login.html")
    def send_2():
        user, priv = proc_jwt(request.cookies.get("jwt"))
        if priv == "JWTError":
            return send_from_directory(app.static_folder, "login.html")
        if priv == "JWSError":
            response = make_response("login.html")
            response.set_cookie("jwt", "")
            return response
        return redirect("dashboard.html")

    @app.route("/login_action.cgi", methods=["POST", "GET"])
    def send_3():
        error = None
        if request.method == "POST":
            user = request.form["inputUsername"]
            if m_valid_login(user, request.form["inputPassword"]) == True:
                privilage = dbman.get_privilage(user).decode("utf-8")
                client_jwt = myjwt.generate_JWT(user, privilage)
                response = make_response("dashboard.html")
                response.set_cookie("jwt", client_jwt)
                return response
            return "Wrong username or wrong password."
        return "Bad Request", 400, {"Content-Type": "text/html"}  # Generate http 400

    @app.route("/templates/dashboard.html")
    def send_4(first="无", second="0", third="0", fourth="0"):
        user, priv = proc_jwt(request.cookies.get("jwt"))
        if priv == "JWTError":
            return "Unauthorized", 401, {"Content-Type": "text/html"}
        chk_internet = internet_on()
        if chk_internet == True:
            first = "良好"
        second = str(callcpp.get_online_client())
        fourth = str(dbman.get_user_count())
        return render_template("dashboard.html", first=first, second=second, third=third, fourth=fourth)

    @app.route("/templates/IRControl.html")
    def send_5():
        user, priv = proc_jwt(request.cookies.get("jwt"))
        if priv == "JWTError":
            return "Unauthorized", 401, {"Content-Type": "text/html"}
        return render_template("IRControl.html")

    @app.route("/templates/Usermanager.html")
    def send_6():
        user, priv = proc_jwt(request.cookies.get("jwt"))
        if priv == "JWTError":
            return "Unauthorized", 401, {"Content-Type": "text/html"}
        return render_template("Usermanager.html")

    @app.route("/<path:filename>")
    def send_7(filename):
        return send_from_directory(app.static_folder, filename)

    @app.route("/js/<path:filename>")
    def send_8(filename):
        return send_from_directory(app.static_folder + "/js", filename)

    @app.route("/css/<path:filename>")
    def send_9(filename):
        return send_from_directory(app.static_folder + "/css", filename)

    @app.route("/fonts/<path:filename>")
    def send_10(filename):
        return send_from_directory(app.static_folder + "/fonts", filename)

    @app.route("/get_user_info.cgi", methods=["GET"])
    def send_11():
        user, priv = proc_jwt(request.cookies.get("jwt"))
        res = '{"User": "' + user + '","Priv": "' + priv + '"}'
        return res, 200, {"Content-Type": "application/json"}

    @app.route("/logout.cgi", methods=["GET"])
    def send_12():
        response = make_response(redirect("login.html"))
        response.set_cookie("jwt", "")
        return response

    @app.route("/renew_jwt.cgi", methods=["GET"])
    def send_13():
        user, priv = proc_jwt(request.cookies.get("jwt"))
        if priv == "JWTError":
            return "Unauthorized", 401, {"Content-Type": "text/html"}
        response = make_response()
        renew = myjwt.renew_JWT(request.cookies.get("jwt"))
        if renew == "Error":
            return "Unauthorized", 401, {"Content-Type": "text/html"}
        if renew == "NotNess":
            return ""
        else:
            response.set_cookie("jwt", renew)
            return response

    @app.route("/study_IR.cgi", methods=["POST", "GET"])
    def send_14():
        if request.method == "POST":
            user, priv = proc_jwt(request.cookies.get("jwt"))
            if priv == "JWTError":
                return "Unauthorized", 401, {"Content-Type": "text/html"}
            IRID = request.form["IRID"]
            m_dict = {}
            m_dict["b"] = "b"
            m_dict["c"] = int(IRID)
            callcpp.m_write_dict(m_dict)
        return "Bad Request", 400, {"Content-Type": "text/html"}

    @app.route("/get_IR_recode.cgi")
    def send_15():
        user, priv = proc_jwt(request.cookies.get("jwt"))
        if priv == "JWTError":
            return "Unauthorized", 401, {"Content-Type": "text/html"}
        st = request.args["rangeL"]
        num = request.args["num"]
        res = dbman.get_IR_dict(st, num)
        response = make_response(JSONEncoder().encode(res))
        return respond

    @app.route("/go_IR_action.cgi", methods=["POST", "GET"])
    def send_16():
        if request.method == "POST":
            user, priv = proc_jwt(request.cookies.get("jwt"))
            if priv == "JWTError":
                return "Unauthorized", 401, {"Content-Type": "text/html"}
            action = request.form["action"]
            operator = {"send": IR_action_Send, "modify": IR_action_Modify, "remove": IR_action_Remove}
            res = operator.get(action)(request.form["m_data"])
            respond = make_response(res)
            return respond
        return "Bad Request", 400, {"Content-Type": "text/html"}

    @app.route("/get_user_list.cgi")
    def send_17():
        # {ID:username}
        user, priv = proc_jwt(request.cookies.get("jwt"))
        if priv == "JWTError":
            return "Unauthorized", 401, {"Content-Type": "text/html"}
        num = request.args["num"]
        st = request.args["start"]
        res = dbman.get_user_list(st, num)
        return JSONEncoder().encode(res), 200, {"Content-Type": "application/json"}

    @app.route("/get_IR_learn_proc.cgi")
    def send_18():
        res = callcpp.m_read()
        return ""

    @app.route("/get_priv_list.cgi")
    def send_19():
        # {username:privilage}
        user, priv = proc_jwt(request.cookies.get("jwt"))
        if priv == "JWTError":
            return "Unauthorized", 401, {"Content-Type": "text/html"}
        num = request.args["num"]
        st = request.args["start"]
        res = dbman.get_priv_list(st, num)
        return JSONEncoder().encode(res), 200, {"Content-Type": "application/json"}

    @app.route("/modify_password.cgi", methods=["POST", "GET"])
    def send_20():
        if request.method == "POST":
            user, priv = proc_jwt(request.cookies.get("jwt"))
            if priv == "JWTError":
                return "Unauthorized", 401, {"Content-Type": "text/html"}
            u_name = request.form["username"]
            oripass = request.form["oripass"]
            newpass = request.form["newpass"]
            if (user != u_name) and (priv != "admin"):
                return "Privilage Error", 400, {"Content-Type": "text/html"}
            if dbman.verify_user(u_name, oripass) != "Success.":
                return "Original password wrong", 400, {"Content-Type": "text/html"}
            if dbman.change_user_pass(u_name, newpass) == "Success.":
                respond = make_response("Success.")
                if u_name == user:  # revoke jwt
                    respond = make_response("Relogin.")
                    respond.set_cookie("jwt", "")
                return respond
        return "Bad Request", 400, {"Content-Type": "text/html"}

    @app.route("/get_operation_log.cgi")
    def send_21():
        user, priv = proc_jwt(request.cookies.get("jwt"))
        if priv == "JWTError":
            return "Unauthorized", 401, {"Content-Type": "text/html"}
        respond = make_response("Success.")
        return respond

    @app.route("/get_ready_info.cgi")
    def send_22():
        user, priv = proc_jwt(request.cookies.get("jwt"))
        if priv == "JWTError":
            return "Unauthorized", 401, {"Content-Type": "text/html"}
        respond = make_response("Success.")
        return respond

    app.run(host="0.0.0.0", port=int(myport), threaded=True)
Beispiel #17
0
import json
import os.path
from gevent import wsgi

from flask import Flask, make_response
app = Flask("Locust Monitor")
app.debug = True
app.root_path = os.path.dirname(__file__)

_locust = None
_num_clients = None
_num_requests = None
_hatch_rate = None

@app.route('/')
def index():
    response = make_response(open(os.path.join(app.root_path, "static", "index.html")).read())
    response.headers["Content-type"] = "text/html"
    return response

@app.route('/swarm')
def swarm():
    from core import locust_runner
    locust_runner.start_hatching()
    return json.dumps({'message': 'Swarming started'})

@app.route('/stats/requests')
def request_stats():
    from core import locust_runner
    stats = []
    
Beispiel #18
0
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):
            app.register_blueprint(obj)
Beispiel #19
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"))
Beispiel #20
0
dataDir = radioRootPath()
if not os.path.isdir(radioRootPath()):
    os.mkdir(radioRootPath())
rundir = get_rundir()

# Include paths
sys.path.insert(0, rundir)
sys.path.insert(0, os.path.join(rundir, "radioLib"))

# Create Flask instance
app = Flask(__name__)
app.secret_key = "\xc8/x\xa4\x9f\xfaQw\xe5\xfe\xdd:\x0eq\xdai_\n\xedZ\x02\xf5\xbb\xb9"

# If frozen, we need define static and template paths
if check_frozen():
    app.root_path = rundir
    app.static_path = "/static"
    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(rundir, "templates"))


def import_modules():
    import modules.index
    from modules.rd import log


@app.teardown_request
def shutdown_session(exception=None):
Beispiel #21
0
import runners
from runners import MasterLocustRunner
from locust.stats import median_from_dict
from locust import version
import gevent

import logging

logger = logging.getLogger(__name__)

DEFAULT_CACHE_TIME = 2.0

app = Flask(__name__)
app.debug = True
app.root_path = os.path.dirname(os.path.abspath(__file__))

_request_stats_context_cache = {}


@app.route("/")
def index():
    is_distributed = isinstance(runners.locust_runner, MasterLocustRunner)
    if is_distributed:
        slave_count = runners.locust_runner.slave_count
    else:
        slave_count = 0

    return render_template(
        "index.html",
        state=runners.locust_runner.state,
Beispiel #22
0
def get():
    global _app
    if not _app:
        _app = Flask(__name__)
        _app.root_path = get_parent_dir(_app.root_path)
    return _app