def test_bottle(path, method='GET', form={}):
			from bottle import TEMPLATE_PATH
			TEMPLATE_PATH.insert(0, '../views')
			TEMPLATE_PATH.insert(0, 'views')

			app = XXX_mywebapp.XXX_setup_web_interface()

			data = '&'.join(['%s=%s' % (k, v) for k, v in form.items()])

			from bottle import run, CGIServer
			from StringIO import StringIO
			import os
			os.environ['REQUEST_METHOD'] = method
			os.environ['PATH_INFO'] = path
			os.environ['SCRIPT_NAME'] = path
			os.environ['QUERY_STRING'] = ''
			os.environ['SERVER_PROTOCOL'] = 'HTTP/1.1'
			os.environ['CONTENT_LENGTH'] = str(len(data))

			old_stdout = sys.stdout
			sys.stdout = new_stdout = StringIO()

			old_stdin = sys.stdin
			sys.stdin = new_stdin = StringIO(data)
			new_stdin.seek(0)

			run(app, server=CGIServer)

			sys.stdin = old_stdin
			sys.stdout = old_stdout

			return new_stdout.getvalue()
Beispiel #2
0
        def test_bottle(path, method='GET', form={}):
            from bottle import TEMPLATE_PATH
            TEMPLATE_PATH.insert(0, '../views')
            TEMPLATE_PATH.insert(0, 'views')

            app = XXX_mywebapp.XXX_setup_web_interface()

            data = '&'.join(['%s=%s' % (k, v) for k, v in form.items()])

            from bottle import run, CGIServer
            from StringIO import StringIO
            import os
            os.environ['REQUEST_METHOD'] = method
            os.environ['PATH_INFO'] = path
            os.environ['SCRIPT_NAME'] = path
            os.environ['QUERY_STRING'] = ''
            os.environ['SERVER_PROTOCOL'] = 'HTTP/1.1'
            os.environ['CONTENT_LENGTH'] = str(len(data))

            old_stdout = sys.stdout
            sys.stdout = new_stdout = StringIO()

            old_stdin = sys.stdin
            sys.stdin = new_stdin = StringIO(data)
            new_stdin.seek(0)

            run(app, server=CGIServer)

            sys.stdin = old_stdin
            sys.stdout = old_stdout

            return new_stdout.getvalue()
Beispiel #3
0
    def __init__(self, config=None, args=None):
        # Init config
        self.config = config

        # Init args
        self.args = args

        # Init stats
        # Will be updated within Bottle route
        self.stats = None

        # cached_time is the minimum time interval between stats updates
        # i.e. HTTP/Restful calls will not retrieve updated info until the time
        # since last update is passed (will retrieve old cached info instead)
        self.timer = Timer(0)

        # Load configuration file
        self.load_config(config)

        # Init Bottle
        self._app = Bottle()
        # Enable CORS (issue #479)
        self._app.install(EnableCors())
        # Password
        if args.password != '':
            self._app.install(auth_basic(self.check_auth))
        # Define routes
        self._route()

        # Path where the statics files are stored
        self.STATIC_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static/public')

        # Paths for templates
        TEMPLATE_PATH.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static/templates'))
Beispiel #4
0
    def __init__(self, port, hbusMaster):
        """Class constructor
           @param port HTTP port
           @param hbusMaster main master object reference for manipulation
           """

        try:
            views = pkg_resources.resource_filename("hbussd",
                                                    "data/views")
            # distribution found!
            TEMPLATE_PATH.insert(0, views)

            self.static_file_path =\
                pkg_resources.resource_filename("hbussd",
                                                "data/web_static")
        except pkg_resources.DistributionNotFound:
            pass
        
        ##Server port
        self.port = port
        ##main master object
        self.hbusMaster = hbusMaster
        ##Minimum object level visible on web interface
        self.objectLevel = 0

        #get logger
        self.logger = logging.getLogger('hbussd.hbusweb')
    def __init__(self, infoscreen, folder, apiport):
        super(InfoScreenWebServer, self).__init__()

        # We need access to the infoscreen base object in order to manipulate it
        self.infoscreen = infoscreen.base

        # Get the folder path so we can build paths to templates etc.
        self.folder = folder

        # Set up the api
        self.api = "http://localhost:{}/api/".format(apiport)

        # Set up templates
        tpls = os.path.join(self.folder, "web", "templates")
        TEMPLATE_PATH.insert(0, tpls)

        # Initialise dictionary for custom web pages provided by screens
        self.custom_screens = {}

        # Build the dictionary of available screens
        self.process_plugins()

        # Define our routes
        self.route("/configure/<screen>", callback=self.update_config, method="GET")
        self.route("/configure/<screen>", callback=self.save_config, method="POST")
        self.route("/view/<screen>", callback=self.view)
        self.route("/", callback=self.list_screens, method=["GET", "POST"])

        # See if there are any custom screens
        self.add_custom_routes()
    def __init__(self, infoscreen, folder, apiport):
        super(InfoScreenWebServer, self).__init__()

        # We need access to the infoscreen base object in order to manipulate it
        self.infoscreen = infoscreen.base

        # Get the folder path so we can build paths to templates etc.
        self.folder = folder

        # Set up the api
        self.api = "http://localhost:{}/api/".format(apiport)

        # Set up templates
        tpls = os.path.join(self.folder, "web", "templates")
        TEMPLATE_PATH.insert(0, tpls)

        # Initialise dictionary for custom web pages provided by screens
        self.custom_screens = {}

        # Build the dictionary of available screens
        self.process_plugins()

        # Define our routes
        self.route("/configure/<screen>",
                   callback=self.update_config,
                   method="GET")
        self.route("/configure/<screen>",
                   callback=self.save_config,
                   method="POST")
        self.route("/view/<screen>", callback=self.view)
        self.route("/", callback=self.list_screens, method=["GET", "POST"])

        # See if there are any custom screens
        self.add_custom_routes()
