Beispiel #1
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'))
    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 #3
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 #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 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 #6
0
def init_application(dbconf=None,cusconf=None,secret=None):
    log.startLogging(sys.stdout)  
    base.update_secret(secret)
    utils.update_secret(secret)
    log.msg("start init application...")
    TEMPLATE_PATH.append("./customer/views/")
    ''' install plugins'''
    engine,metadata = models.get_engine(dbconf)
    sqla_pg = sqla_plugin.Plugin(engine,metadata,keyword='db',create=False,commit=False,use_kwargs=False)
    session = sqla_pg.new_session()
    _sys_param_value = functools.partial(get_param_value,session)
    _get_member_by_name = functools.partial(get_member_by_name,session)
    _get_account_by_number = functools.partial(get_account_by_number,session)
    _get_online_status = functools.partial(get_online_status,session)
    MakoTemplate.defaults.update(**dict(
        get_cookie = get_cookie,
        fen2yuan = utils.fen2yuan,
        fmt_second = utils.fmt_second,
        request = request,
        sys_param_value = _sys_param_value,
        system_name = _sys_param_value("2_member_system_name"),
        get_member = _get_member_by_name,
        get_account = _get_account_by_number,
        is_online = _get_online_status
    ))

    websock.connect(
        _sys_param_value('3_radiusd_address'),
        _sys_param_value('4_radiusd_admin_port')
    )
    
    mainapp.install(sqla_pg)
Beispiel #7
0
def remove_plugin_templates_path(path):
    global env
    tmpl_path = make_templates_from_plugin_path(path)
    if tmpl_path in template_path:
        template_path.remove(tmpl_path)  # for webhooks
        TEMPLATE_PATH.remove(tmpl_path)  # for webviews
        env = Environment(loader=FileSystemLoader(template_path))  # ditch and recreate a new templating environment
	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 #9
0
def page(project, page='index'):
    
    # 设定模版目录
    TEMPLATE_PATH.append('./projects/%s/pages/' % project)
    
    context = { 
        'url': request.url, 
        'req': request.params
    }
    return jinja2_template(page, **context)
Beispiel #10
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 #11
0
def init_application(dbconf=None,consconf=None,secret=None):
    log.startLogging(sys.stdout)  
    log.msg("start init application...")
    base.update_secret(secret)
    utils.update_secret(secret)
    TEMPLATE_PATH.append("./admin/views/")
    ''' install plugins'''
    log.msg("init plugins..")
    engine,metadata = models.get_engine(dbconf)
    sqla_pg = sqla_plugin.Plugin(engine,metadata,keyword='db',create=False,commit=False,use_kwargs=False)
    session = sqla_pg.new_session()
    _sys_param_value = functools.partial(get_param_value,session)
    _get_product_name = functools.partial(get_product_name,session)
    log.msg("init template context...")
    MakoTemplate.defaults.update(**dict(
        get_cookie = get_cookie,
        fen2yuan = utils.fen2yuan,
        fmt_second = utils.fmt_second,
        currdate = utils.get_currdate,
        request = request,
        sys_param_value = _sys_param_value,
        get_product_name = _get_product_name,
        system_name = _sys_param_value("1_system_name"),
        radaddr = _sys_param_value('3_radiusd_address'),
        adminport = _sys_param_value('4_radiusd_admin_port'),
        permit = permit,
        all_menus = permit.build_menus(order_cats=[u"系统管理",u"营业管理",u"运维管理"])
    ))
    
    # connect radiusd websocket admin port 
    log.msg("init websocket client...")
    wsparam = (MakoTemplate.defaults['radaddr'],MakoTemplate.defaults['adminport'],)
    reactor.callLater(3, websock.connect,*wsparam)
    log.msg("init tasks...")
    reactor.callLater(5, tasks.start_online_stat_job, sqla_pg.new_session)
   
    log.msg("init operator rules...")
    for _super in session.query(models.SlcOperator.operator_name).filter_by(operator_type=0):
        permit.bind_super(_super[0])

    log.msg("install plugins...")
    mainapp.install(sqla_pg)
    ops_app.install(sqla_pg)
    bus_app.install(sqla_pg)
    card_app.install(sqla_pg)

    mainapp.mount("/ops",ops_app)
    mainapp.mount("/bus",bus_app)
    mainapp.mount("/card",card_app)
    
    #create dir
    try:os.makedirs(os.path.join(APP_DIR,'static/xls'))
    except:pass
    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 #13
0
def setup_app():
    root = os.path.dirname(os.path.abspath(__file__))
    session_opts = {
        'session.type': 'file',
        'session.cookie_expires': 3600 * 10,
        'session.data_dir': os.path.join(root, 'data/'),
        'session.auto': True
    }

    app = Bottle()
    app = setup_routing(app)
    TEMPLATE_PATH.append(os.path.join(root, 'templates/'))
    TEMPLATE_PATH.remove('./views/')
    app = SessionMiddleware(app, session_opts)
    return app
