Beispiel #1
0
def main(port):
    #Beaker options
    session_opts = {
        'session.type': 'file',
        'session.cookie_expires': True,
        'session.data_dir': './.cache',
        'session.auto': True
    }

    #Debug mode ?
    if port != 80 and port != 443:
        #Sqlite db file
        #mydbfile_solarmax = os.path.join(ROOT_PATH, "Solarmax_data2.s3db")
        #mydbfile_teleinfo = os.path.join(ROOT_PATH, "../teleinfo/Teleinfo_data.s3db")
        mydbfile_solarmax = os.path.join(ROOT_PATH,
                                         "../data/Solarmax_data2.s3db")
        mydbfile_teleinfo = os.path.join(ROOT_PATH,
                                         "../data/Teleinfo_data.s3db")
        access_log_file = 'access.log'

        #Run http test server on given port
        myserver = 'wsgiref'

    else:
        #Sqlite db file
        mydbfile_solarmax = DB_FILE_SOLAR
        mydbfile_teleinfo = DB_FILE_TELEINFO

        #Run CherryPy http or https server
        if port == 80:
            myserver = 'cherrypy'
            access_log_file = VAR_LOG_ACCESS
        elif port == 443:
            myserver = SSLCherryPyServer
            access_log_file = VAR_LOG_ACCESS_SSL

    #Create default bottle application
    app = default_app()
    myapp = SessionMiddleware(app, session_opts)

    handlers = [
        TimedRotatingFileHandler(access_log_file, 'd', 7, 90),
    ]
    loggingapp = WSGILogger(myapp, handlers, ApacheFormatter())

    #Plugins : SQLitePlugin give a connection in each functions with a db parameter
    install(SQLitePlugin(dbfile=mydbfile_solarmax))

    plugin2 = SQLitePlugin(dbfile=mydbfile_teleinfo, keyword='db2')
    plugin2.name = "sqlite2"
    install(plugin2)

    #Run server
    run(app=loggingapp,
        host='0.0.0.0',
        port=port,
        server=myserver,
        reload=True)
Beispiel #2
0
def server(config, host="127.0.0.1"):
    install(SQLitePlugin(dbfile='ratings.db'))
    install(ConfigPlugin(config))

    lInfo("server starting.")
    run(host=host, port=config["http_port"], debug=True, reloader=True)
    lInfo("server stopped.")
Beispiel #3
0
def test_app(app, test_ip):
    """A Webtest app."""

    app.install(IPAuthPlugin(token_manager=TokenManager()))

    # It is not possible to use in-memory SQLite for testing. Because for every new connection table schema will be
    # empty. So temp file will be used for test database
    fd, dbfile = tempfile.mkstemp(suffix='.sqlite')
    sqlite_plugin = app.install(SQLitePlugin(dbfile=dbfile))
    # Create database
    with sqlite3.connect(dbfile) as conn:
        conn.execute('CREATE TABLE access_log\n'
                     '            (\n'
                     '                id INTEGER PRIMARY KEY,\n'
                     '                file_key BLOB,\n'
                     '                access_date DATETIME,\n'
                     '                last_access_date DATETIME\n'
                     '            )')
        conn.commit()

        # Register IP
        t_app = TestApp(app, extra_environ={'REMOTE_ADDR': test_ip})
        res = t_app.get('/register')
        assert 200 == res.status_code
        t_app.token = res.json['Token']
        assert t_app.token is not None

        yield t_app

    # teardown
    if conn:
        conn.close()
    os.close(fd)
    os.unlink(sqlite_plugin.dbfile)
Beispiel #4
0
def runserver(port, ip, debug):
    frp = Process(target=file_removal, args=(settings.STATIC_PATH, ))
    frp.start()
    # TODO: Investigate ResourceWarning: unclosed <socket.socket fd=860, family=AddressFamily.AF_INET,
    # type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 11652), raddr=('127.0.0.1', 11642)>
    click.echo('Start server at: {}:{}'.format(ip, port))
    api.install(
        SQLitePlugin(dbfile=os.path.abspath(
            os.path.join(settings.PROJECT_PATH, '..',
                         settings.SQLITE_FILE_NAME))))
    api.install(IPAuthPlugin())
    run(app=api, host=ip, port=port, debug=debug, reloader=debug)