Beispiel #7
0
def get_images_of_this_month():
    client = DropboxClient(DROPBOX_TOKEN)
    manager = DatastoreManager(client)
    datastore = manager.open_default_datastore()

    offer_table = datastore.get_table('offers')
    offers = offer_table.query()

    images_to_show = []
    for offer in offers:  # dropbox.datastore.Record
        name = offer.get('offerName')
        begin = datetime.datetime.strptime(offer.get('begin'),
                                           "%Y-%m-%d").date()
        end = datetime.datetime.strptime(offer.get('end'), "%Y-%m-%d").date()
        begin_month = '{:02d}'.format(begin.month)
        end_month = '{:02d}'.format(end.month)
        current_month = '{:02d}'.format(datetime.datetime.now().month)
        year = '{:4d}'.format(datetime.datetime.now().year)
        if current_month == begin_month or current_month == end_month:
            # belong to the current month, so we show it
            images_to_show.append(name)

    images_paths = download_and_save_images(images_to_show, year,
                                            current_month)

    TEMPLATE_PATH.insert(0, 'pages/')
    return template('galeria', images=images_paths)
Beispiel #8
0
def main():
    # Set global variables from the command line
    global blogFolder
    global s3Bucket
    
    blogFolder = sys.argv[1]
    s3Bucket = sys.argv[2]
    
    # For any folders that are reserved by Aeriter
    if blogFolder == "templates":
        exit()

    # Read configuration for the blog
    global config
    config = ConfigParser.ConfigParser()
    config.read(blogFolder + '/settings.cfg')
    
    # You'll want to do this at the beginning of the process
    shutil.rmtree(blogFolder + '/rendered', ignore_errors=True)
    make_sure_path_exists(blogFolder + '/rendered')
    
    # Ensure the correct template is being rendered
    TEMPLATE_PATH.insert(0,'./views/%s' % config.get("Settings", "theme"))
    
    # This processes the individual .md files and places them in the "rendered" folder under
    # their respective relative paths.
    global postMetaData
    postMetaData = []
    for file in glob.glob(blogFolder + "/*.md"):
        if file[-9:] == '-draft.md':
            continue
        postMetaData.append(renderPost(file, blogFolder, config))
    genNavPages(postMetaData, blogFolder, config)
    sendToS3(s3Bucket, blogFolder)
Beispiel #9
0
def recommendations():
    TEMPLATE_PATH.insert(0, '')
    s = session()

    # 1. Classify labeled news
    rows = s.query(News).filter(News.label != None).all()

    X, y = [], []
    for row in rows:
        X.append(row.title)
        y.append(row.label)

    X = [clean(x).lower() for x in X]

    model = NaiveBayesClassifier()
    model.fit(X, y)

    # 2. Get unlabeled news
    new_rows = s.query(News).filter(News.label == None).all()

    # 3. Get predictions
    marked = []
    for row in new_rows:
        marked.append((model.predict(row.title.split()), row))

    # 4. Print ranked table
    return template('news_ranked', rows=marked)
Beispiel #10
0
    def test_wsgi_XXX_Test_Name(self):
        '''Test of web interface via WSGI interface'''

        from webtest import TestApp
        from bottle import TEMPLATE_PATH
        TEMPLATE_PATH.insert(0, '../views')
        TEMPLATE_PATH.insert(0, 'views')
        app = XXX_mywebapp.XXX_setup_web_interface()
        harness = TestApp(app)
Beispiel #11
0
 def setUp(self):
     from webtest import TestApp
     from bottle import TEMPLATE_PATH
     TEMPLATE_PATH.insert(0, '../')
     self.app = controller.build_application()
     self.harness = TestApp(self.app)
     self.username = "******"
     self.password = "******"
     self.wrong_password = "******"
	def test_wsgi_XXX_Test_Name(self):
		'''Test of web interface via WSGI interface'''

		from webtest import TestApp
		from bottle import TEMPLATE_PATH
		TEMPLATE_PATH.insert(0, '../views')
		TEMPLATE_PATH.insert(0, 'views')
		app = XXX_mywebapp.XXX_setup_web_interface()
		harness = TestApp(app)
Beispiel #13
0
def start(host="localhost", port=8080):
    """
    Run the web server
    """
    # set TEMPLATE_PATH to use an absolute path pointing to our directory
    abs_app_dir_path = os.path.dirname(os.path.realpath(__file__))
    abs_views_path = os.path.join(abs_app_dir_path, 'templates')
    TEMPLATE_PATH.insert(0, abs_views_path)
    run(host=host, port=port)
    print(f"Running web-server on http://{host}:{port}/")
Beispiel #14
0
def add_plugin_templates_path(path):
    global env
    tmpl_path = make_templates_from_plugin_path(path)
    if os.path.exists(tmpl_path):
        logging.debug("Templates directory found for this plugin [%s]" % tmpl_path)
        template_path.append(tmpl_path)  # for webhooks
        TEMPLATE_PATH.insert(0, tmpl_path)  # for webviews
        env = Environment(loader=FileSystemLoader(template_path))  # ditch and recreate a new templating environment
        return
    logging.debug("No templates directory found for this plugin [Looking for %s]" % tmpl_path)
Beispiel #15
0
def add_plugin_templates_path(path):
    global env
    tmpl_path = make_templates_from_plugin_path(path)
    if os.path.exists(tmpl_path):
        log.debug("Templates directory found for this plugin [%s]" % tmpl_path)
        template_path.append(tmpl_path)  # for webhooks
        TEMPLATE_PATH.insert(0, tmpl_path)  # for webviews
        # Ditch and recreate a new templating environment
        env = Environment(loader=FileSystemLoader(template_path))
        return
    log.debug("No templates directory found for this plugin [Looking for %s]" % tmpl_path)
Beispiel #16
0
def __update_template_path():
    # Sometimes, when caching templates bottle doesn't clear the faulty
    # templates and the error persists even upon restarting the app.
    # The solution is to clear the templates explicitly with this statement:
    TEMPLATES.clear()

    for m in registered_methods:
        method_path = unicode('./{0}/{1}/'.format(config.FP_SUBDIR, m.subdir))
        if method_path not in TEMPLATE_PATH:
            TEMPLATE_PATH.insert(0, method_path)

    logger.info('updated TEMPLATE_PATH')
    def setUp(self):
        dbwrap.connect(connect='sqlite:///:memory:')
        dbwrap.Base.metadata.create_all()

        db = dbwrap.session()
        model.create_sample_data()
        self.db = db

        from webtest import TestApp
        from bottle import TEMPLATE_PATH
        TEMPLATE_PATH.insert(0, '../views')
        self.app = website.build_application()
        self.harness = TestApp(self.app)
