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 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 #3
0
def make_app(projectPath):
    app = Flask(__name__)
    app.root_path = str(projectPath)
    app.config.update(
        DEBUG=True,
        FLATPAGES_AUTO_RELOAD=True,
        FLATPAGES_EXTENSION='.md',
        FREEZER_RELATIVE_URLS=True)
    app.add_url_rule('/', 'index', route_index)
    app.add_url_rule('/<path:path>/', 'page', route_page)
    app.add_url_rule('/tag/<string:tag>/', 'tag', route_tag)
    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 #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
from flask import Flask
from flask import render_template
from flask import Markup

from werkzeug.contrib.cache import MemcachedCache

import os
import markdown

app = Flask(__name__)
app.root_path = os.path.dirname(os.path.realpath(__file__))

import logging
from logging import FileHandler 
file_handler = FileHandler(app.root_path+'/error.log')
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)

try:
    cache = MemcachedCache(['127.0.0.1:11211'])
except RuntimeError:
    
    class FakeCache:
        def get(self, k): return None
        def set(self, k, v, **kwargs): return None
        
    cache = FakeCache()
    
@app.route('/')
@app.route('/<page>')
@app.route('/<page>/<section>')
Beispiel #7
0
def serve(options):
    try:
        import flask
        from flask import Flask, send_file, safe_join
        from flask.json import jsonify
    except ImportError:
        abort("Cannot find flask module which is required for webserver mode.")

    webserver = Flask('git-deps')
    here = os.path.dirname(os.path.realpath(__file__))
    root = os.path.join(here, 'html')
    webserver.root_path = root

    ##########################################################
    # Static content

    @webserver.route('/')
    def main_page():
        return send_file('git-deps.html')

    @webserver.route('/tip-template.html')
    def tip_template():
        return send_file('tip-template.html')

    @webserver.route('/test.json')
    def data():
        return send_file('test.json')

    def make_subdir_handler(subdir):
        def subdir_handler(filename):
            path = safe_join(root, subdir)
            path = safe_join(path, filename)
            if os.path.exists(path):
                return send_file(path)
            else:
                flask.abort(404)
        return subdir_handler

    for subdir in ('node_modules', 'css', 'js'):
        fn = make_subdir_handler(subdir)
        route = '/%s/<path:filename>' % subdir
        webserver.add_url_rule(route, subdir + '_handler', fn)

    ##########################################################
    # Dynamic content

    def json_error(status_code, error_class, message, **extra):
        json = {
            'status': status_code,
            'error_class': error_class,
            'message': message,
        }
        json.update(extra)
        response = jsonify(json)
        response.status_code = status_code
        return response

    @webserver.route('/options')
    def send_options():
        client_options = options.__dict__
        client_options['repo_path'] = os.getcwd()
        return jsonify(client_options)

    @webserver.route('/deps.json/<commitish>')
    def deps(commitish):
        detector = DependencyDetector(options)
        listener = JSONDependencyListener(options)
        detector.add_listener(listener)

        try:
            root_commit = detector.get_commit(commitish)
        except InvalidCommitish as e:
            return json_error(
                422, 'Invalid commitish',
                "Could not resolve commitish '%s'" % commitish,
                commitish=commitish)

        detector.find_dependencies(commitish)
        json = listener.json()
        json['root'] = {
            'commitish': commitish,
            'sha1': root_commit.hex,
            'abbrev': GitUtils.abbreviate_sha1(root_commit.hex),
        }
        return jsonify(json)

    # We don't want to see double-decker warnings, so check
    # WERKZEUG_RUN_MAIN which is only set for the first startup, not
    # on app reloads.
    if options.debug and not os.getenv('WERKZEUG_RUN_MAIN'):
        print("!! WARNING!  Debug mode enabled, so webserver is completely "
              "insecure!")
        print("!! Arbitrary code can be executed from browser!")
        print()
    webserver.run(port=options.port, debug=options.debug, host=options.bindaddr)
Beispiel #8
0
from flask import Flask
from os.path import join, split
from flask.ext.script import Manager
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.root_path = '/'.join(app.root_path.split('/')[:-1])
app.config.from_object('deanthe.config.DevelopmentConfig')

url = app.add_url_rule
manager = Manager(app)
db = SQLAlchemy(app)
Beispiel #9
0
    def __call__(self, environ, start_response):
        # only set PATH_INFO for older versions of Lighty or if no
        # server software is provided.  That's because the test was
        # added in newer Werkzeug versions and we don't want to break
        # people's code if they are using this fixer in a test that
        # does not set the SERVER_SOFTWARE key.
        if 'SERVER_SOFTWARE' not in environ or \
           environ['SERVER_SOFTWARE'] < 'lighttpd/1.4.28':
            environ['PATH_INFO'] = environ.get('SCRIPT_NAME', '') + \
                environ.get('PATH_INFO', '')
        environ['SCRIPT_NAME'] = self.app_root.rstrip('/')
        return self.app(environ, start_response)

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