Beispiel #5
0
def server(config, host="127.0.0.1"):
    """
    start the server part of avrateNG
    """
    install(SQLitePlugin(dbfile='ratings.db'))
    install(ConfigPlugin(config))

    lInfo("server starting.")
    run(host=host,
        port=config["http_port"],
        debug=False,
        reloader=False,
        fast=False)
    lInfo("server stopped.")
Beispiel #6
0
def main(host, port, quiet):
    # Initialize database
    conn = sqlite3.connect(db_file.name)  # or use :memory: to put it in RAM
    cursor = conn.cursor()
    cursor.execute("""
    CREATE TABLE event_log (
        event_type TEXT,
        resource_name TEXT,
        event TEXT,
        event_time TIMESTAMP DEFAULT (datetime('now','localtime'))
    )
    """)

    # Install sqlite bottle plugin
    install(SQLitePlugin(dbfile=db_file.name))
    run(host=host, port=port, quiet=quiet)
Beispiel #7
0
from bottle import run, route, template, install, request
# pip install bottle_sqlite

from bottle_sqlite import SQLitePlugin

install(
    SQLitePlugin(
        dbfile=
        r'/Users/govindarajanv/workstation/programming/python /inventory.db'))


@route('/')
def index():
    return template("Hello {{name}}, Welcome to Bottle", name="User")


@route('/show/<devicename>')
def show_device(db, devicename):
    command = db.execute('SELECT id,os,name from devices where name =?',
                         (devicename, ))

    row = command.fetchone()
    if row:
        return template('{{id}},{{name}},{{os}}',
                        id=row['id'],
                        name=row['name'],
                        os=row['os'])
    else:
        return template("The specified device {{name}} does not exist",
                        name=devicename)
Beispiel #8
0
from bottle import route, run, install, template, request
from bottle_sqlite import SQLitePlugin

install(
    SQLitePlugin(dbfile=r'/home/trp86/python-bottle/database/inventory.db'))


@route('/show/<devicename>')
def show_device(db, devicename):
    command = db.execute('SELECT id,name,os from devices where name = ?',
                         (devicename, ))
    row = command.fetchone() or None
    if row:
        return template('{{id}},{{name}},{{os}}',
                        id=row['id'],
                        name=row['name'],
                        os=row['os'])
    else:
        return template(
            'The specified device with name :{{name}},couldnot be found!',
            name=devicename)


@route('/show')
def querylike(db):
    os = request.query.os or None
    id = request.query.id or None
    name = request.query.name or None

    print(os)
    print(id)
from bottle import *
from bottle_sqlite import SQLitePlugin

sqlite = SQLitePlugin(dbfile='test.db')
install(sqlite)

@route('/show')
def showall(db):
    row = db.execute("SELECT * from student")
    if row:
        return template('showitem', items=row)
    return HTTPError(404, "Page not found")

@route('/show/<item>')
def show(item, db):
    row = db.execute("SELECT * from student where name like ?", ('%'+item+'%',))
    if row:
        return template('showitem', items=row)
    return HTTPError(404, "Page not found")

run(host='192.168.0.31', port=8008)
Beispiel #10
0
from bottle import route, install, template
from bottle_sqlite import SQLitePlugin

install(SQLitePlugin(dbfile='bd.db'))


@route('/show/users')
def show(db):
    c = db.execute('SELECT * FROM usuario ')
    row = c.fetchone()
    return template('<b>Hello {{name}}</b>!', name=row['nome'])


def consulta(db, nome, senha):
    c = db.execute('SELECT * FROM usuario where nome = \'' + nome +
                   '\' and senha = \'' + senha + '\'')
    row = c.fetchone()
    if row:
        return True
    else:
        return False