Beispiel #18
0
def start():
    parser = ArgumentParser(prog=sys.argv[0],
                            description="Pollux'NZ City configurator")

    parser.add_argument("-V",
                        '--version',
                        action='version',
                        version="%(prog)s version 0")

    parser.add_argument("-D",
                        "--debug",
                        dest="debug",
                        action="store_true",
                        default=False,
                        help="Debug mode")
    parser.add_argument(
        "-p",
        "--path",
        dest="path",
        default="/etc/pollux",
        help='path to configuration directory. e.g. /etc/pollux/')
    parser.add_argument("-l",
                        "--lib",
                        dest="lib_path",
                        default="/usr/lib/pollux",
                        help='Directory where the modules lay')
    # HOST ARGUMENT
    parser.add_argument("-H",
                        "--host",
                        dest="host",
                        default='0.0.0.0',
                        help='Host to serve the web application on.')
    # PORT ARGUMENT
    parser.add_argument(
        "-P",
        "--port",
        dest="port",
        default='8080',
        help='Port to be used for serving the web application.')

    args = parser.parse_args(sys.argv[1:])

    TEMPLATE_PATH.insert(0, pollux.views.__path__[0])

    config = Configuration(args.path + "/", args.lib_path)
    sensors = Sensors(args.path + "/")

    install(config)
    install(sensors)

    return args
Beispiel #19
0
def skin_check(conn):
    curs = conn.cursor()
    skin = './views/acme/'
    try:
        curs.execute('select data from other where name = "skin"')
        skin_exist = curs.fetchall()
        if (skin_exist):
            if (os.path.exists(
                    os.path.abspath('./views/' + skin_exist[0][0] +
                                    '/index.tpl')) == 1):
                skin = './views/' + skin_exist[0][0] + '/'
    except:
        pass

    TEMPLATE_PATH.insert(0, skin)