Beispiel #14
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 #15
0
def page(project, page):
    
    # 设定模版目录
    TEMPLATE_PATH.append('./projects/%s/pages/' % project)
    TEMPLATE_PATH.append('./projects/%s/layouts/' % project)

    site = 'http://%s' % request.environ.get('HTTP_HOST')
    context = { 
        'project': project,
        'page': page,
        'site': site,
        'url': request.url, 
        'req': request.params,
        'base': '/%s/' % project,
        'static': '%s/%s/%s/' % (site, ASSET_NAME, project)
    }
    return jinja2_template(page, **context)
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
def getimage(app):
    """Get image file."""
    # append source directory to TEMPLATE_PATH so template is found
    srcdir = os.path.abspath(os.path.dirname(__file__))
    TEMPLATE_PATH.append(srcdir)
    staticbase = '_static'
    buildpath = os.path.join(app.outdir, staticbase)
    try:
        os.makedirs(buildpath)
    except OSError:
        if not os.path.isdir(buildpath):
            raise

    if app.config.sphinxmark_image == 'default':
        imagefile = 'watermark-draft.png'
        imagepath = os.path.join(srcdir, imagefile)
        copy(imagepath, buildpath)
        LOG.debug('[sphinxmark] Using default image: ' + imagefile)
    elif app.config.sphinxmark_image == 'text':
        imagefile = createimage(app, srcdir, buildpath)
        LOG.debug('[sphinxmark] Image: ' + imagefile)
    else:
        imagefile = app.config.sphinxmark_image

        if app.config.html_static_path:
            staticpath = app.config.html_static_path[0]
        else:
            staticpath = '_static'

        LOG.debug('[sphinxmark] static path: ' + staticpath)
        imagepath = os.path.join(app.confdir, staticpath, imagefile)
        LOG.debug('[sphinxmark] Imagepath: ' + imagepath)

        try:
            copy(imagepath, buildpath)
        except Exception:
            message = ("Cannot find '%s'. Put watermark images in the "
                       "'_static' directory or specify the location using "
                       "'html_static_path'." % imagefile)
            LOG.warning(message)
            LOG.warning('Failed to add watermark.')
            return

    return(buildpath, imagefile)
    def __init__(self, args=None):
        # Init args
        self.args = args

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

        # Init Bottle
        self._app = Bottle()
        # Enable CORS (issue #479)
        self._app.install(EnableCors())
        # Define routes
        self._route()

        # Update the template path (glances/outputs/bottle)
        TEMPLATE_PATH.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'bottle'))

        # Path where the statics files are stored
        self.STATIC_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static')
Beispiel #19
0
    def __init__(self, args=None):
        # Init args
        self.args = args

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

        # Init Bottle
        self._app = Bottle()
        self._route()

        # Update the template path (glances/outputs/bottle)
        TEMPLATE_PATH.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'bottle'))

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

        # Define the style (CSS) list (hash table) for stats
        self.__style_list = {
            'DEFAULT': '',
            'UNDERLINE': 'underline',
            'BOLD': 'bold',
            'SORT': 'sort',
            'OK': 'ok',
            'FILTER': 'filter',
            'TITLE': 'title',
            'CAREFUL': 'careful',
            'WARNING': 'warning',
            'CRITICAL': 'critical',
            'OK_LOG': 'ok_log',
            'CAREFUL_LOG': 'careful_log',
            'WARNING_LOG': 'warning_log',
            'CRITICAL_LOG': 'critical_log',
            'NICE': 'nice',
            'STATUS': 'status',
            'PROCESS': ''
        }
Beispiel #20
0
def shift_local():
    import os
    from bottle import TEMPLATE_PATH, default_app

    ON_OPENSHIFT = False
    if os.environ.has_key('OPENSHIFT_REPO_DIR'):
        ON_OPENSHIFT = True

    if ON_OPENSHIFT:
        TEMPLATE_PATH.append(os.path.join(os.environ['OPENSHIFT_HOMEDIR'],
                                      'runtime/repo/wsgi/views/'))
    
        application=default_app()
    else:
        import commands
        from bottle import run

        print "AdNail - Interfaces disponibles: "
        print commands.getoutput("/sbin/ifconfig | egrep -o '^[a-z].......'")
        intfz = raw_input('Introduce la interfaz a utilizar: ')
        comand = "/sbin/ifconfig "+intfz+" | egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | egrep -v '*(0|255)$'"
        iphost = commands.getoutput(comand)
        print "La IP del Servidor es: ", iphost
        run(host=iphost, port=8080, debug=True)
from bottle import route, default_app


@route('/name/<name>')
def nameindex(name='Stranger'):
    return '<strong>Hello, %s!</strong>' % name


@route('/')
def index():
    return '<strong>Hello World!</strong>'


# This must be added in order to do correct path lookups for the views
import os
from bottle import TEMPLATE_PATH
TEMPLATE_PATH.append(
    os.path.join(os.environ['OPENSHIFT_REPO_DIR'], 'wsgi/views/'))

application = default_app()
# Static routes: css, js, images, ...
@get('/<filename:re:.*\.js>')
def javascripts(filename):
	return static_file(filename, root=os.environ['OPENSHIFT_REPO_DIR']+'/wsgi/static/js')

@get('/<filename:re:.*\.css>')
def stylesheets(filename):
	return static_file(filename, root=os.environ['OPENSHIFT_REPO_DIR']+'/wsgi/static/css')

@get('/<filename:re:.*\.(jpg|png|gif|ico)>')
def images(filename):
	return static_file(filename, root=os.environ['OPENSHIFT_REPO_DIR']+'/wsgi/static/img')

@get('/<filename:re:.*\.(eot|ttf|woff|svg)>')
def fonts(filename):
	return static_file(filename, root=os.environ['OPENSHIFT_REPO_DIR']+'/wsgi/static/fonts')

