Ejemplo n.º 1
1
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

def log_to_logger(fn):
    '''
    Wrap a Bottle request so that a log line is emitted after it's handled.
    (This decorator can be extended to take the desired logger as a param.)
    '''
    @wraps(fn)
    def _log_to_logger(*args, **kwargs):
        request_time = datetime.now()
        actual_response = fn(*args, **kwargs)
        # modify this to log exactly what you need:
        logger.info('%s %s %s %s %s' % (request.remote_addr,
                                        request_time,
                                        request.method,
                                        request.url,
                                        response.status))
        return actual_response
    return _log_to_logger

app = Bottle()
app.install(log_to_logger)

@app.route('/')
def home():
    return ['hello, world']

app.run(host='0.0.0.0', port='8080', quiet=True)
Ejemplo n.º 2
0
 def run_app(self):
     api_app = Bottle()
     api_app.install(log_to_logger)
     app.install(log_to_logger)
     api_app.mount('/api/', app)
     conf = self.get_config()
     api_app.config['host'] = conf['host']
     api_app.config['port'] = conf['port']
     api_app.run(host=api_app.config['host'], port=api_app.config['port'])
Ejemplo n.º 3
0
 def __init__(self):
     self.user = None
     self._read_settings()
     self.app = Bottle()
     if self._ssl:
         SSLify(self.app)
     self.bound_bottle()
     try:
         print(self._ssl)
         self.app.run(host=self.web_settings['host'],
                      port=int(self.web_settings['port']),
                      server='ssl' if self._ssl else 'wsgiref')
     except OSError as e:
         print(e)
Ejemplo n.º 4
0
#!/usr/bin/env python3
# -*- coding:utf-8 -*-

from lib.bottle import Bottle
from lib.bottle import TEMPLATE_PATH
from lib.bottle import jinja2_template
from lib.bottle import request
from sample.models.data import website


app = Bottle()
TEMPLATE_PATH.append('../sample/views')


@app.route('/', method=["GET", "POST"])
def index():
    add_website_page = "add_website.html"
    login_page = "login.html"
    session = request.environ.get('beaker.session')
    user_id = session.get("user_id", "")
    # セッション情報が残っていた場合
    if user_id:
        cls_website = website.Website()
        attention = u""
        website_name = request.forms.decode().get('website_name', "")
        website_link = request.forms.decode().get('website_link', "")
        website_keywords = request.forms.decode().get('website_keywords', "")
        complete_add_website = request.forms.get('complete_add_website', "False")
        if website_link:
            if not website_name:
                website_name = cls_website.get_website_title_with_link(website_link)
Ejemplo n.º 5
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/>
"""Controller handles routes starting with /RESOURCE_NAME.

Change this file's name and contents as appropriate to the
resources your app exposes to clients.

"""
from lib.bottle import Bottle, view, request, response, redirect, HTTPError
from ..models import code_store as cs
from . import project, get_project, project_visual_data, BRYTHON
__author__ = 'carlo'

bottle = Bottle(
)  # create another WSGI application for this controller and resource.
# debug(True) #  uncomment for verbose error logging. Do not use in production