def consulta_API(db, token):
    c = db.execute('SELECT * FROM usuario where token = \'' + token + '\'')
    row = c.fetchone()
    if row:
        return True
    else:
        return False
Beispiel #11
0
from bottle import Bottle, install, run, template, get, post, request, static_file, error, redirect, view
from bottle_sqlite import SQLitePlugin
import logging
import json

logger = logging.getLogger("readings")

app = Bottle()

app.install(SQLitePlugin(dbfile="./readings.db"))

@app.error(404)
@view("error404")
def error404(error):
    '''
    The generic error page found in the template error404.tpl under
    views is returned if a 404 - nor found error is generated
    '''
    return

@app.route('/about')
@view("about")
def about():
    return

@app.route("/json")
def jsonview(db):
    c = db.execute("SELECT rowid, systolic, diastolic, heartrate, date, notes FROM Readings")
    r = [dict((c.description[i][0], value) \
               for i, value in enumerate(row)) for row in c.fetchall()]
    return json.dumps(r)
Beispiel #12
0
#!/usr/bin/env python
# −*− coding:utf−8 −*−
from bottle import route, run, install, template, get, post, request
from bottle_sqlite import SQLitePlugin
install(SQLitePlugin(dbfile="film.db"))  #//->Zugang zur DB richtig definieren

#Zeichenerklärung:
#//-> an dieser Stelle muss noch Folgendes programmiert werden
#//<- Zeile zum Debuggen, später löschen


@route("/")
@route("/<place>", method='POST')
@route("/<place>", method='GET')
def film(db, place="home"):  #Standard
    daten = []  #//<- Beispiel-Array nach Bedarf löschen
    #Baseline-Suche
    if place == "search_base":
        idfilm = request.forms.get(
            'idfilm'
        )  #//<-Beispiel Daten aus einem Formular ziehen, nach Bedarf löschen
        query = "SELECT * FROM Film WHERE 1=1;"  #//<- Beispiel query ausführen und Daten abrufen, nach Bedarf löschen
        c = db.execute(query)
        daten = c
        row = c.fetchone()  #//<- Beispiel Daten abrufen
        idfilm = row[0]
    if place == "searchb_result":
        searchtext = request.forms.get('searchtext')
        """//-> Folgendes Schritt für Schritt programmieren zur TF*IDF-Suche
    $inhalt = explode(" ",$_POST['Suchfeld']);   
import os, binascii
from dateutil import parser as dateparser
from bottle import run, get, post, delete, install, HTTPError, request
from bottle_sqlite import SQLitePlugin
from dbsetup import init_db
from google_auth import gauth
from app_conf import DBNAME
from app_gcm import send_link

init_db(DBNAME)
install(SQLitePlugin(dbfile=DBNAME))

install(gauth)


def to_dict(row):
    return dict(
        sha=row['sha'],
        url=row['url'],
        timestamp=row['timestamp'],
        # Convert integer to boolean
        deleted=(1 == row['deleted']))


@get('/')
@get('/links')
def list_links(db, userid):
    '''Return a complete list of all links'''
    args = [userid]

    deleted_part = ' AND deleted IS 0'
Beispiel #14
0
        abort(400)
    # deadline format is %d/%m/%y %H:%M
    import datetime
    deadline = datetime.datetime.strptime(
        request.json.get('deadline', datetime.datetime.now()),
        "%d/%m/%y %H:%M")
    response.content_type = 'application/json'
    return put_data(db, idnum, column='deadline', data=deadline)


@route('/schedule/<idnum>/complete', method='PUT')
def put_complete(idnum, db):
    row = db.execute('SELECT * from schedule where id=?', [idnum]).fetchone()
    if row:
        complete = row['complete']
        # toggle complete flag
        if complete == 0:
            complete = 1
        else:
            complete = 0
        response.content_type = 'application/json'
        return put_data(db, idnum, column='complete', data=complete)
    return HTTPError(404, "Data not found")


if __name__ == "__main__":
    sqlite = SQLitePlugin(dbfile='schedule.db')
    install(sqlite)

    run(host='192.168.0.21', port=5000)
Beispiel #15
0
from bottle import route, run, request, install
from bottle_sqlite import SQLitePlugin
import json
from sklearn.svm import SVR
import numpy as np


class state:
    model = SVR()
    cols = []
    trained = False


curState = state()

install(SQLitePlugin(dbfile='./testDB.sqlite'))


@route('/getTables', method='GET')
def getTables(db):
    sql = "select name from sqlite_master where type='table'"
    c = db.execute(sql)
    tbls = []
    for row in c:
        tbls.append(row[0])
    return json.dumps(tbls)


@route('/getColumns', method='POST')
def getColumns(db):
    reqJson = request.json
Beispiel #16
0
#
# app.py
# Copyright (c) 2017 HTKエンジニアリング All Rights Reserved.
#
# Distributed under terms of the MIT license.
from bottle import *
from bottle_sqlite import SQLitePlugin
from datetime import datetime
import json

# temperテーブル構造
#  0|time  |text|0||0
#  1|sensor|text|0||0
#  2|temper|real|0||0
dbfile = 'data/temper.db'
install(SQLitePlugin(dbfile=dbfile))


# --------------
# グラフページ
# --------------
# jqPlot描画ページ(メインページ)
@route('/')
@route('/jqplot')
def jqplot():
    return template('base', title='テストページ', type='jqplot')


# Highcharts描画ページ
@route('/highcharts')
def highcharts():
Beispiel #17
0
# Copyright (c) 2012, John M. Gabriele
# License: MIT (see LICENSE.txt for details)

from bottle import route, run, template, request, response,\
    redirect, install
from bottle_sqlite import SQLitePlugin

import time, random, string

install(SQLitePlugin(dbfile='db/site.db'))


# ----------------------------------------------------------------------
# If the user is logged in, returns the username.
def is_logged_in(db):
    cookie_session_id = request.get_cookie('session_id')
    if not cookie_session_id:
        return False

    c = db.execute('select user_id from sessions where session_id = ?',
                   (cookie_session_id,))
    row = c.fetchone()
    if row:
        c = db.execute('select username from users where id = ?', (row[0],))
        row = c.fetchone()
        return row[0]
    else:
        return False


# ----------------------------------------------------------------------
Beispiel #18
0
#!/usr/bin/env python

# author: [email protected]

import ConfigParser
from bottle import route, install, run, template, static_file, response, PasteServer  #, debug
from bottle_sqlite import SQLitePlugin
import json
import urllib
import urllib2
import datetime

config = ConfigParser.RawConfigParser()
config.read('config.ini')

install(SQLitePlugin(dbfile=(config.get("pool", "database"))))


@route('/api/btime')
def blocktime():
    response.headers['Cache-Control'] = 'public, max-age=100'
    payload = {
        'requestType': 'getForging',
        'secretPhrase': config.get("pool", "poolphrase")
    }
    opener = urllib2.build_opener(urllib2.HTTPHandler())
    data = urllib.urlencode(payload)
    forging = json.loads(
        opener.open(config.get("pool", "nhzhost") + '/nhz', data=data).read())
    getdl = forging["deadline"]
    dl = str(datetime.timedelta(seconds=getdl))
Beispiel #19
0
cur = db.cursor()

# Create table
try:
    cur.execute('''CREATE TABLE items (name text)''')
except sqlite3.OperationalError:
    pass

items = [('foo',), ('bar',), ('baz',)]

cur.executemany("INSERT INTO items VALUES (?)", items)
db.commit()
db.close()


plugin = SQLitePlugin(dbfile='/tmp/test.db')
session_manager = bottlesession.CookieSession()
valid_user = bottlesession.authenticator(session_manager)

app = bottle.Bottle()
app.install(plugin)


@app.route('/')
@app.route('/:name')
@valid_user()
def hello(name='world'):
    return '<h1>Hello %s!</h1>' % name.title()


@app.route('/auth/login')
Beispiel #20
0
from bottle import static_file
from bottle import template
from bottle import install
from bottle import abort, error, redirect
from bottle_sqlite import SQLitePlugin

from config import db_path, static_dir, views_dir

import time
import os
import sys
import json

bottle.TEMPLATE_PATH.insert(0, views_dir)

install(SQLitePlugin(dbfile=db_path))


def get_kwargs_base(title, db):
    return {
        'categories':
        db.execute('SELECT * FROM category').fetchall(),
        'recent_posts':
        db.execute(
            'SELECT id,title FROM article ORDER BY publish_time DESC LIMIT 5').
        fetchall(),
        'title':
        title
    }

Beispiel #21
0
import requests, json

from bottle import route, run, template, static_file, abort, install, request, response
from imagga.color import ColorAPIClient

# The database
from bottle_sqlite import SQLitePlugin
install(SQLitePlugin(dbfile='database.db'))

# Import the config file
from config import *


class Instagram(object):
    """A small class for fetching photos from Instagram"""
    def __init__(self, client_id):
        super(Instagram, self).__init__()

        self.api_url = 'https://api.instagram.com/v1'
        self.client_id = client_id

    def get(self, resource, params=list()):
        url = self.api_url

        if resource == '/media/popular':
            url = self.append_client_id(url + resource)
        else:
            return False

        try:
            data = self.fetch_data(url)
Beispiel #22
0
from bottle import Bottle, request, response, abort, redirect
from bottle_sqlite import SQLitePlugin
from bcrypt import checkpw
from jwt import encode, decode, DecodeError, ExpiredSignature
import datetime
import inspect

app = application = Bottle()

app.config.load_config('oj.cfg')
app.install(SQLitePlugin(dbfile=app.config.get('sqlite.dbfile')))

exp_time = eval(app.config.get('jwt.exp_time'))
jwt_secret = app.config.get('jwt.secret')


class ErrorHandler:
    def get(self, ignore, default):
        def error_handler(error):
            from json import dumps
            from bottle import tob
            return tob(
                dumps({
                    "status_code": error.status_code,
                    "status": error.status,
                    "reason": error.body
                }))

        return error_handler

Beispiel #23
0
def install_db():
    dbfile = os.path.join(app_root, 'todo.db')
    install(SQLitePlugin(dbfile=dbfile))
Beispiel #24
0
import paths.general_paths as general_paths
import paths.user_paths as user_paths
import paths.librarian_paths as librarian_paths

from config import database_file, HOST

# Create Bottle Object
app = bottle.Bottle()

# Database Configuration
migrations_path = 'migrations/'
caribou.upgrade(database_file, migrations_path)

# Install Plugins
app.install(message_plugin)
app.install(SQLitePlugin(dbfile=database_file, pragma_foreign_keys=True))


# HTML Errors
@app.error(404)
def error404(error):
    return bottle.template('visitor_pages/page_not_found')


@app.error(401)
def error401(error):
    print("ERROR")
    try:
        bottle.redirect('/', 303)
    except bottle.HTTPResponse as res:
        return res
Beispiel #25
0
import datetime
import json
import random
import secrets
import types

from beaker.middleware import SessionMiddleware
import bottle
from bottle import abort, run, static_file, request, response, route
from bottle_sqlite import SQLitePlugin

import cfg
import utils

app = bottle.app()
app.install(SQLitePlugin(dbfile=cfg.DB_PATH, autocommit=False))

ROLE_ADMIN = 1

if cfg.CORS_ALLOW_ORIGIN:

    def add_cors_headers(res):
        res.headers[
            'Access-Control-Allow-Origin'] = cfg.CORS_ALLOW_ORIGIN or '*'
        res.headers[
            'Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
        res.headers[
            'Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
        res.headers['Access-Control-Allow-Credentials'] = 'true'

    @bottle.hook('before_request')
from bottle import Bottle, route, run, install, template, static_file, request, response
from bottle_sqlite import SQLitePlugin
import hashlib, json, datetime

from tokendb import TokenDB

#import bottle
#application = application = bottle.default_app()
#app = application = Bottle()
app = Bottle()
app.install(SQLitePlugin(dbfile='token.db'))


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


@app.route('/')
def index():
    return template('views/index.tpl')


@app.route('/api/status')
def api_status(db):
    name = request.GET.get('name') or request.forms.get('name') or ''
    token = request.GET.get('token') or request.forms.get('token') or ''
    #print 'Name:', name, ',Token:', token
    ''' check login '''
    tdb = TokenDB(db)
    ret = tdb.admin_check(name, token)
Beispiel #27
0
from bottle import route, run, template, request, debug, install
import bottle
import bottle.ext.sqlite
from bottle_sqlite import SQLitePlugin
import bottle
from bottle.ext import sqlite

app = bottle.Bottle()
plugin = SQLitePlugin(dbfile='cwags (11).sqlite')
bottle.install(plugin)

print app 
#HOST = '192.168.47.101'

test_list = [
    {
    'protocol': 'proto1',
    'service':'s1',
    'plugin': 'plug1',
    'value':1
     },
    {
    'protocol': 'proto2',
    'service':'s2',
    'plugin': 'plug2',
    'value':2
     },
    {
    'protocol': 'proto3',
    'service':'s3',
    'plugin': 'plug3',
Beispiel #28
0
from bottle import template
from bottle import install
from bottle_sqlite import SQLitePlugin

config = {
    'log-file': './www.log',
    'pid-file': './.www.pid',
    'db-file': '../db/imgs.db',
    'img-path': '../db/imgs',
    'daemon': sys.argv[1] if len(sys.argv) > 1 else None
}
if config['daemon']:
    import daemon
    daemon.daemon_exec(config)

install(SQLitePlugin(dbfile=config['db-file']))

templatestr = """<!DOCTYPE html>
<html>
<head>
<title>BING IMAGE</title>
<style>
body{
	max-width: 90%;
	margin: auto;
	padding-bottom:2em;
	background-color: #333333;
	color: #eeeeee; 
	font-family: "Helvetica";
	font-size: 2em;
}
@route('/static/<filename:path>')
def serve_static(filename):
    '''js, css, 画像などの静的ファイルを返す'''

    return static_file(filename, root=STATIC_DIR)