@get('/<filename:re:.*\.(doc|pdf)>')
def fonts(filename):
	return static_file(filename, root=os.environ['OPENSHIFT_REPO_DIR']+'/wsgi/static/resources')


# This must be added in order to do correct path lookups for the views
import os
from bottle import TEMPLATE_PATH

TEMPLATE_PATH.append(os.path.join(os.environ['OPENSHIFT_REPO_DIR'], 'wsgi/views/'))
application=default_app()

Beispiel #23
0
__author__ = 'arobres'

from bottle import run, template, Bottle, request, response, auth_basic, redirect, static_file, TEMPLATE_PATH
from constants import THEME, SUBJECT, MESSAGES
from collections import defaultdict
import ujson
from sys import argv
import os
from time import sleep

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



app = Bottle()
user_list = []
USER_ATTRIBUTES = {'name', 'username', 'password', 'role', 'email'}
FORUM_ATTRIBUTES = {'theme', 'subject', 'message'}
ROLES = ['QA', 'DEVELOPER', 'MANAGER']
THEMES = ['Security', 'Development', 'Automation', 'Testing']
user_messages_dict = defaultdict(list)
forum_messages_dict = defaultdict(list)


def check_username(username, password):
    for user in user_list:
        if user['username'] == username:
            if user['password'] == password:
                return True
    return False
Beispiel #24
0
#-*-coding:utf8;-*-
#qpy:3
#Liwal WebApp
#http://localhost:8080/
"""
main.py
"""
import json
from pprint import pprint
from bottle import route, run, template, TEMPLATE_PATH

with open('/storage/emulated/0/qpython/repos/Liwal/settings.json'
          ) as settings_file:
    settings = json.load(settings_file)

pprint(settings)

TEMPLATE_PATH.insert(0, settings['root_path'] + 'views')

#import controllers:
import controller.home

run(host=settings['host'], port=settings['port'])
Beispiel #25
0
# -*- coding: utf-8 -*-
__version__ = '0.1'

import sys
import os
from bottle import Bottle, TEMPLATE_PATH

app = Bottle(autojson=False)
app_root_path = sys.path[0]
TEMPLATE_PATH.append(os.path.join(app_root_path, "project", "views"))
TEMPLATE_PATH.remove("./views/")
from project.controller import *
Beispiel #26
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 #27
0
#!/usr/bin/env python
# -*- encoding: utf-8 -*-

from bottle import get, post, redirect, request, run, static_file, template, TEMPLATE_PATH
from calendar import month_name
from datetime import date
from os import getenv
from os.path import dirname, join as path_join
from py2neo import Graph, watch

from demo.moviegraph.model import Movie, Person, Comment

home = dirname(__file__)
static = path_join(home, "static")
TEMPLATE_PATH.insert(0, path_join(home, "views"))

# Set up a link to the local graph database.
graph = Graph(password=getenv("NEO4J_PASSWORD"))
watch("neo4j.bolt")


@get('/css/<filename:re:.*\.css>')
def get_css(filename):
    return static_file(filename, root=static, mimetype="text/css")


@get('/images/<filename:re:.*\.png>')
def get_image(filename):
    return static_file(filename, root=static, mimetype="image/png")

Beispiel #28
0
from bottle import get, post, route, run, template, TEMPLATE_PATH, request, redirect, static_file
import os

TEMPLATE_PATH.insert(0, "./views")
root = os.getcwd()

#------------------------------------------------------------------------------------------------
#                                   DATABASE CONNECTIVITY
#------------------------------------------------------------------------------------------------
# import pymongo

# client = pymongo.MongoClient("mongodb://*****:*****@route('/static/<filepath:path>')
def serve_static(filepath):
    myroot = os.path.join(root, "static")
    return static_file(filepath, root=myroot)


@get('/')
@get('/home')
def home():
    return template('home')
Beispiel #29
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 #30
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 #31
0
 def __init__(self):
     self.BASE_DIR = os.path.dirname(os.path.abspath(__file__))
     # テンプレートファイルを設置するディレクトリのパスを指定
     TEMPLATE_PATH.append(self.BASE_DIR + "/templetes")
     self.md = markdown.Markdown()
     self.html = ''
Beispiel #32
0
from beaker.middleware import SessionMiddleware

from mining.controllers.api import api_app
from mining.controllers.stream import stream_app
from mining.controllers.export import export_app
from mining.utils import conf
from mining.auth import auth
from mining.settings import TEMPLATE_PATH, STATIC_PATH
from mining.celeryc import celery_app
from mining.bin.scheduler import scheduler_app
from mining.bin.demo.build_admin import build

reload(sys)
sys.setdefaultencoding('utf-8')

T.insert(0, TEMPLATE_PATH)

session_opts = {
    'session.type': 'file',
    'session.data_dir': '/tmp/openmining.data',
    'session.lock_dir': '/tmp/openmining.lock',
    'session.cookie_expires': 50000,
    'session.auto': True
}

app = SessionMiddleware(Bottle(), session_opts)
app.wrap_app.mount('/api', api_app)
app.wrap_app.mount('/stream', stream_app)
app.wrap_app.mount('/export', export_app)

app.wrap_app.install(auth)
Beispiel #33
0
from bottle import request, response, route, run, static_file, template, TEMPLATE_PATH
import os
import io

from ..imgsteg import Imgsteg

base = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_PATH.insert(0, os.path.join(base, "views/"))
file = None


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


@route("/")
def index():
    return template('index')


@route("/api/<command>", method="POST")
def inversion(command):
    im = Imgsteg(file)

    # print(command)
    new_im = None

    if command == "original":
        new_im = im.im
    elif command == "inversion":
Beispiel #34
0
# -- determine where I launch python and config lib path
# base_dir = os.path.dirname(__file__)
# third_party_path = os.path.abspath(os.path.join(base_dir, 'third_party' ))
# sys.path.insert(0, third_party_path)

# -- common bottle importation
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    from bottle import TEMPLATE_PATH, Bottle, run, static_file, debug, request
    from bottle import jinja2_view as view, jinja2_template as template

debug(True)

base_dir = os.path.dirname(__file__)
TEMPLATE_PATH.append(os.path.abspath(os.path.join(base_dir, 'views')))

# -- the instance app is important
app = Bottle()

# -- serve static files, files located in static
static_folder = 'static'
_static_folder = os.path.join(os.path.dirname(__file__), static_folder)


@app.route('/stats/region/:chrom', method='GET')
def stats_region(chrom):
    # Note: chrom is give as an argument

    # we then extract start and end using HTML GET
    start = request.GET.get('start', '').strip()
Beispiel #35
0
    def __init__(self):
        self._app = Bottle()
        self._controller = video_controller.make_video_controller()

        TEMPLATE_PATH.insert(0, os.path.join(app_path, 'views'))
        SimpleTemplate.defaults['get_url'] = self._app.get_url
Beispiel #36
0
def build_application():
    #  XXX Define application routes in this class

    app = Bottle()

    #  Pretty much this entire function needs to be written for your

    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('/', name='index')  # XXX URL to page
    @view('index')  # XXX Name of template
    def index():
        'A simple form that shows the date'

        import datetime

        now = datetime.datetime.now()

        #  any local variables can be used in the template
        return locals()

    #  XXX User list page
    @app.route('/users', name='user_list')  # XXX URL to page
    @view('users')  # XXX Name of template
    def user_list():
        'A simple page from a dabase.'

        db = dbwrap.session()

        users = db.query(model.User).order_by(model.User.name)

        #  any local variables can be used in the template
        return locals()

    #  XXX User details dynamically-generated URL
    @app.route('/users/<username>', name='user')  # XXX URL to page
    @view('user')  # XXX Name of template
    def user_info(username):
        'A simple page from a dabase.'

        user = model.user_by_name(username)

        #  any local variables can be used in the template
        return locals()

    #  XXX A simple form example, not used on the demo site
    @app.route('/form')  # XXX URL to page
    @view('form')  # XXX Name of template
    def static_form():
        'A simple form processing example'

        form = NewUserFormProcessor(request.forms.decode())
        if request.method == 'POST' and form.validate():
            #  XXX Do something with form fields here

            #  if successful
            redirect('/users/%s' % form.name.data)

        #  any local variables can be used in the template
        return locals()

    #  XXX Create a new user, form processing, including GET and POST
    @app.get('/new-user', name='user_new')  # XXX GET URL to page
    @app.post('/new-user')  # XXX POST URL to page
    @view('user-new')  # XXX Name of template
    def new_user():
        'A sample of interacting with a form and a database.'

        form = NewUserFormProcessor(request.forms.decode())

        if request.method == 'POST' and form.validate():
            db = dbwrap.session()

            sean = model.User(full_name=form.full_name.data,
                              name=form.name.data,
                              email_address=form.email_address.data)
            db.add(sean)
            db.commit()

            redirect(app.get_url('user', username=form.name.data))

        #  any local variables can be used in the template
        return locals()

    #  REQUIRED: return the application handle herre
    return app
                    format="%(asctime)s - %(levelname)s - %(message)s")
CLIENT_ID = "e29426dfb22c41cdbc92122fbb9c398c"
CLIENT_SECRET = "837fd2824bec47e5a003419165674bdd"
SCOPE = "user-top-read user-read-recently-played playlist-modify-public playlist-modify-private"
CACHE = ".spotifyoauthcache"
CLIENT_CREDENTIALS = SpotifyClientCredentials(client_id=CLIENT_ID,
                                              client_secret=CLIENT_SECRET)
SP_OAUTH2 = oauth2.SpotifyOAuth(client_id=CLIENT_ID,
                                client_secret=CLIENT_SECRET,
                                redirect_uri="http://localhost:8000/verified",
                                scope=SCOPE,
                                cache_path=CACHE)
LIMIT = 50
OFFSET = 0

TEMPLATE_PATH.insert(0, "")

# global functions


def get_token():
    access_token = ""
    token_info = SP_OAUTH2.get_cached_token()
    if token_info:
        access_token = token_info["access_token"]
    else:
        url = request.url
        code = SP_OAUTH2.parse_response_code(url)
        if code:
            print("Found Spotify auth code in Request URL! "
                  "Trying to get valid access token...")
Beispiel #38
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 #39
0
import os

from bottle import Bottle, route, run, request, response, static_file
from bottle import TEMPLATE_PATH, jinja2_template as template

app = Bottle()  #ボトルのインスタンス作成

# index.pyが設置されているディレクトリの絶対パスを取得
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# テンプレートファイルを設置するディレクトリのパスを指定
TEMPLATE_PATH.append(BASE_DIR + "/views")