@bottle.get('/')
@view('index')
@get_project
def home():
    """ Return User Selection at application root URL"""
    module = request.query.module
    # project = request.query.proj or "spy"
    module = "NOT FOUND: %s" % module.upper() if module else None
    # print("home project", project)
    tops, items = project_visual_data(project)
    return dict(project=project,
                result=items,
Ejemplo n.º 6
0
class WebInterface(object):
    def __init__(self):
        self.user = None
        self._read_settings()
        self.app = Bottle()
        if self._ssl:
            SSLify(self.app)
        self.bound_bottle()
        try:
            print(self._ssl)
            self.app.run(host=self.web_settings['host'],
                         port=int(self.web_settings['port']),
                         server='ssl' if self._ssl else 'wsgiref')
        except OSError as e:
            print(e)

    def _read_settings(self):
        conf = configparser.ConfigParser(allow_no_value=True)
        conf.read('settings.ini')
        settings = conf['socket']
        self.web_settings = conf['web_server']
        try:
            self._ssl = conf.getboolean('web_server', 'https_enabled')
        except AttributeError as e:
            self._ssl = False
        self.page_size = int(self.web_settings['page_size'])
        db_autoclean = int(conf['db_settings']['store_days'])
        try:
            self.db_engine.db_autoclean_days = db_autoclean
        except AttributeError:
            self.db_engine = DataEngine(settings['host'],
                                        settings['port'],
                                        db_autoclean_days=db_autoclean)
            self.db_engine.start_sync_loop(settings['db_update_period'])

    def bound_bottle(self):
        self.app.route('/')(self.last_messages)
        self.app.route('/device/<dev_id>')(self.messages_by_id)
        self.app.route('/delete')(self.delete_messages)
        self.app.route('/delete/accept')(self.delete_messages_accepted)
        self.app.route('/login')(self.login)
        self.app.post('/login')(self.do_login)
        self.app.route('/logout')(self.logout)
        self.app.route('/settings')(self.change_settings)
        self.app.post('/settings')(self.do_change_settings)
        self.app.route('/settings/change_password')(self.change_password)
        self.app.post('/settings/change_password')(self.do_change_password)
        self.app.route('/settings/useradd')(self.useradd)
        self.app.post('/settings/useradd')(self.do_useradd)
        self.app.route('/settings/userdel')(self.userdel)
        self.app.post('/settings/userdel')(self.do_userdel)
        self.app.route('/settings/reboot')(self.reboot)
        self.app.route('/static/<filename>')(self.server_static)
        self.app.route('/static/<filename>')(self.server_static)

    def _check_cookie(self):
        session_id = request.get_cookie('session_id')
        if session_id:
            self.user = self.db_engine.validate_session(session_id)
            if self.user:
                response.set_cookie(
                    'session_id',
                    session_id,
                    expires=datetime.now() + timedelta(
                        days=int(self.web_settings['session_expire_days'])))

    def server_static(self, filename):
        return static_file(filename, root='./static')

    @view('index')
    def last_messages(self):
        self._check_cookie()
        sort_by = request.query.sort_by or 'received_at'
        page = int(request.query.page or 1)
        reverse = bool(int(request.query.reverse or 0))
        messages, pages = self.db_engine.get_last_messages(
            sort_by=sort_by,
            reverse=reverse,
            page=page,
            page_size=self.page_size)
        page_info = {
            'sort_by': sort_by,
            'page': page,
            'reverse': reverse,
            'pages': pages
        }
        return dict(rows=messages, page_info=page_info, user=self.user)

    @view('device')
    def messages_by_id(self, dev_id):
        self._check_cookie()
        sort_by = request.query.sort_by or 'received_at'
        page = int(request.query.page or 1)
        reverse = bool(int(request.query.reverse or 0))
        messages, pages = self.db_engine.get_messages_by_id(
            id_=dev_id,
            sort_by=sort_by,
            reverse=reverse,
            page=page,
            page_size=self.page_size)
        page_info = {
            'id': dev_id,
            'sort_by': sort_by,
            'page': page,
            'reverse': reverse,
            'pages': pages
        }
        return dict(data=messages, page_info=page_info, user=self.user)

    @view('delete')
    def delete_messages(self):
        self._check_cookie()
        id_ = request.query.id or None
        if id_ == "None": id_ = None
        return dict(dev_id=id_, user=self.user)

    @view('deleted')
    def delete_messages_accepted(self):
        self._check_cookie()
        id_ = request.query.id or None
        if id_ == "None": id_ = None
        if self.user:
            deleted = self.db_engine.delete_messages(id_)
            return dict(deleted=deleted, user=self.user)
        else:
            abort(401, "You have no access to this page")

    @view('login')
    def login(self):
        return dict(user=self.user)

    def do_login(self):
        username = request.forms.get('username')
        password = request.forms.get('password')
        session_id = self.db_engine.validate_user(username, password)
        if session_id:
            self.user = username
            response.set_cookie(
                'session_id',
                session_id,
                expires=datetime.now() +
                timedelta(days=int(self.web_settings['session_expire_days'])))
        else:
            self.user = None
        return template('login_result', user=self.user)

    @view('logout')
    def logout(self):
        accepted = request.query.accepted or 0
        if accepted:
            self.user = None
            response.delete_cookie('session_id')
            return template('login_result', user=None)
        else:
            return dict(user=self.user)

    @view('settings')
    def change_settings(self):
        self._check_cookie()
        conf = configparser.ConfigParser(allow_no_value=True)
        conf.read('settings.ini')
        if self.user:
            return dict(settings=conf, user=self.user)
        else:
            abort(401, "You have no access to this page")

    def do_change_settings(self):
        self._check_cookie()
        conf = configparser.ConfigParser(allow_no_value=True)
        conf.read('settings.ini')
        conf['web_server']['session_expire_days'] = request.forms.get(
            'session_expire_days')
        conf['web_server']['page_size'] = request.forms.get('page_size')
        conf['db_settings']['store_days'] = request.forms.get('store_days')
        if self.user:
            with open('settings.ini', 'w') as file:
                conf.write(file)
            self._read_settings()
        redirect('/settings')

    @view('change_password')
    def change_password(self):
        self._check_cookie()
        success = request.query.success or 0
        if str(success) == '1':
            return template('change_password', user=self.user, success=True)
        else:
            if self.user: return dict(user=self.user, success=False)
            else: abort(401, 'You are not authorised')

    def do_change_password(self):
        old_pwd = request.forms.get('old_password')
        new_pwd = request.forms.get('new_password_1')
        new_pwd_2 = request.forms.get('new_password_2')
        print("DEBUG: ", self.user, new_pwd)
        if self.user and new_pwd == new_pwd_2:
            self.db_engine.change_password(self.user, old_pwd, new_pwd)
            redirect('/settings/change_password?success=1')
        else:
            redirect('/settings')

    @view('useradd')
    def useradd(self):
        self._check_cookie()
        result = request.query.result
        if self.user: return dict(user=self.user, result=result)
        else: abort(401, 'You are not authorised')

    def do_useradd(self):
        username = request.forms.get('username')
        if self.user:
            try:
                if self.db_engine.add_user(username):
                    redirect('/settings/useradd?result=created')
                else:
                    redirect('/settings/useradd?result=error')
            except sqlite3.IntegrityError:
                redirect('/settings/useradd?result=duplicate')
            except sqlite3.OperationalError:
                redirect('/settings/useradd?result=error')
        else:
            abort(401, 'You are not authorised')

    @view('userdel')
    def userdel(self):
        self._check_cookie()
        result = request.query.result
        if self.user:
            return dict(user=self.user,
                        result=result,
                        users=self.db_engine.get_user_list())
        else:
            abort(401, 'You are not authorised')

    def do_userdel(self):
        self._check_cookie()
        user = request.forms.get('username')
        passwd = request.forms.get('password')
        userdel = request.forms.get('userdel')
        if user == userdel:
            redirect('/settings/userdel?result=self')
        else:
            if self.db_engine.delete_user(user, passwd, userdel):
                print('redirecting')
                redirect('/settings/userdel?result=del')

    @view('reboot')
    def reboot(self):
        self._check_cookie()
        accepted = bool(int(request.query.accepted or 0))
        if self.user:
            if accepted:
                sleep(.1)
                os.popen('sudo reboot')
            return dict(user=self.user, accepted=accepted)
Ejemplo n.º 7
0
__author__ = 'reason'
from lib.bottle import Bottle,TEMPLATE_PATH
import index,shunion,option ,datareport ,nokiareport,ssx,wlapi,tdwap
import  setting

TEMPLATE_PATH.insert(0,setting.TEM_PATH)

app=Bottle()
app.mount("/nokiadata",nokiareport.app)
app.mount("/data",datareport.app)
app.mount("/index",index.app)
app.mount("/shunion",shunion.app)
app.mount("/option",option.app)
app.mount("/ssx",ssx.app)
app.mount("/wlapi",wlapi.app)
app.mount("/tdwap",tdwap.app)



Ejemplo n.º 8
0
__author__ = 'reason'
from lib.bottle import Bottle,TEMPLATE_PATH
import index
import  setting

TEMPLATE_PATH.insert(0,setting.TEM_PATH)

app=Bottle()

app.mount("/index",index.app)




Ejemplo n.º 9
0
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
from functools import wraps

from common import Logging
from common.Logging import get_generic_logger
from common.YamlConfig import AppConfig
from lib.bottle import Bottle, request, response

from ..AppRunner import AppRunner
from ..RemoteServerApi import get_server_config, get_server_info

app = Bottle()

logger = get_generic_logger()


@app.route('/si', method=['GET'])
def si():
    try:
        return get_server_info()
    except Exception as e:
        return {'status': e}


@app.route('/cf', method=['GET'])
def si():
    try:
        return get_server_config()
    except Exception as e:
        return {'status': e}
Ejemplo n.º 10
0
#!/usr/bin/env python3
# -*- coding:utf-8 -*-

from lib.bottle import Bottle
from lib.bottle import TEMPLATE_PATH
from sample.controllers import login
from sample.controllers import sign_up
from sample.controllers import search
from sample.controllers import manage
from sample.controllers import add_website
from sample.controllers import edit_profile
from sample.controllers import logout

app = Bottle()
TEMPLATE_PATH.append('../sample/views')

# resources/でアクセスできるRESTful API群を以下に羅列していく
app.mount('/login', login.app)
app.mount('/sign_up', sign_up.app)
app.mount('/search', search.app)
app.mount('/manage', manage.app)
app.mount('/add_website', add_website.app)
app.mount('/edit_profile', edit_profile.app)
app.mount("/logout", logout.app)


@app.get('/')
def index():
    return str('Hello. This is sample_top page.')
Ejemplo n.º 11
0
# -*- coding:utf-8 -*-

from lib.bottle import Bottle
from lib.bottle import run
from beaker.middleware import SessionMiddleware
from sample.controllers import index as sample_index

# セッションの設定
session_opts = {
    'session.type': 'file',
    'session.data_dir': '/tmp',
    'session.cookie_expires': True,
    'session.auto': True,
}

app = Bottle()
apps = SessionMiddleware(app, session_opts)


@app.route('/')
def index():
    return str('Hello. This is top page.')


if __name__ == '__main__':
    # 以下のindex.py(sample/controllers/index.py)で、さらに別のroutesを指定することも可能。
    # このようにワンクッション置くことで、/sampleと言うようなURLのみの場合にも何かメッセージを表示することが可能。
    app.mount('/sample', sample_index.app)

    run(app=apps, host='localhost', port=8080, debug=True, reloader=True)
Ejemplo n.º 12
0
__author__ = 'reason'
from lib.bottle import Bottle,TEMPLATE_PATH
import main,user,code,upload,setting,play,vlist,playlist,home
import logging
# import redis
from setting import project_path

TEMPLATE_PATH.insert(0,setting.TEM_PATH)

app=Bottle()

# init path
app.mount("/main",main.app)
app.mount("/code",code.app)
app.mount("/user",user.app)
app.mount("/upload",upload.app)
app.mount("/programs",play.app)
app.mount("/list",vlist.app)
app.mount("/zh",playlist.app)
app.mount("/home",home.app)


# init log config
log_file = project_path + "/log/gkgp.log" 
logging.basicConfig(filename = log_file, level = logging.DEBUG,format = '%(asctime)s - %(levelname)s: %(message)s') 

Ejemplo n.º 13
0
__author__ = 'reason'
from lib.bottle import Bottle,TEMPLATE_PATH
import index,option,video,channel,notice,template,main
import  setting


TEMPLATE_PATH.insert(0,setting.TEM_PATH)

app=Bottle()

app.mount("/option",option.app)
app.mount("/index",index.app)
app.mount("/video",video.app)
app.mount("/channel",channel.app)
app.mount("/notice",notice.app)
app.mount("/template",template.app)
app.mount("/main",main.app)
Ejemplo n.º 14
0
"""Main.py is the top level script.

Loads the Bottle framework and mounts controllers.  Also adds a custom error
handler.
"""
from lib import bottle
from lib.bottle import Bottle, redirect, request
# name and list your controllers here so their routes become accessible.
from server.controllers import main_controller, project_controller, code_controller
# Enable debugging, which gives us tracebacks
bottle.DEBUG = True

# Run the Bottle wsgi application. We don't need to call run() since our
# application is embedded within an App Engine WSGI application server.
appbottle = Bottle()

# Mount a new instance of bottle for each controller and URL prefix.
# appbottle.mount("/external/brython/Lib/site-packages", project_controller.bottle)
appbottle.mount("/<:re:.*>/_spy", code_controller.bottle)
appbottle.mount("superpython", project_controller.appbottle)

# Mount a new instance of bottle for each controller and URL prefix.
appbottle.mount("/main", main_controller.bottle)
appbottle.mount("/code", code_controller.bottle)
# bottle.mount("/pontos", pontos_controller.bottle)


@appbottle.get('/')
def home():
    """ Return Hello World at application root URL"""