Beispiel #20
0
    def __init__(self):

        self.project_name = "Watering System"

        board_name = HARDWARE_CONFIG.kit
        board_module = "{0}.hardware.{1}".format(__package__, board_name)
        board_class_name = "{0}Board".format(board_name.capitalize())
        self.board = getattr(import_module(board_module), board_class_name)()
        GPIO.setmode(GPIO.BOARD)

        self.schedule = {}

        self.water_level = []

        resource_package = __name__
        package_root = resource_filename(resource_package, "")
        TEMPLATE_PATH.insert(0, package_root)

        self.server = Bottle()
        self.server.route("/", callback=self.serve_index)
        self.server.route("/styles.css", callback=self.serve_css)
        self.server.route("/on", callback=self.get_on)
        self.server.route("/off", callback=self.get_off)
        self.server.route("/schedule",
                          method="GET",
                          callback=self.get_schedule)
        self.server.route("/schedule",
                          method="PUT",
                          callback=self.put_schedule)

        GPIO.setup(self.board.FLOW_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.add_event_detect(self.board.FLOW_PIN,
                              GPIO.BOTH,
                              callback=self.flow_changed,
                              bouncetime=300)

        GPIO.setup(self.board.PUMP_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.add_event_detect(self.board.PUMP_PIN,
                              GPIO.BOTH,
                              callback=self.pump_changed,
                              bouncetime=300)

        self.monitor_water_level_job = SCHEDULER.add_job(
            self.monitor_water_level, "interval", seconds=10)

        self.monitor_flow_job = SCHEDULER.add_job(self.monitor_flow,
                                                  "interval",
                                                  seconds=10)
Beispiel #21
0
def work(p,rp,nonesym,timec,timebg,btc,btbg,etc,etbg,showetflag,showbtflag):
    global port, static_path, nonesymbol, timecolor, timebackground, btcolor, btbackground, etcolor, etbackground, showbt, showet
    port = p
    static_path = rp
    nonesymbol = nonesym
    timecolor = timec
    timebackground = timebg
    btcolor = btc
    btbackground = btbg
    etcolor = etc
    etbackground = etbg
    showet = showetflag
    showbt = showbtflag
    TEMPLATE_PATH.insert(0,rp)
    s = WSGIServer(("0.0.0.0", p), default_app(), handler_class=WebSocketHandler)
    s.serve_forever()
Beispiel #22
0
def work(p,rp,nonesym,timec,timebg,btc,btbg,etc,etbg,showetflag,showbtflag):
    global port, static_path, nonesymbol, timecolor, timebackground, btcolor, btbackground, etcolor, etbackground, showbt, showet
    port = p
    static_path = rp
    nonesymbol = nonesym
    timecolor = timec
    timebackground = timebg
    btcolor = btc
    btbackground = btbg
    etcolor = etc
    etbackground = etbg
    showet = showetflag
    showbt = showbtflag
    TEMPLATE_PATH.insert(0,rp)
    s = WSGIServer(("0.0.0.0", p), default_app(), handler_class=WebSocketHandler)
    s.serve_forever()
Beispiel #23
0
def build_application(env='dev'):
    app = Bottle()

    # with app:
    # Our application object is now the default
    # for all shortcut functions and decorators

    nlp = get_stanford_nlp()

    say_words = read_say_words()

    with open("web/config.js", "w") as f:
        host = host_dict[env]
        f.write('getViewUrl = {{\n\turl:\'http://{}:{}\'\n}}'.format(host[0], host[1]))

    BaseTemplate.defaults['app'] = app  # XXX Template global variable
    TEMPLATE_PATH.insert(0, 'views')  # XXX Location of HTML templates

    #  XXX Routes to static content
    # @app.route('/<path:re:favicon.ico>')
    # @app.route('/static/<path:path>')
    # def static(path):
    #     'Serve static content.'
    #     return static_file(path, root='static/')

    #  XXX Index page
    @app.route('/')  # XXX URL to page
    @view('index')  # XXX Name of template
    def index():
        """
        :return:
        """
        return static_file('index.html', root=WEB_DIR)

    @app.route('/static/<filename:path>')
    def send_static(filename):
        return static_file(filename, root=WEB_DIR)

    @app.post('/views', name='view')
    def fetch_views():
        sentence = request.forms.getunicode('sentence')

        views = get_views(sentence, nlp, say_words)
        view_dict = [{"person": person, "verb": verb, "view": view} for person, verb, view in views]
        return json.dumps(view_dict)

    return app
Beispiel #24
0
    def __init__(self):
        debug(True)
        TEMPLATE_PATH.insert(0, './templates')
        logging.basicConfig(format='%(asctime)s: [%(levelname)s]: %(message)s',
                            datefmt='%Y-%m-%d %H:%M:%S',
                            level=logging.WARN)

        logging.getLogger('autobrowser').setLevel(logging.DEBUG)

        self.redis = redis.StrictRedis.from_url(self.REDIS_URL,
                                                decode_responses=True)

        self.app = default_app()

        self.init_routes()

        self.client = docker.from_env()
def start():
    parser = ArgumentParser(prog=sys.argv[0],
                description="Pollux'NZ City configurator")

    parser.add_argument("-V", '--version', action='version', version="%(prog)s version 0")
    
    parser.add_argument("-D",
                        "--debug",
                        dest="debug",
                        action="store_true",
                        default=False,
                        help="Debug mode")
    parser.add_argument("-p",
                        "--path",
                        dest="path",
                        default="/etc/pollux",
                        help='path to configuration directory. e.g. /etc/pollux/')
    parser.add_argument("-l",
                        "--lib",
                        dest="lib_path",
                        default="/usr/lib/pollux",
                        help='Directory where the modules lay')
    # HOST ARGUMENT
    parser.add_argument("-H",
                        "--host",
                        dest="host",
                        default='0.0.0.0',
                        help='Host to serve the web application on.')
    # PORT ARGUMENT
    parser.add_argument("-P",
                        "--port",
                        dest="port",
                        default='8080',
                        help='Port to be used for serving the web application.')
    
    args = parser.parse_args(sys.argv[1:])

    TEMPLATE_PATH.insert(0,pollux.views.__path__[0])

    config = Configuration(args.path+"/",args.lib_path)
    sensors = Sensors(args.path+"/")

    install(config)
    install(sensors)

    return args
Beispiel #26
0
    def __init__(self,
                 name=None,
                 arm=None,
                 panel=None,
                 log_level=INFO,
                 template_path="data/templates/",
                 static_path="data/static/",
                 resources_search_path=None):
        LogMixin.__init__(self, name=name, level=log_level)
        self.log_info('log level set to %s',
                      self.log_effective_level_as_string)

        if resources_search_path:
            self.log_info('processing resource search path :')
            for pkg in resources_search_path:
                self.log_info('+ ' + pkg)
                path = resource_filename(pkg, template_path)
                self.log_info('  + template path : %s', path)
                if path not in TEMPLATE_PATH:
                    if not os.path.isdir(path):
                        raise ValueError('path not found: ' + path)
                    TEMPLATE_PATH.insert(0, path)
                    self.log_info("    added to bottle.TEMPLATE_PATH")
                else:
                    self.log_info("    already in bottle.TEMPLATE_PATH")

                path = resource_filename(pkg, static_path)
                if path not in STATIC_PATH:
                    self.log_info('  + static path : %s', path)
                    if not os.path.isdir(path):
                        raise ValueError('path not found: ' + path)
                    STATIC_PATH.insert(0, path)
                    self.log_info("    added to STATIC_PATH")
                else:
                    self.log_info("    already in STATIC_PATH")

        Bottle.__init__(self)

        self.arm = arm
        self.panel = panel

        self.route('/help', 'GET', callback=self.get_help)
        self.route('/static/<filepath:path>',
                   'GET',
                   callback=self.serve_static)
Beispiel #27
0
def init(root="/home/isanz"):
    global ROOT
    global application
    global i18n
    TEMPLATE_PATH.insert(0, root)
    ROOT = root
    i18n_defaults(SimpleTemplate, request)
    #print >>sys.stderr, "Starting up, log=" + str(log) + " db=" + str(db)
    session_opts = {
        'session.type': 'file',
        'session.cookie_expires': True,
        'session.data_dir': './sessions',
        'session.auto': True
    }
    
    i18n =  I18NPlugin(domain='messages', default='en', locale_dir=ROOT+'colours/locale')
    app = I18NMiddleware(default_app(), i18n)
    application = SessionMiddleware(app, session_opts)
    def __init__(self, config=None, args=None):
        # Init config
        self.config = config

        # Init args
        self.args = args

        # Init stats
        # Will be updated within Bottle route
        self.stats = None

        # cached_time is the minimum time interval between stats updates
        # i.e. HTTP/RESTful calls will not retrieve updated info until the time
        # since last update is passed (will retrieve old cached info instead)
        self.timer = Timer(0)

        # Load configuration file
        self.load_config(config)

        # Set the bind URL
        self.bind_url = 'http://{}:{}/'.format(self.args.bind_address,
                                               self.args.port)

        # Init Bottle
        self._app = Bottle()
        # Enable CORS (issue #479)
        self._app.install(EnableCors())
        # Password
        if args.password != '':
            self._app.install(auth_basic(self.check_auth))
        # Define routes
        self._route()

        # Path where the statics files are stored
        self.STATIC_PATH = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), 'static/public')

        # Paths for templates
        TEMPLATE_PATH.insert(
            0,
            os.path.join(os.path.dirname(os.path.realpath(__file__)),
                         'static/templates'))