# python ./main.py を直接実行したときはローカルサーバーを立ち上げる
if __name__ == "__main__":
    run(app=app, host="localhost", port=8081, quiet=False, reloader=True)
Beispiel #40
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 #41
0
def main(template_path):
    TEMPLATE_PATH.insert(0, template_path)

    @get("/static/<filename>")
    def serve_static_files(filename):
        """Function to serve CSS and JS files"""
        return static_file(filename, root='python-pyzftp/static')

    @route("/zftp", method=["GET", "POST"])
    def process_form():
        """Function to display main webpage and process the form contents"""

        global statuses, anyerror

        if not anyerror:
            machine = ""
            userid = ""
            pswd = ""
            ftno = 1
            checked1 = "checked"
            checked2 = ""
            checked3 = "checked"
            checked4 = ""
            dsn = ""
            filname = ""
        else:
            for k1, v1 in statuses.items():
                machine = v1["machine"]
                userid = v1["userid"]
                pswd = v1["pswd"]
                ftno = ""
                checked1 = ""
                checked2 = ""
                checked3 = ""
                checked4 = ""
                dsn = ""
                filname = ""
                break

        if request.method == "GET":
            return template("zftpmain",
                            machine=machine,
                            userid=userid,
                            pswd=pswd,
                            ftno=ftno,
                            checked1=checked1,
                            checked2=checked2,
                            checked3=checked3,
                            checked4=checked4,
                            dsn=dsn,
                            filname=filname,
                            anyerror=anyerror,
                            statuses=statuses)
        elif request.method == "POST":

            statuses = {}
            anyerror = False
            ismachine_exist = True
            iscred_exist = True
            isfile_exist = True
            iserror = False

            # get all the name attributes from the submitted form
            keylst = list(request.forms.keys())
            trnsfr1lst = [key for key in keylst if "trsfrno" in key]
            trnsfr2lst = [
                int(key.replace("trsfrno", "")) for key in trnsfr1lst
            ]

            machine = request.forms.get("machine")
            userid = request.forms.get("userid")
            pswd = request.forms.get("pswd")

            # try catch hostname/ip error
            try:
                host = FTP(machine)
            except:
                ismachine_exist = False

            # try catch credentials error
            try:
                if ismachine_exist:
                    host.login(userid, pswd)
            except:
                iscred_exist = False
                host.quit()

            if not ismachine_exist or not iscred_exist:
                iserror = True
                anyerror = True

            threads = []

            for trsfrno in trnsfr2lst:
                ckey1 = "ftpverb-radio" + str(trsfrno)
                ckey2 = "ftpformat-radio" + str(trsfrno)
                if request.forms.get(ckey1) == "receive":
                    get = True
                else:
                    get = False
                if request.forms.get(ckey2) == "text":
                    text = True
                else:
                    text = False
                dsnkey = "dsn" + str(trsfrno)
                filnamekey = "filename" + str(trsfrno)
                dsn = request.forms.get(dsnkey)
                dsn = dsn.replace("'", "")
                dsn = dsn.replace('"', "")
                dsn = "'" + dsn + "'"
                filname = request.forms.get(filnamekey)

                if get:
                    if text:
                        # log = f"{trsfrno} transfer starts.."
                        # print(log)
                        thread = Thread(target=gettext,
                                        args=(machine, userid, pswd, trsfrno,
                                              dsn, filname, ismachine_exist,
                                              iscred_exist, isfile_exist,
                                              iserror))
                        threads.append(thread)
                    else:
                        # log = f"{trsfrno} transfer starts.."
                        # print(log)
                        thread = Thread(target=getbinary,
                                        args=(machine, userid, pswd, trsfrno,
                                              dsn, filname, ismachine_exist,
                                              iscred_exist, isfile_exist,
                                              iserror))
                        threads.append(thread)
                else:
                    if text:
                        # log = f"{trsfrno} transfer starts.."
                        # print(log)
                        thread = Thread(target=puttext,
                                        args=(machine, userid, pswd, trsfrno,
                                              dsn, filname, ismachine_exist,
                                              iscred_exist, isfile_exist,
                                              iserror))
                        threads.append(thread)
                    else:
                        # log = f"{trsfrno} transfer starts.."
                        # print(log)
                        thread = Thread(target=putbinary,
                                        args=(machine, userid, pswd, trsfrno,
                                              dsn, filname, ismachine_exist,
                                              iscred_exist, isfile_exist,
                                              iserror))
                        threads.append(thread)

            for thread in threads:
                thread.daemon = True
                thread.start()

            for thread in threads:
                thread.join()

            redirect("/zftp/status")

    @route("/zftp/status", method=["GET"])
    def showmessages():
        """Function to display status webpage"""
        return template("zftpstatus", statuses=statuses)

    run(host="localhost", port=9001,
        debug=True)  # uses socket - localhost:9001

    return
Beispiel #42
0
# -*- coding: utf-8 -*-
__version__ = '0.1'
from bottle import Bottle, TEMPLATE_PATH
app = Bottle()
TEMPLATE_PATH.append("./chanelist/views/")
from chanelist.controllers import *
Beispiel #43
0
from bottle import TEMPLATE_PATH, install, run, BaseRequest
import os
from logit import logit

TEMPLATE_PATH.insert(0, os.getenv('SITE_TEMPLATES', ''))

# routes are here and use default_app, to be after app and db setup
import routes.web_handlers
import routes.api_handlers
BaseRequest.MEMFILE_MAX = 1024 * 1024