@route('/presen_images/<filename:path>')
def serve_images(filename):
    ''' プレゼン用画像を返す'''

    return static_file(filename, root=UPLOAD_DIR)


if __name__ == '__main__':

    # 初回起動時のDBセットアップ
    with open('./schema.sql',
              'r') as schema, sqlite3.connect('./peppre.db') as conn:
        conn.executescript(schema.read())

    # bottle-sqlite をセットアップ
    install(SQLitePlugin(dbfile='./peppre.db'))

    # プレゼン画像保存ディレクトリを作成
    if not os.path.isdir(UPLOAD_DIR):
        os.mkdir(UPLOAD_DIR)

    # LAN 内からのリクエストを受け付けるため host=0.0.0.0 を指定
    run(host='0.0.0.0', port=8000, debug=True)
Beispiel #30
0
from bottle import *
from bottle_sqlite import SQLitePlugin

install(SQLitePlugin(dbfile='/tmp/test.db'))

app = Bottle()


@app.route('/index/<name:re:[0-9]*>')
def index(name='world'):
    #return '<strong>hello {}!'.format(name)
    return template('form.html')


@app.get('/login')
def login_form():
    return template('form')


@app.post('/login')
def login():
    name = request.forms.get('name')
    password = request.forms.get('password')
    if name == 'admin' and password == 'pwd':
        return '<h1>successful!</h1>'
    else:
        #return '<p>sorry!</p>'
        #return template('form.html')
        #redirect('/login')
        abort(404)