Beispiel #29
0
def runserver(port, ip, debug, dev=False):
    click.echo('Start server at: {}:{}'.format(ip, port))

    if dev and 'true' == str(dev).lower():
        # 设置运行环境
        os.environ['run_env'] = 'dev'
    # 加载bottle

    from app import settings
    from app.routes import Routes

    TEMPLATE_PATH.insert(0, settings.TEMPLATE_PATH)
    session_opts = {'session.type': 'file', 'session.auto': True}

    app = SessionMiddleware(Bottle(), session_opts)

    # Bottle Routes
    app.wrap_app.merge(Routes)

    @app.wrap_app.route('/assets/<path:path>', name='assets')
    def assets(path):
        yield static_file(path, root=settings.STATIC_PATH)

    run(app=app, host=ip, port=port, debug=debug, reloader=debug)
    def __init__(self):

        self.project_name = "Watering System"

        board_name = HARDWARE_CONFIG.kit
        board_module = "{0}.hardware.{1}".format(__package__, board_name)
        board_class_name = "{0}Board".format(board_name.capitalize())
        self.board = getattr(import_module(board_module), board_class_name)()

        self.schedule = {}

        self.moisture = []

        resource_package = __name__
        package_root = resource_filename(resource_package, "")
        TEMPLATE_PATH.insert(0, package_root)

        self.server = Bottle()
        self.server.route("/", callback=self.serve_index)
        self.server.route("/styles.css", callback=self.serve_css)
        self.server.route("/on", callback=self.get_on)
        self.server.route("/off", callback=self.get_off)
        self.server.route("/schedule",
                          method="GET",
                          callback=self.get_schedule)
        self.server.route("/schedule",
                          method="PUT",
                          callback=self.put_schedule)

        self.monitor_moisture_job = SCHEDULER.add_job(self.monitor_moisture,
                                                      "interval",
                                                      minutes=5)

        self.monitor_flow_job = SCHEDULER.add_job(self.monitor_flow,
                                                  "cron",
                                                  hour="0-23")
Beispiel #31
0
import os
import jinja2
from google.appengine.api import memcache
from jinja2 import Template
from bottle import Bottle, request, response, static_file
from bottle import TEMPLATE_PATH as T

PROJECT_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)))
TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'templates')
JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(TEMPLATE_PATH),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)
STATIC_PATH = os.path.join(PROJECT_PATH, 'assets')

T.insert(0, TEMPLATE_PATH)

app = Bottle()


@app.route('/')
def index():
    def file_exist(file):
        return os.path.isfile("{}/images/logo/{}.png".format(
            STATIC_PATH, file))

    langs = memcache.get('langs')
    if not langs:
        langs = os.listdir("./vim_template/langs")
        memcache.add('langs', langs, 3600)
Beispiel #32
0
                    worker_pelican,\
                    worker_shootup


# Global Variables, Bottle Settings
################################################
config_path = os.path.join(os.path.dirname(__file__),
                            '../../config.json')
with open(config_path) as config_file:
    config = json.load(config_file)
    db_path = config['basket']['path']
    engine = create_engine(db_path)
    Session = sessionmaker(bind=engine)
    DB = Session()

TEMPLATE_PATH.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__),
                        'views')))
redis_conn = Redis()
Q = Queue(connection=redis_conn)


# Static Resources
################################################
@route('/static/<filename:path>')
def send_static(filename):
    return static_file(filename, root=os.path.join(os.path.dirname(__file__),
                        'static/'))


# Pages
################################################
@route('/')
Beispiel #33
0
from bottle import Bottle, TEMPLATE_PATH
from bottle.ext import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
engine = create_engine('sqlite:///database.db', echo=True)

app = Bottle()
TEMPLATE_PATH.insert(0, 'app/views/')
plugin = sqlalchemy.Plugin(engine,
                           Base.metadata,
                           keyword='db',
                           create=True,
                           commit=True,
                           use_kwargs=False)

app.install(plugin)

from app.controllers import default
from app.models import tables
Beispiel #34
0
"Initialize demo bottle application"

import logging
import logging.config
from bottle import Bottle, request, TEMPLATE_PATH
from rackspace_app import config

APP = Bottle()
TEMPLATE_PATH.insert(0, '/home/umeshbhaskaran/r_demo/bottle/rackspace_app/templates')
# Loading Configurations
APP.config.update(config.Config.__dict__)

# Configuring logger

LOGGER = logging.getLogger('rackspace_app')
HANDLER = logging.FileHandler('/tmp/rackspace_app.log')
FORMATTER = logging.Formatter(
        '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(message)s')
HANDLER.setFormatter(FORMATTER)
LOGGER.addHandler(HANDLER)
LOGGER.setLevel(logging.DEBUG)
Beispiel #35
0
import logging
from json import dumps
import sys
import commands
from datetime import datetime
import os
import re

# Logging First!
logging.basicConfig(format='localhost - - [%(asctime)s] %(message)s', level=logging.DEBUG)
log = logging.getLogger("bottle")

# Basic Vars
INSTALLDIR = '/app'
APPDIR = INSTALLDIR #+ '/bottle' #os.path.dirname(sys.argv[0])
TEMPLATE_PATH.insert(0, APPDIR +'/views')
dbfile = APPDIR + '/bottle.db'
d = {}
aaa = Cork(APPDIR + '/auth')

__version__ = '0.9.0'
osversion = commands.getoutput('uname') + " " + commands.getoutput('uname -r')

d['version'] = __version__
d['osversion'] = osversion

# Enable bottle debug logging - is this even useful?
debug(True)

# Create Bottle instance
rootapp = Bottle()
Beispiel #36
0
import bottle_session
from bottle import Bottle, TEMPLATE_PATH
from bottle.ext import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
engine = create_engine('sqlite:///database.db', echo=True)

app = Bottle()
TEMPLATE_PATH.insert(0, 'app/views/')
plugin = sqlalchemy.Plugin(
    engine,
    Base.metadata,
    keyword='db',
    create=True,
    commit=True,
    use_kwargs=False
)
plugin_session = bottle_session.SessionPlugin(cookie_lifetime=120)

app.install(plugin)
app.install(plugin_session)

from app.controllers import default
from app.models import tables
Beispiel #37
0
@url https://github.com/fgaim
"""

import os
import json
from datetime import datetime

from bottle import Bottle, TEMPLATE_PATH, template, response

from . import utils
from . import core

app = Bottle()
abs_path = os.path.dirname(os.path.realpath(__file__))
abs_views_path = os.path.join(abs_path, 'views')
TEMPLATE_PATH.insert(0, abs_views_path)

EXCLUDE_SELF = False  # Do not report to `/gpustat` calls.


@app.route('/')
def index():
    gpustats = core.all_gpustats()
    now = datetime.now().strftime('Updated at %Y-%m-%d %H-%M-%S')
    return template('index', gpustats=gpustats, update_time=now)


@app.route('/gpustat', methods=['GET'])
def report_gpustat():
    """
    Returns the gpustat of this host.