logit('starting breadcrumbs')
if __name__ == '__main__':
    run(host=os.getenv('SITE_HOST', '127.0.0.1'),
        port=eval(os.getenv('SITE_PORT', "8080")),
        debug=eval(os.getenv('SITE_DEBUG', 'True')))
Beispiel #44
0
import os
from bottle import TEMPLATE_PATH, route, static_file, template, install, request
from app.apod import Apod

BASE_PATH = os.path.dirname(os.path.abspath(__file__))

TEMPLATE_PATH.append(BASE_PATH + "/templates")


@route('/', method='GET')
@route('/<date>', method='GET')
def index(date=None):
    return template('index.tpl')


@route('/about', method='GET')
def about():
    return template('about.tpl')


@route('/apod/:date', method='GET')
def apod(date):
    apod = Apod(date)

    return {
        "title": apod.title,
        "image_credit": apod.image_credit,
        "low_res_image_path": apod.low_res_image_path,
        "high_res_image_path": apod.high_res_image_path,
        "explanation": apod.explanation.decode('utf-8', 'ignore'),
        "date": apod.date,
Beispiel #45
0
from bottle import route, run, template, request, redirect, error, static_file, TEMPLATE_PATH, get, post, hook, app
from bottle.ext import beaker
from datetime import datetime, date
import sqlite3
import os
import datetime
import json
import websockets

abs_app_dir_path = os.path.dirname(os.path.realpath(__file__))
abs_views_path = os.path.join(abs_app_dir_path, "views")
abs_static_path = os.path.join(abs_app_dir_path, "static")
TEMPLATE_PATH.insert(0, abs_views_path)

session_opts = {
    "session.type": "file",
    "session.cookie_expires": True,
    "session.data_dir": "./data",
    "session.auto": True
}

app = beaker.middleware.SessionMiddleware(app(), session_opts)


@hook("before_request")
def setup_request():
    request.session = request.environ["beaker.session"]


@route("/static/<filename>")
def server_static(filename):
Beispiel #46
0
        return template('jornada', datos=datos, ronda=ronda)


@error(404)
def error404(error):
    return template('errores')


@error(500)
def error500(error):
    return template('errores')


@error(405)
def error405(error):
    return template('errores')


ON_OPENSHIFT = False
if os.environ.has_key('OPENSHIFT_REPO_DIR'):
    ON_OPENSHIFT = True

if ON_OPENSHIFT:
    TEMPLATE_PATH.append(
        os.path.join(os.environ['OPENSHIFT_HOMEDIR'],
                     'app-root/repo/wsgi/views/'))

    application = default_app()
else:
    run(host='localhost', port=8080)
Beispiel #47
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 #48
0
def register_ui_views(app):

    BaseTemplate.defaults['app'] = app  # Template global variable
    # Location of HTML templates
    TEMPLATE_PATH.insert(
        0,
        os.path.abspath(os.path.join(os.path.dirname(__file__),
                                     '../templates')))

    # TODO: API and UI must use the same adapter
    adapter_type = ZKAdapter

    # TODO: format errors in a nice UI instead of abort

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

    @app.route('/', name='applications', method=["GET", "POST"])
    @view('applications')  # Name of template
    def index():
        if request.method == "POST":
            application_name = request.forms.new_application
            if application_name:
                try:
                    with adapter_type() as adapter:
                        adapter.create_application(application_name)
                except KeyExistsError:
                    abort(409,
                          "Application %s already exists." % application_name)
            else:
                abort(400, "Please provide a name for the new application.")

        default = "Enabled" if settings.DEFAULT_VALUE else "Disabled"
        with adapter_type() as adapter:
            applications = adapter.get_applications()

        #  any local variables can be used in the template
        return locals()

    @app.route('/<application_name>/features',
               name='features',
               method=["GET", "POST"])
    @view('features')  # Name of template
    def features(application_name):
        application_name = application_name.lower()
        saved = False
        added = False
        error = None
        abort = False

        if request.method == "POST":
            feature_chck_name_tmpl = "%s_checkbox"
            segment_chck_name_tmpl = "%s_%s_checkbox"
            option_chck_name_tmpl = "%s_%s_%s_checkbox"

            with adapter_type() as adapter:
                segments = adapter.get_all_segments(application_name)
                features = adapter.get_all_features(application_name)

                for feature in features:
                    # a checkbox is checked if it exists in request.forms
                    feature_dict = {
                        "feature_toggled":
                        True if request.forms.get(feature_chck_name_tmpl %
                                                  feature) else False,
                        "segmentation": {
                            segment: {
                                "toggled":
                                True if request.forms.get(
                                    segment_chck_name_tmpl %
                                    (feature, segment)) else False,
                                "options": {
                                    option: True if request.forms.get(
                                        option_chck_name_tmpl %
                                        (feature, segment, option)) else False
                                    for option in segments[segment]
                                }
                            }
                            for segment in segments
                        }
                    }
                    adapter.update_feature(application_name, feature,
                                           feature_dict)
                    saved = True

        default = "Enabled" if settings.DEFAULT_VALUE else "Disabled"
        try:
            with adapter_type() as adapter:
                features = adapter.get_all_features(application_name)
        except KeyDoesNotExistError:
            error = "Application %s does not exist." % application_name
            abort = True

        #  any local variables can be used in the template
        return locals()

    # TODO: change this crappy URL later
    @app.post('/<application_name>/create', name='create')
    @view('features')  # Name of template
    def create_feature(application_name):
        application_name = application_name.lower()
        feature_name = request.forms.new_feature
        added = False
        saved = False
        error = None
        abort = False

        if feature_name:
            try:
                with adapter_type() as adapter:
                    adapter.create_feature(application_name, feature_name)
                added = True
            except KeyExistsError:
                error = ("Feature %s already exists for application %s." %
                         (feature_name, application_name))

        else:
            error = "Please provide a name for the new feature."

        # TODO: redirect to features instead of this block
        default = "Enabled" if settings.DEFAULT_VALUE else "Disabled"
        try:
            with adapter_type() as adapter:
                features = adapter.get_all_features(application_name)
        except KeyDoesNotExistError:
            error = "Application %s does not exist." % application_name
            abort = True

        #  any local variables can be used in the template
        return locals()

    @app.route('/<application_name>/segments',
               name='segments',
               method=["GET", "POST"])
    @view('segments')  # Name of template
    def segments(application_name):
        application_name = application_name.lower()
        if request.method == "POST":
            segment_name = request.forms.new_segment
            if segment_name:
                try:
                    with adapter_type() as adapter:
                        adapter.create_segment(application_name, segment_name)
                except KeyExistsError:
                    abort(
                        409, "Segment %s already exists for application %s." %
                        (segment_name, application_name))
            else:
                abort(400, "Please provide a name for the new segment.")

        try:
            with adapter_type() as adapter:
                segments = adapter.get_all_segments(application_name)
        except KeyDoesNotExistError:
            abort(404, "Application %s does not exist." % application_name)

        #  any local variables can be used in the template
        return locals()

    @app.post('/<application_name>/options/<segment>', name='options')
    def options(application_name, segment):
        option_name = request.forms.new_option
        if option_name:
            try:
                with adapter_type() as adapter:
                    adapter.create_segment_option(application_name, segment,
                                                  option_name)
            except KeyExistsError:
                abort(
                    409, "Option %s already exists for segment %s in "
                    "application %s." %
                    (option_name, segment, application_name))
        else:
            abort(400, "Please provide a name for the new segment option.")

        redirect(app.get_url('segments', application_name=application_name))
Beispiel #49
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 #50
0
from bottle import get
from bottle import request
from bottle import response
from bottle import TEMPLATE_PATH

import datetime
import logging
import json
import os.path
sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), '../../'))
import core.adaat
app = Bottle()
#~ xpath = os.path.join(os.path.dirname(__file__), 'views')
xpath = os.path.dirname(os.path.realpath(__file__))
#~ print("xpath", xpath)
TEMPLATE_PATH.insert(0, os.path.join(xpath, "views"))

#----------------------------------
# define logger
# prepare logging 
#---------------------------------
d = os.path.dirname(sys.argv[0])
LOG_FILENAME = os.path.join(d,u'tmp','logging_mishkal.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)
myLogger.setLevel(logging.INFO) # in production use logging.INFO

Beispiel #51
0
import os
import sys
from bottle import run, template, route, request, static_file, Response, app, TEMPLATE_PATH
from datahandle import dataeng
import time
import datetime
TEMPLATE_PATH.insert(
    0,
    'C:/Users/BRUNO - PC/REPOS_GIT/DataloggerDHT22/Tests web server/Python/webserver'
)

NAME_DB = 'fauba_dataloggers.db'
DIRECTORY_DB = "C:/Users/BRUNO - PC/REPOS_GIT/DataloggerDHT22/Tests web server/Python/webserver"
MEASUREMENTS_TABLE_NAME = 'MEASUREMENTS'
DEVICES_STATE_TABLE_NAME = 'DEVICES_STATUS'
DB_COLUMN_NAME_ID_TRANSCEIVER = 'ID_TRANSCEIVER'
DB_COLUMN_NAME_BATTERY_LEVEL = 'BATTERY_LEVEL'
DB_COLUMN_NAME_ID_SENSOR = 'ID_SENSOR'
DB_COLUMN_NAME_TIMESTAMP = 'TIMESTAMP'
DB_COLUMN_NAME_DATE_TIME = 'DATE_TIME'
DB_COLUMN_NAME_TEMPERATURE = 'TEMPERATURE'
DB_COLUMN_NAME_HUMIDITY = 'HUMIDITY'

localdir = str(sys.path[0])


def initDB(dir, nameDB):
    print('DB directory to open: ' + str(dir + '\\' + nameDB))  #debug
    db = dataeng.DataEngine(
        dir + '\\' + nameDB, debugmode=False
    )  #Create DataEngine object with the database directory.  Will create dir if it doesn't exist.
Beispiel #52
0
import logging
import os
from jinja2 import Environment, FileSystemLoader
from bottle import TEMPLATE_PATH

log = logging.getLogger(__name__)


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):
        log.debug("Templates directory found for this plugin [%s]" % tmpl_path)
Beispiel #53
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 #54
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import sys
import click
from bottle import static_file, Bottle, run, TEMPLATE_PATH, request
from beaker.middleware import SessionMiddleware

from requester import settings
from requester.routes import Routes
from requester.utils import validate_input, hash_password
import sqlite3

