def __init__(self, config_path, config, notifier, websocket_notifier, authenticator, health, inventory_auth=None, inventory_host=None): app = bottle.app() app.config.load_config(config_path) engine = database.engine() plugin = sabottle.Plugin( engine, None, keyword='db', use_kwargs=True, create=False, ) app.install(plugin) self._check_for_index_html(app) conn = beanstalkc.Connection( host=config.get("general", "beanstalk_host"), port=11300 ) conn.use('deployer-deployments') app.config["deployer.engine"] = engine app.config["deployer.beanstalk"] = conn app.config["deployer.notifier"] = notifier app.config["deployer.websocket_notifier"] = websocket_notifier app.config["deployer.bcrypt_log_rounds"] = 12 app.config["deployer.authenticator"] = authenticator app.config["health"] = health app.config["deployer.inventory"] = inventory_host app.config["deployer.inventory_auth"] = inventory_auth self.httpd = make_server("0.0.0.0", config.getint('general', 'api_port'), app, server_class=ThreadingWSGIServer, handler_class=LoggingWSGIRequestHandler)
def sqlalchemy_plugin(Base): """ Default arguments for sql_alchemy """ return sqlalchemy.Plugin( engine, Base.metadata, keyword='db', create=True, commit=True, use_kwargs=False )
def test_route_with_view(self): @self.app.get('/', apply=[accept_only_kwargs]) def test(db): pass self.app.install(sqlalchemy.Plugin(self.engine, Base.metadata)) self._request_path('/')
def _install_plugin(engine=None, plugin=None): if not engine: logger.info('Creating in-memory db...') engine = create_engine('sqlite:///:memory:', echo=False) if not plugin: logger.info('Creating SQLAlchemy Plugin...') plugin_config = dict(keyword='db', create=False, commit=True, use_kwargs=True) plugin = sqlalchemy.Plugin(engine, **plugin_config) app.install(plugin) Base.metadata.create_all(engine)
def main(): args = get_user_arguments() app.settings = get_config(args.config_file) engine = create_engine(app.settings.connect_string, echo=False) plugin = sqlalchemy.Plugin(engine, Base.metadata, keyword='db', create=True, commit=True, use_kwargs=False) app.install(plugin) app.org = Organize(engine) bottle.run(app, host=args.ip, port=args.port, server="cherrypy")
def run_server(): # database setup engine = create_engine('sqlite:///:memory:', echo=True) app.models.base.Base.metadata.create_all(engine) # initialize database Session = sessionmaker(bind=engine) session = Session() register_users(session) session.commit() session.close() # run server install(orm.Plugin( engine, keyword='db', )) run(host='localhost', port=8080)
def main(): args = get_user_arguments() if args.quiet: logger.setLevel(logging.ERROR) else: logger.setLevel(logging.DEBUG if args.debug else logging.INFO) engine = create_engine(args.connect_string, echo=False) plugin = sqlalchemy.Plugin(engine, Base.metadata, keyword='db', create=True, commit=True, use_kwargs=False) app.install(plugin) app.mount("/api", api_app) bottle.run(app, host=args.ip, port=args.port, server="cherrypy")
def get_db_plugin(database_url): engine_config = configure_engine(database_url) Session.configure(bind=engine_config.engine) # pylint: disable=undefined-variable return sqlalchemy.Plugin( # SQLAlchemy engine created with create_engine function. engine_config.engine, # SQLAlchemy metadata, required only if create=True. Base.metadata, # Keyword used to inject session database in a route (default 'db'). keyword='db', # If it is true, execute `metadata.create_all(engine)` when plugin is applied (default False). create=True, # If it is true, plugin commit changes after route is executed (default True). commit=False, # If it is true and keyword is not defined, plugin uses **kwargs argument to inject session database (default False). use_kwargs=False, create_session=Session)
def __init__(self, server='auto', host='0.0.0.0', port=8080, db_url='sqlite:///:memory:', db_echo=False, reloader=False, debug=False, template_path='./bottleplate/app/views/'): self.server_type = server self.host = host self.port = port self.reloader = reloader self.debug = debug self.app = bottle.Bottle() routes.setup_routing(self.app) if template_path not in bottle.TEMPLATE_PATH: bottle.TEMPLATE_PATH.append(template_path) if './' in bottle.TEMPLATE_PATH: bottle.TEMPLATE_PATH.remove('./') if './views' in bottle.TEMPLATE_PATH: bottle.TEMPLATE_PATH.remove('./views') bottle.debug(self.debug) engine = create_engine(db_url, echo=db_echo) sqlalchemy_plugin = sqlalchemy.Plugin(engine, Base.metadata, keyword='db', create=True, commit=True, use_kwargs=False) self.app.install(sqlalchemy_plugin)
from bottle import request, response import sqlalchemy logger = logging.getLogger(__name__) app = application = Bottle() try: app.install(builtins.bottle_sqlalchemy) except AttributeError: # setup logging logging.basicConfig(format=os.environ.get('SV_LOGGING_FORMAT'), level=os.environ.get('SV_LOGGING_LEVEL')) # handle standalone service engine = create_engine(os.environ.get('SV_DB_CONNECTION'), echo=False) sqla_plugin = bottle_sqlalchemy.Plugin(engine, keyword="db") app.install(sqla_plugin) sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/..') import models from models import Employee, Interviewer @app.route('/employee', method=['OPTIONS', 'GET']) def index(db): employees = db.query(Employee).all() return json.dumps([r.as_dict() for r in employees], default=models.alchemyencoder)
from json import dumps import string from bs4 import BeautifulSoup app = default_app() app.config.load_config('api.conf') app.config.setdefault('api.db', 'sqlite:///:memory:') app.config.setdefault('api.base', 'http://localhost:8080') app.config.setdefault('api.queuedir', '/tmp') Base = declarative_base() engine = create_engine(app.config['api.db'], echo=False) plugin = sqlalchemy.Plugin(engine, keyword='db', commit=True, use_kwargs=False) app.install(plugin) class Expression(FullText, Base): __tablename__ = 'expression' __fulltext_columns__ = ('description', 'title', 'credit') id = Column(INTEGER(unsigned=True, zerofill=True), Sequence('expression_id_seq', start=1, increment=1), primary_key=True) title = Column(String(500)) description = Column(String(2048)) # # Allowed: Any CC URI + defined by rightsstatements.org #
# -*- coding: utf-8 -*- from bottle.ext import sqlalchemy from sqlalchemy import create_engine from sakuya.config import get_config from sakuya.models import sakuya_db, db_monitor URI_FORMAT = '%(adapter)s://%(username)s:%(password)s@%(host)s:%(port)d/%(database)s?charset=utf8&use_unicode=1' db_config = get_config('database') engine_sakuya_db = create_engine(URI_FORMAT % db_config['sakuya_db'], echo=db_config['sakuya_db']['echo'], pool_recycle=3600) plugin_sakuya_db = sqlalchemy.Plugin(engine_sakuya_db, sakuya_db.Base.metadata, keyword='sakuya_db', use_kwargs=True) engine_db_monitor = create_engine(URI_FORMAT % db_config['db_monitor'], echo=db_config['db_monitor']['echo'], pool_recycle=3600) plugin_db_monitor = sqlalchemy.Plugin(engine_db_monitor, db_monitor.Base.metadata, keyword='db_monitor', use_kwargs=True) def init_db(): sakuya_db.Base.metadata.create_all(bind=engine_sakuya_db)
from bottle import run, route, template, static_file, request, hook, redirect from beaker.middleware import SessionMiddleware from functools import wraps from bottle.ext import sqlalchemy from sqlalchemy import create_engine, Column, Integer, Sequence, String, Text from sqlalchemy.ext.declarative import declarative_base from uuid import uuid4 import random from sys import argv Base = declarative_base() engine = create_engine('mysql+pymysql://1505982309:[email protected]/1505982309_lverk') app = bottle.app() plugin = sqlalchemy.Plugin(engine, keyword='db') app.install(plugin) session_opts = { 'session.cookie_expires': True, 'session.encrypt_key': 'jhfkjshgjshgfjfdhfgenejnjvnjfnvjnjsvsljflsjfak', 'session.httponly': True, 'session.timeout': 3600 * 24, 'session.type': 'cookie', 'session.validate_key': True, } app = SessionMiddleware(app, session_opts) class user(Base): __tablename__='user'
if sys.version_info[0] == 3: xrange = range _is_pypy = hasattr(sys, "pypy_version_info") DBDRIVER = "mysql+pymysql" if _is_pypy else "mysql" DBHOSTNAME = "tfb-database" DATABASE_URI = ( "%s://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world?charset=utf8" % (DBDRIVER, DBHOSTNAME)) app = Bottle() Base = declarative_base() db_engine = create_engine(DATABASE_URI) plugin = sqlalchemy.Plugin(db_engine, keyword="db") app.install(plugin) # Engine for raw operation. Use autocommit. raw_engine = create_engine(DATABASE_URI, connect_args={"autocommit": True}, pool_reset_on_return=None) class World(Base): __tablename__ = "World" id = Column(Integer, primary_key=True) randomNumber = Column(Integer) def serialize(self): """Return object data in easily serializeable format"""
import sys from operator import attrgetter, itemgetter from functools import partial try: import ujson as json except ImportError: import json app = Bottle() app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'mysql://*****:*****@DBHOSTNAME:3306/hello_world?charset=utf8' Base = declarative_base() db_engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI']) plugin = sqlalchemy.Plugin( db_engine, keyword='db', ) app.install(plugin) if sys.version_info[0] == 3: xrange = range class World(Base): __tablename__ = "World" id = Column(Integer, primary_key=True) randomNumber = Column(Integer) # http://stackoverflow.com/questions/7102754/jsonify-a-sqlalchemy-result-set-in-flask @property def serialize(self):
from models import Base #builtins.base = Base = declarative_base() # setup logging logger = logging.getLogger(__name__) logging.basicConfig(format=os.environ.get('SV_LOGGING_FORMAT'), level=os.environ.get('SV_LOGGING_LEVEL')) app = application = Bottle() # reference db in builtins - shares in-memory sqlite across apps engine = create_engine(os.environ.get('SV_DB_CONNECTION'), echo=True) builtins.bottle_sqlalchemy = bottle_sqlalchemy.Plugin(engine, Base.metadata, keyword="db", create=True, commit=True) app.install(builtins.bottle_sqlalchemy) # import apps from candidate.candidate_service import app as canApp from employee.employee_service import app as empApp from job.job_service import app as jobApp app.merge(canApp) app.merge(empApp) app.merge(jobApp) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-l",
from bottle import Bottle, request from bottle.ext import sqlalchemy from datetime import datetime, timedelta from . import config from . import db from .db import CryptoKey app = Bottle() app.install( sqlalchemy.Plugin( db.engine, # SQLAlchemy engine created with create_engine function. db.Base.metadata, # SQLAlchemy metadata, required only if create=True. keyword= 'db', # Keyword used to inject session database in a route (default 'db'). create= True, # If it is true, execute `metadata.create_all(engine)` when plugin is applied (default False). commit= True, # If it is true, plugin commit changes after route is executed (default True). )) def validate_request(r, fields): message = None if not r: message = "no params given" if not message: for field in fields: if field not in r: message = "missing mandatory parameter '%s'" % field break if message:
from modeles.periode import Periode from modeles.zone import Zone from modeles.zone_base import ZoneBase from modeles.zone_image import ZoneImage from modeles.zone_video import ZoneVideo from modeles.zone_table import ZoneTable from modeles.ligne import Ligne from modeles.cellule import Cellule from modeles.administrateur import Administrateur from modeles.base import Base # Initialisation de l'application «Bottle» app = Bottle() # Installation du plugin «SQLAlchemy» dans l'application de «Bottle» app.install(sqlalchemy.Plugin(create_engine('sqlite:///src//data//database.db'), keyword='db', commit=True, use_kwargs=False)) # Obtention du port à utiliser par le server via la console port_choisi = "" while not port_choisi.isdigit(): port_choisi = input("Entrez un port sur lequel héberger le serveur : ") print("\nVoici votre adresse IP : " + socket.gethostbyname(socket.gethostname()) + "\n") #=============================================================================== # Authentification #=============================================================================== def verifier_session(func): """ Décorateur de fonction qui vérifie l'authenticité de la session du navigateur.
from bottle import HTTPError from bottle.ext import sqlalchemy from sqlalchemy import create_engine, Column, Integer, Sequence, String from sqlalchemy.types import DateTime, Date, Boolean from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() engine = create_engine('sqlite:///test.db', echo=False) app = bottle.Bottle() plugin = sqlalchemy.Plugin( engine, # SQLAlchemy engine created with create_engine function. Base.metadata, # SQLAlchemy metadata, required only if create=True. keyword= 'db', # Keyword used to inject session database in a route (default 'db'). create= True, # If it is true, execute `metadata.create_all(engine)` when plugin is applied (default False). commit= True, # If it is true, plugin commit changes after route is executed (default True). use_kwargs= False # If it is true and keyword is not defined, plugin uses **kwargs argument to inject session database (default False). ) app.install(plugin) class Group(Base): __tablename__ = 'group' id = Column(Integer, Sequence('id_seq'), primary_key=True) name = Column(String(8), unique=True) nrusers = Column(Integer) description = Column(String) # Описание группы - цель
def authorize(fail_redirect='login', role='user'): full_fail_redirect = get_redirect_url(fail_redirect) aaa.require(fail_redirect=full_fail_redirect, role=role) def isDevMode(): return devMode == "enabled" # Section: Main app app = bottle.default_app() if isDevMode(): app.catchall = False dbPlugin = sqlalchemy.Plugin(models.base.engine, keyword='db') app.install(dbPlugin) session_opts = { 'session.cookie_expires': True, 'session.encrypt_key': sessionEncryptKey, 'session.httponly': True, 'session.timeout': 3600 * 24, # 1 day 'session.type': 'cookie', 'session.validate_key': True, 'session.auto': True } sessionApp = SessionMiddleware(app, session_opts) # Put the cork object on the base template bottle.BaseTemplate.defaults['aaa'] = aaa
def get_plugin(): return sqlalchemy.Plugin(engine, metadata, keyword='orm')
def create_plugin(engine, config): sqlalchemy.Plugin(engine, **config)
def _install_plugin(self, *args, **kwargs): self.app.install(sqlalchemy.Plugin(*args, **kwargs))
import bottle bottle.BaseRequest.MEMFILE_MAX = 1024 * 1024 * 1024 from bottle import request, static_file, view, template, redirect from bottle.ext import sqlalchemy from sqlalchemy import create_engine, Column, \ Integer, String, DateTime, ForeignKey, and_ from sqlalchemy.ext.declarative import declarative_base from ezdeploy import cf from ezdeploy.env import ENV Base = declarative_base() engine = create_engine('sqlite:///deploy.db', echo=True) app = bottle.Bottle() plugin = sqlalchemy.Plugin(engine, Base.metadata, create=True) app.install(plugin) class Package(Base): __tablename__ = 'packages' purl = Column(String(1024), primary_key=True) service = Column(String(256)) env = Column(String(256)) changelog = Column(String(1024)) pdate = Column(DateTime()) class Deploy(Base): __tablename__ = 'deploys'
def test_without_metadata(self): sqlalchemy.Plugin(self.engine, create=False)
from sqlalchemy.ext.declarative import declarative_base from bottle.ext import sqlalchemy from wtforms.form import Form from wtforms import validators from wtforms import StringField, IntegerField, TextAreaField Base = declarative_base() engine = create_engine('sqlite:///:memory:', echo=True) # bottle-sqlalchemyの設定 plugin = sqlalchemy.Plugin( engine, Base.metadata, keyword='db', # 関数内で挿入される場合の変数名 create=True, # テーブルを作成するか commit=True, # 関数終了時にコミットするか use_kwargs=False) # プラグインのインストール bottle.install(plugin) class Book(Base): # booksテーブル __tablename__ = 'books' # カラムの定義 id = Column(Integer, primary_key=True) title = Column(Unicode(100), nullable=False)
def test_without_metadata_create_table_raises(self): plugin = sqlalchemy.Plugin(self.engine, create=True) self.assertRaises(bottle.PluginError, self.app.install, plugin)
import bottle_session 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() 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_session) app.install(plugin) from app.controllers import default from app.models import tables
redirect, response, error, abort, ) from bottle.ext import sqlalchemy from app.config import DOMAIN from app.models import engine, Base, User from app.utils import create_key_pair, get_webfinger from app.auth import sign_up app = Bottle() # Plugins sqlalchemy_plugin = sqlalchemy.Plugin(engine, Base.metadata, keyword="db", create=True) app.install(sqlalchemy_plugin) PROJECT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_PATH.insert(0, "{0}/templates".format(PROJECT_PATH)) def post_get(name, default=""): return request.POST.get(name, default).strip() @app.get("/") def home(): return {"message": "hello world"}