Beispiel #38
0
#coding='utf8'
from bottle import error, route, static_file, debug, run, request, response, template, TEMPLATE_PATH, PasteServer
#from gevent import monkey; monkey.patch_all()
#from time import sleep
import RPi.GPIO as GPIO

GPIO_OUT = 12
def light_init():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(GPIO_OUT, GPIO.OUT)

debug(True)
TEMPLATE_PATH.insert(0, './')

@error(403)
def mistake403(code):
  return 'The parameter you passed has the wrong format!'

@error(404)
def mistake404(code):
  return 'Sorry, this page does not exist!'

@route('/stat/<filepath:path>')
def static(filepath):   
    return static_file(filepath, root='./stat/')

@route('/')
def light_html():   
    return template('light')

@route('/light')
Beispiel #39
0
import os
import config
from bottle import TEMPLATE_PATH, static_file, request, response,\
    template, redirect

TEMPLATE_PATH.insert(0, os.path.join(os.path.dirname(__file__), './templates'))
from aiobottle import AsyncBottle
app = AsyncBottle()
from . import bottle_login

login_plugin = bottle_login.Plugin()
app.install(login_plugin)

from . import views

from beaker.middleware import SessionMiddleware
session_opts = {
    'session.type': 'file',
    'session.cookie_expires': 7 * 24 * 60 * 60,
    'session.data_dir': 'run',
    'session.auto': True
}

server = SessionMiddleware(app, session_opts)
Beispiel #40
0
import bottle
from bottle import debug, error, get, post, request, response, route, run, static_file, template, TEMPLATE_PATH
import json
import operator
from beaker.middleware import SessionMiddleware
import sys
sys.path.insert(0, './lib/')
import crawler_db
import env_server
import google_authenticator

TEMPLATE_PATH.insert(0,'./views/')

# GLOBAL
URLS_PER_PAGE = 10

session_opts = {
        'session.type': 'file',
        'session.cookie_expires': 300,
        'session.data_dir': './data',
        'session.auto': True
        }
app = SessionMiddleware(bottle.app(), session_opts)


@error(404)
def error404(error):
    output = template('error_page')
    return output

Beispiel #41
0
import requests
import jinja2
from jinja2 import Template
from bottle import Bottle, request, response, static_file
from bottle import TEMPLATE_PATH as T


PROJECT_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)))
TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'views')
JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(TEMPLATE_PATH),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)
STATIC_PATH = os.path.join(PROJECT_PATH, 'assets')

T.insert(0, TEMPLATE_PATH)

app = Bottle()


@app.route('/')
def index():

    def file_exist(file):
        return os.path.isfile("{}/images/logo/{}.png".format(
            STATIC_PATH, file))

    template = JINJA_ENVIRONMENT.get_template('index.html')
    url = "https://api.github.com/repos/avelino/.vimrc/contents/langs"
    langs = [g["name"] for g in json.loads(requests.get(url).text)]
Beispiel #42
0
nameRe = re.compile ("^[a-zA-Z0-9_-]+$")

configfile = file(os.getenv("NIXPASTE_CONFIG", "config.json"), "r")
config = json.load(configfile)
configfile.close()

# TypeError: Key has type <type 'unicode'> (not a string)
for k,v in config.items():
	del config[k]
	config[str(k)] = v

app = Bottle()
app.config.update (config)

TEMPLATE_PATH.insert(0, os.path.abspath (config["VIEWS"]))

def mergeConfig(**v):
	c = copy(config)
	c.update(v)
	return c

class Storage:
	def __init__ (self, config):
		self.config = config
		
	def hashname (self, num):
		h = hashlib.pbkdf2_hmac('sha256', str(num), self.config["SALT"], 200000, self.config["LENGTH"])
		return base64.urlsafe_b64encode(h)

	def firstview (self, hashname):
Beispiel #43
0
import sys, os
sys.path.append('/var/www/SiteUppity')

from bottle import Bottle, route, view, run, template, static_file, TEMPLATE_PATH

TEMPLATE_PATH.insert(0, os.path.abspath(os.path.dirname(__file__)))

import subprocess, re, json, httplib, requests

application = Bottle()

@application.route('/index.html')
@application.route('/default.html')
@application.route('/')
@view('index')
def index():
    pass

@application.route('/favicon.ico')
def fav():
    return static_file('favicon.ico', root='/var/www/SiteUppity')

@application.route('/robots.txt')
def robot():
    return static_file('robots.txt', root='/var/www/SiteUppity')

@application.route('/getresponse/<secure:int>/<d>/<path>/')
@application.route('/getresponse/<secure:int>/<d>/<path>')
@application.route('/getresponse/<secure:int>/<d>/')
@application.route('/getresponse/<secure:int>/<d>')
def getresponse(secure, d, path = ""):
Beispiel #44
0
__author__ = 'SolPie'
import os
from datetime import datetime

from bottle import (Bottle, request, redirect,static_file, TEMPLATE_PATH, jinja2_template as render_template)

from settings import *


app = Bottle()
TEMPLATE_PATH.insert(0, TEMPLATES_PATH)

from utils.dbm import PhotoDBM, TrashDBM
from utils.photos import walkPhotos, walkTrash, Photo
from utils.md5 import md5_bytes, md5_path
## slash test
# from utils.bottleEx import StripPathMiddleware
#
# app = app()
# appEx = StripPathMiddleware(app=app)
##

##dbm test
db = PhotoDBM()
db.open(DB_PATH)
# p = db.get('test')
# p.filename = 'file.jpg'
# p.md5num = 'fe334edf'
# p.path = 23
# p.title = 'hello world'
# db.set('test', p)
Beispiel #45
0
__version__ = '3.1.2'

from bottle import TEMPLATE_PATH, route, template, static_file, error, request, response, redirect, default_app
from sqlalchemy import create_engine, MetaData
from sqlalchemy import Table, Column, Integer, String, DateTime, Boolean, ForeignKey
from sqlalchemy import select, func
import smtplib
from email.mime.text import MIMEText
from pyzufall.satz import satz
from datetime import datetime, timedelta
import random
import os.path
import sys

basepath = os.path.dirname(__file__)
TEMPLATE_PATH.insert(0, basepath + '/views/')

app = default_app()

app.config.setdefault('debug', False)
app.config.setdefault('satzgenerator.database', '')

# Konfiguration laden
app.config.load_config('config.ini')

if app.config['debug']:
    from bottle import debug

if app.config['satzgenerator.database'] == 'mysql':
    user = app.config['satzgenerator.mysql.user']
    password = app.config['satzgenerator.mysql.password']
Beispiel #46
0
from bottle import request, response, TEMPLATE_PATH, static_file
from bottle import jinja2_template as template
from PyDebrid import __path__
from PyDebrid.application import app
from PyDebrid.serienjunkies import SerienjunkiesLink
from PyDebrid.container import ContainerDecrypter
import hashlib

TEMPLATE_PATH.insert(0,__path__[0]+"/data/")

@app.route("/")
def index():
	return template("pydebrid.html", queue=app.pydebrid.pimp.links)

@app.route("/favicon.ico")
def favicon():
	return static_file("favicon.ico", root=__path__[0]+"/data/")

@app.route("/list")
def list():
	#return {'links': sorted(app.pydebrid.pimp.links.values(), key = lambda link: link['perc'])}
	return app.pydebrid.pimp.links

@app.route("/remove/<link>")
def remove(link):
	if link in app.pydebrid.pimp.links:
		app.pydebrid.pimp.bitchlist[link].cancle()
		return {'message': 'Removed Link'}

@app.post("/add_och")
def add_och():
Beispiel #47
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from bottle import route, run, get, request, Bottle, redirect, static_file, SimpleTemplate, TEMPLATE_PATH, template
from FirebaseClient import *
import json
import requests
import imojify
import translate
from random import randrange


TEMPLATE_PATH.insert(0, '../front-end/')

root = Bottle()


@root.get('/')
def server_root():

    return template('index')


@root.get('/favicon.ico')
def get_favicon():
    return server_static('favicon.ico')

# serve static files
@root.route('/static/<filename>')
def server_static(filename):
    root = "../front-end/"
Beispiel #48
0
        return True
    else:
        return False


def num_words(tweet):
    sanitized_tweet = re.sub("[^\s\w\d\-']", "", tweet)
    words = sanitized_tweet.split()
    count = 0
    for word in words:
        if check_if_word(word):
            count += 1
    return count


TEMPLATE_PATH.insert(0, "views")


@route("/")
@route("/<username>")
@view("index")
def greet(username=None):
    if username:
        tweets = get_tweets(username)
    else:
        tweets = None
    return dict(tweets=tweets)


run(host="localhost", port=8080, debug=True)
Beispiel #49
0
WSGI server. The simplest is CGI::

    from wsgiref.handlers import CGIHandler
    CGIHandler().run(app)

Check out the file ``xychan.dh.cgi`` for a working CGI script, and
``xychan.dh.passenger`` for a Passenger WSGI deployment.

"""

from bottle import TEMPLATE_PATH, default_app, request, cookie_is_encoded
import os

STATIC_PATH = __path__[0] + os.sep + 'static'

TEMPLATE_PATH.insert(0, __path__[0] + os.sep + 'templates')

from basics import *
from .db import DbSessionMiddleware, configure_db
from .image_store import configure_image_dir
from .context import context_middleware


def strip_path_middleware(app):
    def _strip_path_app(environ, start_response):
        environ['PATH_INFO'] = environ['PATH_INFO'].rstrip('/')
        return app(environ, start_response)
    return _strip_path_app


app = strip_path_middleware(
Beispiel #50
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import click
from bottle import static_file, Bottle, run, TEMPLATE_PATH
from beaker.middleware import SessionMiddleware

from calculo import settings
from calculo.routes import Routes


TEMPLATE_PATH.insert(0, settings.TEMPLATE_PATH)
session_opts = {
    'session.type': 'file',
    'session.auto': True
}

app = SessionMiddleware(Bottle(), session_opts)

# Bottle Routes
app.wrap_app.merge(Routes)


@app.wrap_app.route('/assets/<path:path>', name='assets')
def assets(path):
    yield static_file(path, root=settings.STATIC_PATH)


@click.group()
def cmds():
Beispiel #51
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

from bottle import Bottle
from bottle import debug, run
from bottle import redirect, abort, static_file
from bottle import jinja2_template as template
from bottle import request, response, local
from bottle import TEMPLATE_PATH

from mysession import get_session_info, set_session_info
from mysession import deco_session_check

from setting import CUSTOM_TPL_PATH

TEMPLATE_PATH.insert(0, CUSTOM_TPL_PATH)

app = Bottle()

app.mount('/test', __import__('test').app)

@app.route('/center')
def handel_redirect():
    return redirect(request.path+'/')

@app.route('/')
@deco_session_check
def handle_index():
    return '我是首页'

if __name__ == '__main__':
Beispiel #52
0
__author__ = 'Konglx'

import logging
import os
from jinja2 import Environment, FileSystemLoader
from bottle import TEMPLATE_PATH


def make_templates_path(root):
    return root + os.sep + 'templates'


system_templates_path = make_templates_path(os.path.dirname(__file__))
template_path = [system_templates_path]
TEMPLATE_PATH.insert(0, system_templates_path)  # for views
env = Environment(loader=FileSystemLoader(template_path))


def tenv():
    return env


def make_templates_from_plugin_path(plugin_path):
    return make_templates_path(os.sep.join(plugin_path.split(os.sep)[:-1]))


def add_plugin_templates_path(path):
    global env
    tmpl_path = make_templates_from_plugin_path(path)
    if os.path.exists(tmpl_path):
Beispiel #53
0
import json, sys

# Extend the bottle class to initialize the DB and config
class WhisperApp(Bottle):

  def __init__(self, catchall=True, autojson=True):
    self.app_config = _init.init_config() # Necessary due to naming conflicts in the Bottle class
    self.database = _database
    self.utils = _utils

    _init.init_db()
    super().__init__()

app = WhisperApp()
app.install(SQLitePlugin(dbfile="whisper/db/whisper.db"))
TEMPLATE_PATH.insert(0, 'whisper/views')

# Todo: add cookies.
@app.route('/', template="index")
def index(db):
  stats = app.database.get_stats(db)
  if stats is None:
    return dict(sent=None, opened=None)
  else:
    sent, opened = stats
    return dict(sent=sent, opened=opened)

@app.route('/faq', template="faq")
def faq():
  return dict()
Beispiel #54
0
# -*- coding: utf-8 -*-
import os
from bottle import Bottle, request, response
from bottle import jinja2_template as template
from bottle import TEMPLATE_PATH
from faker import Faker
import pickle
import uuid
import redis
import json

TEMPLATE_PATH.insert(0, os.path.join(os.path.dirname(__file__), 'views'))

app = Bottle()

def mount_json(object_base):
    fake = Faker()
    obj = {}
    for key, value in object_base.items():
        if isinstance(value, dict):
            obj[key] = mount_json(value)
            continue
        if isinstance(value, list):
            if value[0] in dir(fake):
                try:
                    if value[0] == 'list_email':
                        obj[key] = [fake.email() for n in range(value[1])]
                        continue

                    func = getattr(fake, value[0])
                    obj[key] = func(value[1])
Beispiel #55
0
	def insert(self, statement):
		conn = MySQLdb.Connection(host=self.db_host, user=self.db_username, passwd=self.db_password, db=self.db_name)
		curs = conn.cursor()
		curs.execute(statement)
		conn.commit()
		conn.close()
	def select(self, statement):
		conn = MySQLdb.Connection(host=self.db_host, user=self.db_username, passwd=self.db_password, db=self.db_name)
		curs = conn.cursor()
		curs.execute(statement)
		conn.commit()
		result = curs.fetchall()
		return result
		conn.close()

TEMPLATE_PATH.insert(0,'/apps/helloyou/templates/')

@get('/')
def index():
	return template('index')

@post('/hello')
def hello():
	name = request.forms.get('name')
	if name:
		db = dbc()
		db.insert('insert into guests (name) values ("%s")' % name)
		return template('<b>Hello {{name}}</b>!<p><hr><br><a href="/">Back</a><br><a href="/list">List entries</a><p>', name=name)
	else:
		return template('index')
Beispiel #56
0
from bottle import route, response, request, get, post, TEMPLATE_PATH, template, static_file, redirect, abort
import redis
import uuid
from src import util, user

red = redis.StrictRedis(host='redis_01',port=6379,db=0)
TEMPLATE_PATH.insert(0,'/var/www/html/templates')

@get('/game/new')
def newGame():
    new_hash = uuid.uuid4()
    red.hset('sfb:game:' + str(new_hash), 'init', 1)
    red.lpush('sfb:game:list', str(new_hash))
    return str(new_hash)

@get('/game/<hash>')
def viewGame(hash):
    cur_user = user.checkIfLoggedIn()
    cur_players = red.hget('sfb:game:' + hash,'players')
    if cur_players == None or len(cur_players) < 4:
        red.lpush('sfb:game:' + hash + ':players',cur_user)
    else:
        return "Game is at maximum capacity"
    if cur_user:
        if red.hget('sfb:game:' + hash, 'init'):
            num_players = red.lrange('sfb:game:' + hash + ':players',0,-1)
            return template('game',hash=hash,user=cur_user,num_players=num_players)
        return "This game does not exist"
    abort(401,util.error401())
Beispiel #57
0
import os
from bottle import (get, post, redirect, request, route, run, static_file,
                    template, TEMPLATE_PATH, error)
import utils
import json

TEMPLATE_PATH.insert(0, os.path.dirname(__file__))

# Static Routes


@get("/js/<filepath:re:.*\.js>")
def js(filepath):
    return static_file(filepath, root="./js")


@get("/css/<filepath:re:.*\.css>")
def css(filepath):
    return static_file(filepath, root="./css")


@get("/images/<filepath:re:.*\.(jpg|png|gif|ico|svg)>")
def img(filepath):
    return static_file(filepath, root="./images")


@route('/')
def index():
    sectionTemplate = "./templates/home.tpl"
    return template("./pages/index.html",
                    version=utils.getVersion(),
Beispiel #58
0
session_opts = {
    # 'session.auto': True,
    'session.cookie_expires': True,
    'session.encrypt_key': 'please use a random key and keep it secret!',
    'session.httponly': True,
    # 'session.secure': True, # Uncoment when using with SSL
    'session.timeout': 3600 * 24,  # 1 day
    'session.type': 'cookie',
    'session.validate_key': True,
}
app_session = SessionMiddleware(app, session_opts)


# Misc settings
PROJECT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_PATH.insert(0, '{0}/templates'.format(PROJECT_PATH))


# Session hook
@app.hook('before_request')
def setup_request():
    """Make session object accessible on all requests"""
    request.session = request.environ.get('beaker.session')


# Static files
@app.get('/static/<filename:path>')
def static_files(filename):
    """Serve static files"""
    return static_file(filename, root='{0}/static/'.format(PROJECT_PATH))
Beispiel #59
0
from bottle import static_file
from bottle import template
from bottle import view
from bottle import get
from bottle import request
from bottle import response
from bottle import TEMPLATE_PATH

import json
import os.path
import datetime
import logging
import adaat
app = Bottle()
WEB_PATH = os.path.dirname(os.path.realpath(__file__))
TEMPLATE_PATH.insert(0, os.path.join(WEB_PATH, "views"))

# define logger
# prepare logging
d = os.path.dirname(sys.argv[0])
LOG_FILENAME = os.path.join(d, u'tmp', 'logging_yaziji.out')
logging.basicConfig(
    filename=LOG_FILENAME,
    level=logging.INFO,
)
myLogger = logging.getLogger('Mishkal')
h = logging.StreamHandler(
)  # in production use WatchedFileHandler or RotatingFileHandler
h.setFormatter(
    logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
myLogger.addHandler(h)