TEMPLATE_PATH.insert(0, settings.TEMPLATE_PATH)
session_opts = {
    'session.type': 'cookie',
    'session.cookie_expires': True,
    'session.httponly': True,
    'session.timeout': 3600 * 24,  # 1 day
    'session.validate_key': True,
    'session.auto': True,
}

app = SessionMiddleware(Bottle(), session_opts)

# Bottle Routes
app.wrap_app.merge(Routes)


@app.wrap_app.route('/assets/<path:path>', name='assets')
Beispiel #55
0
import os
import sqlite3
# 課題2の答えはここ(一番右) 時間を取得するためにimportする
from bottle import route, run, debug, template, request, static_file, error, redirect, response , datetime , get, TEMPLATE_PATH
# secrets.token_hex([nbytes=None])
# 十六進数のランダムなテキスト文字列を返します。文字列は nbytes のランダムなバイトを持ち、各バイトは二つの十六進数に変換されます。nbytes が None の場合や与えられなかった場合は妥当なデフォルト値が使われます。
import secrets

TEMPLATE_PATH.insert(0, os.path.abspath(os.path.join(os.path.dirname("__file__"), "../ref03")))

secret_cookie = secrets.token_hex()
print(secret_cookie)

@route('/')
def index():
    print("ここでもsecret_cookie:" + secret_cookie)
    return template('index')


# GET  /register => 登録画面を表示
# POST /register => 登録処理をする
@route('/register',method=["GET", "POST"])
def register():
    #  登録ページを表示させる
    if request.method == "GET":
        # ログインしてないからクッキーがセットされてない
        name = request.get_cookie("user_id" , secret="secret_cookie")
        if name is None:

            return template("register")
        else:
Beispiel #56
0
import os
import ssl

# Note: any modules that supply bottle functionality need to be imported
# here even though they aren't used directly.
import shared_cfg
import authentication
import navigation
import manage_passwords

log = logging.getLogger(__name__)

# Tell bottle to look in these directories for templates.
RBB_EXPORT_DIRECTORY = 'web-ui_exported'
GENERATED_TEMPLATE_DIRECTORY = 'generated_templates'
TEMPLATE_PATH.append('./{0}/'.format(RBB_EXPORT_DIRECTORY))
TEMPLATE_PATH.append('./{0}/'.format(GENERATED_TEMPLATE_DIRECTORY))


@get('/css/<filename:re:.*\.css>')
def send_css(filename):
    global RBB_EXPORT_DIRECTORY
    return static_file(filename, root='{0}/css'.format(RBB_EXPORT_DIRECTORY))


@get('/fonts/<filename:re:.*\.(eot|svg|ttf|woff)>')
def send_font(filename):
    global RBB_EXPORT_DIRECTORY
    return static_file(filename, root='{0}/fonts'.format(RBB_EXPORT_DIRECTORY))

Beispiel #57
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 #58
0
# Licença Pública Geral GNU para maiores detalhes.
#
# Você deve ter recebido uma cópia da Licença Pública Geral GNU
# junto com este programa, se não, veja em <http://www.gnu.org/licenses/>
"""Handle http requests.

.. moduleauthor:: Carlo Oliveira <*****@*****.**>

"""
import os
import sys
import logging as log
from bottle import TEMPLATE_PATH

LOG_LEVEL = int(os.getenv("LABASELOG", log.ERROR))

log.basicConfig(level=LOG_LEVEL)

P_N_O_D_E_D = "S_N_O_D_E-%02d"
HERE = os.path.dirname(__file__)
SRC_DIR = os.path.join(HERE, "views")
# add your project directory to the sys.path
project_home = HERE  # os.path.join(here, "src/")
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

# make sure the default templates directory is known to Bottle
templates_dir = os.path.join(project_home, 'views/')
if templates_dir not in TEMPLATE_PATH:
    TEMPLATE_PATH.insert(0, templates_dir)
Beispiel #59
0
import os
import pymongo
import string
from bottle import TEMPLATE_PATH, route, jinja2_template as template, request, response
from models import *
from bottle import static_file, request
import urllib
import urllib2
import sys
import json
import datetime
TEMPLATE_PATH.append('./templates')
sys.path.append('./backend/configs')
sys.path.append('./backend')
import apilib
APP_CONFIG = {}
APP_CONFIG["DBNAME"] = "gigzibit"
APP_CONFIG["LOGTABLE"] = "log"
APP_CONFIG["THUMBNAIL_COLOR"] = "#FEFEFE"
APP_CONFIG["HEADING_COLOR"] = "#EBE0D6"
APP_CONFIG["NAV_COLOR"] = "#FDFDFA"


@route('/bootstrap/<dir1>/<dir2>/:filename')
def serve_static(dir1, dir2, filename):
    return static_file(dir1 + '/' + dir2 + '/' + filename, root='./bootstrap/docs/')
    
@route('/HTML-KickStart/<dir1>/:filename')
def serve_static(dir1, filename):
    return static_file(dir1 + '/' + filename, root='./HTML-KickStart/')
    
Beispiel #60
0
from bottle import run, template, static_file, get, post, delete, request, TEMPLATE_PATH
import json
import os
import database_sql

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


@get("/admin")
def admin_portal():
    return template("pages/admin.html")


@get("/")
def index():
    return template("index.html")


@get('/js/<filename:re:.*\.js>')
def javascripts(filename):
    return static_file(filename, root='js')


@get('/css/<filename:re:.*\.css>')
def stylesheets(filename):
    return static_file(filename, root='css')


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