opt = {}
parser = OptionParser()
parser.add_option('-d', '--debug', dest='DEBUG', action='store_true',
            help='Provides debug output when unhandled exceptions occur.')
parser.add_option('-v', '--verbose', dest='VERBOSE', action='store_true',
            help='Provides verbose output for what is being done.')
parser.add_option('-s', '--student', dest='STUDENT', action='store_true',
            help='Connects to the student LDAP instead of the staff.')
cmd_opt, junk = parser.parse_args()

c = ConfigFile(app.root_path + '/config.ini')
keys = c.getsection('Refdesk') 
for key in keys:
    opt[key] = keys[key]
Beispiel #10
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(app.config["THEME"] + "/main.html", 
Beispiel #11
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 = []
    
from flask import Flask
from flask import render_template, url_for

import os
import os.path

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

progs = ["approximate", "precipitation", "feature_view", "clusters", "voronoi"]

cache = {}

@app.route("/viz/<prog>")
def viz(prog):
    if prog not in progs:
        raise Exception("Bad program")
    return render_template(prog + ".html")

@app.route("/precipitation")
def precipitation():
    import scipy.io
    import json

    cache_name = "precipitation"

    if cache_name in cache:
        return cache[cache_name]

    matrices = scipy.io.loadmat("gen/precip/201505.mat")
    matrix = matrices["precip"]
Beispiel #13
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 #14
0
    try:
        return cache[f]
    except KeyError:
        try:
            cache[f] = DomainLoader(filename=fname, cachefile=fname+"_cache.pkl").domain
        except:
            try:
                cache[f] = AIMind(filename=fname, cachefile=fname+"_cache.pkl").domain
            except Exception as e:
                print(e)
                print("cannot load file %s, ignoring"%fname)

        return cache[f]

app = Flask(__name__)
app.root_path = os.path.dirname(sys.executable) if getattr(sys, 'frozen', False) else os.path.dirname(__file__)

def clean(x, form):
    if x is None:
        return "No analogy could be made."
    if form.get('sanitize') == "true":
        x = x.replace("<","&lt;")
        x = x.replace(">","&gt;")
    if form.get('clear') == "true":
        x = x.replace("<","")
        x = x.replace(">","")
    return x


@app.route('/')
def index():
Beispiel #15
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 #16
0
from plume.user import UserBackend
from plume.utils import get_path, split_path
from pytz import common_timezones


def filter_render(data, toc=False):
    return Markup(render_document(data, toc))


def filter_strong(data):
    return Markup("<strong>%s</strong>" % data)


# Create application
app = Flask("__main__", static_folder=STATIC_DIR, template_folder=TEMPLATE_DIR)
app.root_path = ROOT_PATH

app.jinja_options["extensions"].append("jinja2.ext.do")

app.jinja_env.filters.update({"render": filter_render, "strong": filter_strong})


# Load secret key
file_path = os.path.join(CONF_DIR, "plume.secret")

if not os.path.exists(file_path):
    raise Exception("secret file %s is missing\n" % file_path)

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:
Beispiel #17
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():
    return send_from_directory(app.root_path + 'app', 'upload.html')
Beispiel #18
0
import json
import os
import shelve

import requests
from flask import Flask, session
from flask.ext.mako import MakoTemplates
from flask.ext.githubhook import GitHubHook
from memoize import Memoizer


app = Flask(__name__, static_url_path='')
app.root_path = os.path.abspath(os.path.join(__file__, '..'))
app.instance_path = os.path.abspath(os.path.join(__file__, '..', '..', 'var'))

config_path = os.path.join(app.instance_path, 'config.py')
if os.path.exists(config_path):
    locals_ = {}
    execfile(config_path, locals_, app.config)
    app.config.update(locals_)
else:
    print 'Could not find var/config.py'

app.config['SECRET_KEY'] = app.config.get('SECRET_KEY') or 'monkey'

app.config['GITHUB_ALLOWED_OWNERS'] = set(['mikeboers', 'FluentImage'])
app.debug = app.debug or bool(os.environ.get('DEBUG'))

githubhook = GitHubHook(app=app, url_prefix='/hook')
mako = MakoTemplates(app)
Beispiel #19
0
import os
import json
from flask import Flask, render_template, jsonify, send_from_directory, request
from flask_swagger import swagger
from localstack.constants import VERSION
from localstack.utils.aws.aws_stack import Environment
from localstack.utils import common
from localstack.dashboard import infra


root_path = os.path.dirname(os.path.realpath(__file__))
web_dir = root_path + '/web/'

app = Flask('app', template_folder=web_dir)
app.root_path = root_path


@app.route('/swagger.json')
def spec():
    swag = swagger(app)
    swag['info']['version'] = VERSION
    swag['info']['title'] = 'AWS Resources Dashboard'
    return jsonify(swag)


@app.route('/graph', methods=['POST'])
def get_graph():
    """ Get deployment graph
        ---
        operationId: 'getGraph'
        parameters:
Beispiel #20
0
import os

from flask import Flask
from monitoring.views.base import IndexView

app = Flask(__name__, static_folder='static')
app.config.from_pyfile('flask.conf.py')

app.root_path = os.path.join(app.root_path, 'monitoring')

app.add_url_rule('/', view_func=IndexView.as_view('index'))

app.debug = True
Beispiel #21
0
pyximport.install()
import os, sys
from orbit.framing import TEXT
from flask import Flask, render_template
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

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')

class EchoState(State):
	def onNewConnection(self, ws):
		ws.opcode = TEXT

	def onUpdate(self, ws, opcode, data, fin):
		print 'Opcode: %s' % opcode
		print 'Data: %s' % data
		ws.write(cgi.escape(data).encode('utf8'))

	def onEndConnection(self, ws):
		self.transaction.finish()
Beispiel #22
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 #23
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 #24
0
from gevent import wsgi
from flask import Flask, make_response, request, render_template

from locust import runners
from locust.cache import memoize
from locust.runners import MasterLocustRunner
from locust.stats import median_from_dict
from locust import __version__ as version

logger = logging.getLogger(__name__)

DEFAULT_CACHE_TIME = 2.0

app = Flask(__name__, static_url_path='/meruem/static')
app.debug = True
app.root_path = os.path.dirname(os.path.abspath(__file__))


@app.route('/meruem')
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,
        is_distributed=is_distributed,
        slave_count=slave_count,
Beispiel #25
0
import os

import jinja2
from flask import Flask
from flask_sockets import Sockets

CURRENT_DIRECTORY = os.path.dirname(__file__)
STATIC_FOLDER = os.path.join("twidder", "static")
MEDIA_FOLDER = os.path.join("twidder", "media")

ALLOWED_MEDIA = {"jpg", "png", "mp4", "mp3", "wav"}

app = Flask(__name__, static_url_path='', static_folder=STATIC_FOLDER)
app.config["SECRET_KEY"] = os.urandom(24)
app.config['UPLOAD_FOLDER'] = MEDIA_FOLDER
app.root_path = os.getcwd()

app.jinja_loader = jinja2.ChoiceLoader([
    app.jinja_loader,
    jinja2.FileSystemLoader(os.path.join(CURRENT_DIRECTORY, "static"))
])

sockets = Sockets(app)

from . import twidder
Beispiel #26
0
def get():
    global _app
    if not _app:
        _app = Flask(__name__)
        _app.root_path = get_parent_dir(_app.root_path)
    return _app
Beispiel #27
0
    return os.path.abspath(__file__)[:-13]

# Set the rundir
rundir = get_rundir()

# Include paths
sys.path.insert(0, rundir)
sys.path.insert(0, os.path.join(rundir, 'lib'))

# Create Flask instance
from flask import Flask
app = Flask(__name__)

# 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():
    """All modules that are available in Maraschino are at this point imported."""
    import modules.applications
    import modules.controls
Beispiel #28
0
from flask import Flask, render_template, abort, send_file
import os.path as path
import os
import re
import vlc
from subprocess import call, Popen
app = Flask(__name__)
app.root_path = path.abspath(path.dirname(__file__)).replace("\\","/")
app.media_path = app.root_path+"/content/local-media"#path.join(app.root_path, "content", "local-media")
#create custom 404 page for friendly faults and then have an ajax for internet connection check (succeed reload old url, failure report)
streams = [ ('localMedia', 'images/local-media-icon.png'),
		('youtube', 'images/youtube-icon.png')  ]
		
i = vlc.Instance("--video-on-top")
mediaPlayer = i.media_player_new()
app.download = None

@app.route("/")
#return the app itself
def index():
	return render_template("2col_base.html")
	
	
@app.route("/mediaPlayerAction/<string:action>")
def mediaPlayerAction(action):
	if action == "play":
		if mediaPlayer.get_state() == vlc.State.Ended:
			mediaPlayer.stop()
		if mediaPlayer.get_state() == vlc.State.Stopped:
			mediaPlayer.play()
		else:
Beispiel #29
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 #30
0
import serveconf
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):
		from cStringIO import StringIO
		if s is not None: