def test_install_conflicts(self): self.app.install(sqlite.Plugin(keyword='db2')) @self.app.get('/') def test(db, db2): pass # I have two plugins working with different names self._request('/')
def setUp(self): self.app = bottle.Bottle(catchall=False) _, dbfile = tempfile.mkstemp(suffix='.sqlite') self.plugin = self.app.install(sqlite.Plugin(dbfile=dbfile)) self.conn = sqlite3.connect(dbfile) self.conn.execute( "CREATE TABLE todo (id INTEGER PRIMARY KEY, task char(100) NOT NULL)" ) self.conn.commit()
def test_with_keyword(self): self.plugin = self.app.install(sqlite.Plugin()) @self.app.get('/') def test(db): self.assertEqual(type(db), type(sqlite3.connect(':memory:'))) self.app({ 'PATH_INFO': '/', 'REQUEST_METHOD': 'GET' }, lambda x, y: None)
def __init__(self, routes=None): super(ShaApiBottle, self).__init__() if routes is not None: assert issubclass(routes.__class__, list), \ u'routes must be an array of route dicts to be passed to bottle.route' for route in routes: assert issubclass( route.__class__, dict ), u'route must be a dict that can be passed to bottle.route' if os.environ.get(u'SHA_API_CONFIG') is not None and \ os.path.isfile(os.path.normpath(os.environ.get(u'SHA_API_CONFIG'))): config_file = os.path.normpath(os.environ.get(u'SHA_API_CONFIG')) # If coverage for the above works then this one is the same case so skip it elif os.path.isfile(u'/etc/sha_api/sha_api.conf'): # pragma: no cover config_file = u'/etc/sha_api/sha_api.conf' else: config_file = None if config_file is not None: self.config.load_config(config_file) sqlite_db_file = global_config(self.config, u'sqlite', u'dbfile', None) if sqlite_db_file is None: # Dont use the ':memory:' because they end up closing it after each route uses it, making it useless # for anything other than a temporary db cache since we wont be able to persist our primary table. temp_file = tempfile.NamedTemporaryFile(delete=False) sqlite_db_file = temp_file.name self.install(sqlite.Plugin(dbfile=sqlite_db_file)) # bind all the routes if routes is not None: for route in routes: self.route(**route) # Initialize the sqlite db db_con = sqlite3.connect(sqlite_db_file) db_con.execute(""" CREATE TABLE IF NOT EXISTS sha_api ( digest TEXT, message TEXT, PRIMARY KEY (digest, message) ); """) db_con.close()
def test_text_factory_fail(self): self.app.install(sqlite.Plugin(keyword='db3', text_factory=unicode)) @self.app.get('/') def test(db, db3): char = 'ööö' db3.execute( "CREATE TABLE todo (id INTEGER PRIMARY KEY, task char(100) NOT NULL)" ) try: db3.execute("INSERT INTO todo (id,task) VALUES ('1',:TEST)", {"TEST": char}) except sqlite3.ProgrammingError as e: pass self._request('/')
def test_text_factory(self): # set text factory to str, unicode (default) would cause # PrammingError: You must not use 8-bit bytestrings .. exception self.app.install(sqlite.Plugin(keyword='db2', text_factory=str)) @self.app.get('/') def test(db, db2): char = 'ööö' db2.execute( "CREATE TABLE todo (id INTEGER PRIMARY KEY, task char(100) NOT NULL)" ) db2.execute("INSERT INTO todo (id,task) VALUES ('1',:TEST)", {"TEST": char}) count = len(db2.execute("SELECT * FROM todo").fetchall()) self.assertEqual(count, 1) self._request('/')
def test_without_keyword(self): self.plugin = self.app.install(sqlite.Plugin()) @self.app.get('/') def test(): pass self.app({ 'PATH_INFO': '/', 'REQUEST_METHOD': 'GET' }, lambda x, y: None) @self.app.get('/2') def test(**kw): self.assertFalse('db' in kw) self.app({ 'PATH_INFO': '/2', 'REQUEST_METHOD': 'GET' }, lambda x, y: None)
import bottle from bottle.ext import sqlite from bottle import HTTPError from json import dumps app = bottle.Bottle() plugin = sqlite.Plugin(dbfile='database.db') app.install(plugin) @app.get('/skills/<skill_id:int>') def skills_by_id(skill_id, db): row = db.execute('SELECT * FROM skills WHERE id=?', (skill_id, )).fetchone() if row: return { 'title': row['title'], 'description': row['description'], 'url': row['url'], 'image_path': row['image_path'] } return HTTPError(404, 'Page not found') @app.get('/skills') def get_all_skills(db): rows = db.execute('SELECT * FROM skills') if rows: results = [] for row in rows: results.append({
from bottle import Bottle, run, Response, static_file, request, response, template, redirect, default_app import uuid, bottle, logging from board import Board from stats import Stat from bottle.ext import sqlite application = Bottle() sqlPlugin = sqlite.Plugin(dbfile='ml.db') application.install(sqlPlugin) # Static file routes @application.route('/asset/<filepath:path>') def server_static(filepath): return static_file(filepath, root='asset/') # application routes @application.route('/') def index(): return template("home.tpl") @application.route('/stats') def patterns(db): stats = Stat(db) return template("stats.tpl", totalGames=stats.getTotalGames(), totalMoves=stats.getTotalMoves(), avgMoves=stats.getAvgMoves(), scenarioCount=stats.getScenarios(),
# @route('/hello/<name>') # def index(name): # return template('<b>Hello {{name}}</b>!', name=name) # @route("/uptime") # def uptime(): # # sending the uptime command as an argument to popen() # # and saving the returned result (after truncating the trailing \n) # ut = os.popen('uptime -p').read()[:-1] # return template('<b>Uptime: {{ut}}</b>', ut=ut) # run(host="0.0.0.0", port=8080) app = bottle.Bottle() plugin = sqlite.Plugin(dbfile='/mnt/data/my_scripts/app/api/src/app.db') app.install(plugin) def brixUptime(timeout): out = subprocess.check_output( ["/mnt/data/my_scripts/openssh_ssh_brix.sh", "uptime"], timeout=timeout) return out def check_live(hostname): response = os.system("ping -c 1 -W 1 " + hostname) # and then check the response... if response == 0: pingstatus = "Brix2807 is active, uptime: {}".format(brixUptime())
from bottle import * from bottle.ext import sqlite from os import path # File dir ROOT = path.dirname(path.realpath(__file__)) app = Bottle() plugin = sqlite.Plugin(dbfile=path.join(ROOT, 'points.db')) app.install(plugin) @app.route('/') @view('index.tpl') def map(): context = {'title': "Où doit aller l'hélico ?"} return context @app.route('/static/<filename:path>') def server_static(filename): return static_file(filename, root='.') @app.route('/sendPoint', method='GET') def getPoint(db): # Extraction des paramètres x = request.params.get('x', 0.0, type=float) y = request.params.get('y', 0.0, type=float) # Insertion DB #db.execute('INSERT INTO point(date, x, y) VALUES (CURRENT_TIMESTAMP,?,?)', (x,y))
from datetime import datetime from json import dumps from PIL import Image import imagenet_inspect import train # initialization DEEPSTATION_ROOT = (os.getcwd() + os.sep + __file__).replace('main.py', '') f = open(DEEPSTATION_ROOT + os.sep + 'settings.yaml') settings = yaml.load(f) f.close() app = bottle.Bottle() plugin = sqlite.Plugin(dbfile=DEEPSTATION_ROOT + os.sep + 'deepstation.db' ) app.install(plugin) UPLOADED_IMAGES_DIR = settings['uploaded_images'] UPLOADED_RAW_FILES_DIR = settings['uploaded_raw_files'] PREPARED_DATA_DIR = settings['prepared_data'] TRAINED_DATA_DIR = settings['trained_data'] TEMP_IMAGE_DIR = settings['inspection_temp_image'] INSPECTION_RAW_IMAGE = settings['inspection_raw_image'] NVIDIA_SMI_CMD = settings['nvidia_smi'] # static files @app.route('/statics/<filepath:path>') def server_static(filepath): return bottle.static_file(filepath, DEEPSTATION_ROOT + os.sep + 'statics' + os.sep)
from bottle import route, request, Bottle, run, response, HTTPError, HTTPResponse, hook, static_file from bottle.ext import sqlite from collections import OrderedDict import json import sqlite3 # Bottle initialization and database setup dbfilename = "cybercare.db" app = application = Bottle() plugin = sqlite.Plugin(dbfile=dbfilename, keyword="db") app.install(plugin) # Enable cors and set format to json @hook('after_request') def set_headers(): response.headers['Access-Control-Allow-Origin'] = '*' response.headers["Content-Type"] = "application/json" # Returns a formatted dictionary from an SQLite cursor object # Assumes a query has been executed already def to_json(cursor): # Unflatten address from its sql representation def nest_address(d): address = {} for key in ["street", "city", "state", "zip"]: address[key] = d.pop(key) d["address"] = address return d
# coding=utf-8 from gevent import monkey; monkey.patch_all() import session import crawler from bottle import default_app, request, response, redirect, abort from bottle import jinja2_template as template from bottle import jinja2_view as view from bottle.ext import sqlite from enum import Enum from auth import logged_in, get_data_from_session app = default_app() plugin = sqlite.Plugin(dbfile='test.db') app.install(plugin) class UserType(Enum): GhostWriter = 1 MC = 2 def encrypt_link(t_id): bin_string = bin(t_id)[2:] bin_string = bin_string.replace('0', 'x') bin_string = bin_string.replace('1', 'y') return bin_string
import sys import textwrap import logging.config import sqlite3 import bottle from bottle import get, post, error, abort, request, response, HTTPResponse from bottle.ext import sqlite # Set up app, plugins, and logging # app = bottle.default_app() app.config.load_config('./api.ini') plugin = sqlite.Plugin(app.config['sqlite.dbfile']) app.install(plugin) # Return errors in JSON # # Adapted from # <https://stackoverflow.com/a/39818780> # def json_error_handler(res): if res.content_type == 'application/json': return res.body res.content_type = 'application/json' if res.body == 'Unknown Error.': res.body = bottle.HTTP_CODES[res.status_code] return bottle.json_dumps({'error': res.body})
else: msg = { 'dialogue_id': dialogue_id, 'message_id': -1, 'datetime' : strftime('%Y-%m-%d %H:%M:%S'), #use request header date-time later 'from': -1, 'body': 'user is offline', 'other_online': 0 } return msg # var 1) if new_message.is_set take last message entry for current dialogue and return it # # var 2) try using queues for this # # var 3) leave messages in memory in some sort of dictionary with stuff from all dialogues #TODO: USE SESSIONS #================================== BASIC SERVER SETUP ======================================================= app = bottle.app() app.install(sqlite.Plugin(dbfile='./data/chatData.db')) if __name__ == '__main__': bottle.debug(True) bottle.run(app=app, server='gevent', host=host_name, port=port_num, quiet=False)
import bottle import model app = bottle.Bottle() bottle.debug(True) @app.route('/') def main(db): "Present the main page" return bottle.template('main.tpl') @app.post('/') def handle_form(db): """Handle post from submission""" if __name__ == "__main__": from bottle.ext import sqlite # install the database plugin app.install(sqlite.Plugin(dbfile=model.DATABASE_NAME)) app.run(port=8011)
import bottle from bottle.ext import sqlite # pip install -v bottle bottle-sqlite bottle-redis bottle-memcache bottle-mongodb # CREATE TABLE items(id INTEGER PRIMARY KEY ASC, name); # httperf --server=localhost --port=8080 --uri=/show/irr --num-calls=1 --num-conns=1000 app = bottle.Bottle() plugin = sqlite.Plugin(dbfile='/tmp/test.db') app.install(plugin) @app.route('/show/:item') def show(item, db): row = db.execute('SELECT * from items where name=?', (item, )).fetchone() if row: return "id=%s and name=%s" % (row[0], row[1]) bottle.response.status = 404 return None app.run(host='localhost', port=8080, debug=True, reloader=True)
from datetime import datetime, timedelta from calendar import timegm import config def render(tlp, obj=None): env = jinja2.Environment(loader=jinja2.FileSystemLoader('views'), extensions=['pyjade.ext.jinja.PyJadeExtension']) tlp = env.get_template(tlp) if obj is None: return tlp.render() return tlp.render(obj) app = bottle.Bottle() plugin = sqlite.Plugin(dbfile='db.sqlite3') app.install(plugin) @app.route('/') def index(): return render('home.html') @app.route('/static/<filename:path>') def send_static(filename): print(filename) return bottle.static_file(filename, root='./static/') @app.route('/founder/<filename:path>')
# timeline API import sys import textwrap import logging.config import sqlite3 import bottle from bottle import * from bottle.ext import sqlite # SET UP app = bottle.default_app() app.config.load_config('./etc/api.ini') plugin = sqlite.Plugin(app.config['sqlite.dbfile']) user_db = sqlite.Plugin(dbfile='../userAPI/var/clients.db', keyword='userDB') app.install(plugin) app.install(user_db) logging.config.fileConfig(app.config['logging.config']) # RETURN errors in JSON def json_error_handler(res): if res.content_type == 'application/json': return res.body res.content_type = 'application/json' if res.body == 'Unknown Error.': res.body = bottle.HTTP_CODES[res.status_code] return bottle.json_dumps({'error': res.body})
import bottle from bottle import route, run, template, static_file from bottle.ext import sqlite import datetime app = bottle.Bottle() plugin = sqlite.Plugin(dbfile='./db/test.db') app.install(plugin) # Show the line chart. @app.route('/') def index(db): return template('template/chart') # Output csv file. @app.route('/data.csv') def data(db): lines = [] lines.append('date,temperature') # Query database, only show the last 60 entries. rows = db.execute( 'SELECT `date`, `temperature` FROM `stats` ORDER BY `date` DESC LIMIT 60;' ).fetchall() for row in rows: date = datetime.datetime.strptime(row[0], "%Y-%m-%d %H:%M:%S").isoformat() temp = str(row[1]) lines.append(date + ',' + temp)
import json from config import Config # http://bottlepy.org/docs/dev/ # https://developer.mastercard.com/documentation/merchant-identifier # https://github.com/greggles/mcc-codes # https://github.com/jleclanche/python-iso18245 app = bottle.Bottle() app.config.update({ 'autojson': True, }) plugin = sqlite.Plugin(dbfile=Config['db_file']) app.install(plugin) # Initialize MC consumerKey = Config['consumerKey'] keyStorePath = Config['keyStorePath'] keyAlias = Config['keyAlias'] keyPassword = Config['keyPassword'] debug = Config['debug'] sandbox = Config['sandbox'] auth = MCApiCore.OAuthAuthentication(consumerKey, keyStorePath, keyAlias, keyPassword) MCApiCore.Config.setAuthentication(auth) MCApiCore.Config.setDebug(debug) MCApiCore.Config.setSandbox(sandbox)
import time import datetime import bottle from bottle import route from bottle import Bottle from bottle import install from bottle import request from bottle import response from bottle.ext import sqlite import duckduckgo # --- test TODO test for failure --- app = Bottle(__name__) plugin = sqlite.Plugin(dbfile='database/bigbox.db') app.install(plugin) # --- test --- # db_datetime_utc: return epoch in utc def db_datetime_utc(): """store datetime in UTC epoch format""" t = datetime.datetime.utcnow() return time.mktime(t.timetuple()) #--- routes --- # HACK WARNING: I'm tired, this is untested & potentially # insecure code. no correction, this is naive
# get the form field likes = request.forms.get('likes') if likes: database.store_like(db, likes) return redirect('/') @app.route('/static/<filepath:path>') def static(filepath): return static_file(filepath, root='static') if __name__ == "__main__": # code to connect to the database and create the tables from bottle.ext import sqlite DATABASE_NAME = 'test.db' db = sqlite3.connect(DATABASE_NAME) database.create_tables(db) # code to run our web application plugin = sqlite.Plugin(dbfile=DATABASE_NAME) app.install(plugin) # run the application app.run()
import bottle from bottle.ext import sqlite from datetime import datetime app = application = bottle.Bottle() plugin = sqlite.Plugin(dbfile='./scores.sqlite3') app.install(plugin) def get_names(db): """Hole die Teilnehmerliste aus der Datenbank und gib sie als Dictionary zurück""" names_list = db.execute('SELECT * FROM names ORDER BY id').fetchall() return {id: name if name != '' else '#' + str(id) for (id, name) in names_list} @app.route('/') def index(): """Zeige die Rangliste""" return bottle.template('./index.tpl') @app.route('/scores') def scores(db): """API-Endpunkt: Liefere die Daten der Rangliste im JSON-Format""" scores = sorted(db.execute('SELECT * FROM scores').fetchall(), key=lambda score: score['punkte'] / score['anzahl']) return dict( names = get_names(db), scores = [dict(score) for score in scores], now = datetime.now().strftime('%Y-%m-%d um %H:%M:%S Uhr') ) @app.route('/names') def names(db):
config = ConfigParser() config.read( [path.join(BASE_DIR, 'settings.ini'), os.getenv('CONF_FILE', '')]) return config class Error(Exception): pass BASE_DIR = path.dirname(__file__) CONF = read_config() expire_info = CONF['db']['date_expire'] bottle.TEMPLATE_PATH = [BASE_DIR] # Set default attributes to pass into templates. SimpleTemplate.defaults = dict(CONF['html']) SimpleTemplate.defaults['url'] = bottle.url # подключаем базу plugin = sqlite.Plugin(dbfile=CONF['db']['dbname']) install(plugin) # Run bottle internal server when invoked directly (mainly for development). if __name__ == '__main__': bottle.run(**CONF['server']) # Run bottle in application mode (in production under uWSGI server). else: application = bottle.default_app()
import bottle from bottle import static_file, template from bottle.ext import sqlite import time from datetime import datetime app = bottle.Bottle() sqlitePlugin = sqlite.Plugin(dbfile='data.db') app.install(sqlitePlugin) @app.get("/css/<filepath:re:.*\.css>") def css(filepath): return static_file(filepath, root="css") @app.get("/img/<filepath:re:.*\.(jpg|gif|png|ico|JPG)>") def img(filepath): return static_file(filepath, root="img") @app.get("/js/<filepath:re:.*\.js>") def js(filepath): return static_file(filepath, root="js") @app.get('/') @app.get('/index.html') def main(db): return visitors_count(db, 'index') @app.get('/gallery.html')
import sys import textwrap import logging.config import sqlite3 import bottle from bottle import get, post, abort, request, response from bottle.ext import sqlite # Set up app, plugins, and logging # app = bottle.default_app() app.config.load_config("./etc/api.ini") plugin = sqlite.Plugin(app.config["sqlite.dbfile"]) app.install(plugin) logging.config.fileConfig(app.config["logging.config"]) # Return errors in JSON # # Adapted from <https://stackoverflow.com/a/39818780> # def json_error_handler(res): if res.content_type == "application/json": return res.body res.content_type = "application/json" if res.body == "Unknown Error.": res.body = bottle.HTTP_CODES[res.status_code]
""" import unittest import sqlite3 from bottle.ext import sqlite import bottle from webtest import TestApp from random import choice import os from database import create_tables, sample_data import main import users DATABASE_NAME = "test.db" # initialise the sqlite plugin for bottle main.app.install(sqlite.Plugin(dbfile=DATABASE_NAME)) bottle.debug() class Level3FunctionalTests(unittest.TestCase): def setUp(self): self.app = TestApp(main.app) self.db = sqlite3.connect(DATABASE_NAME) create_tables(self.db) self.users, self.positions = sample_data(self.db) def tearDown(self): self.db.close() os.unlink(DATABASE_NAME) def doLogin(self, user, password):
""" Ayy lmao """ import time import bottle import valve.source.a2s from bottle import mako_template as template from bottle.ext import sqlite APP = bottle.Bottle() PLUGIN = sqlite.Plugin(dbfile='sourcemod.sq3') APP.install(PLUGIN) SERVER_ADDRESS = ("139.59.23.194", 27015) def a2s(): """Retrieves info about the server """ try: server = valve.source.a2s.ServerQuerier(SERVER_ADDRESS) t_send = time.time() info = server.info() ping = (time.time() - t_send) * 1000.0 #players = server.players() return [True, ping, info] #, players] except Exception: return [False]