How to use the bottle.Bottle function in bottle

To help you get started, we’ve selected a few bottle examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mit-cml / appinventor-sources / appinventor / misc / emulator-support / aiWinStarter.py View on Github external
#!/usr/bin/python
from bottle import run,route,app,request,response,template,default_app,Bottle,debug,abort
import sys
import os
import platform
import subprocess
import re
#from flup.server.fcgi import WSGIServer
#from cStringIO import StringIO
#import memcache

app = Bottle()
default_app.push(app)

VERSION = "2.2"

platforms = platform.uname()[0]
print "Platform = %s" % platforms
if platforms == 'Windows':               # Windows
    PLATDIR = os.environ["ProgramFiles"]
    PLATDIR = '"' + PLATDIR + '"'
    print "AppInventor tools located here: %s" % PLATDIR
else:
    sys.exit(1)

@route('/ping/')
def ping():
    response.headers['Access-Control-Allow-Origin'] = '*'
github jbruce12000 / kiln-controller / kiln-controller.py View on Github external
print ("Could not import config file.")
    print ("Copy config.py.EXAMPLE to config.py and adapt it for your setup.")
    exit(1)

logging.basicConfig(level=config.log_level, format=config.log_format)
log = logging.getLogger("kiln-controller")
log.info("Starting kill controller")

script_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, script_dir + '/lib/')
profile_path = os.path.join(script_dir, "storage", "profiles")

from oven import Oven, Profile
from ovenWatcher import OvenWatcher

app = bottle.Bottle()
oven = Oven()
ovenWatcher = OvenWatcher(oven)

@app.route('/')
def index():
    return bottle.redirect('/picoreflow/index.html')

@app.post('/api')
def handle_api():
    log.info("/api is alive")
    log.info(bottle.request.json)

    # run a kiln schedule
    if bottle.request.json['cmd'] == 'run':
        wanted = bottle.request.json['profile']
        log.info('api requested run of profile = %s' % wanted)
github j0lv3r4 / dnscheck / index.py View on Github external
__version__ = "0.1.0"

import os
import dns.resolver
from dns.exception import Timeout
from bottle import Bottle, request, redirect
from cors import CorsPlugin, enable_cors
from tld import exceptions
from utils import jsonify, validate_domain, resolve_domain, get_authoritative_nameserver

app = Bottle()

ORIGINS = os.getenv("ORIGINS", "*").split(",")
ENV = os.getenv("ENV", "development")


@app.get("/")
def redirect_to_app():
    return redirect("https://dnscheck.now.sh")


@enable_cors
@app.post("/authoritative_nameserver")
def post_auth_ns():
    domain = request.forms.get("domain")

    if domain is None:
github looprock / megaphone / megaphone / megaphone.py View on Github external
import json
import sys
import os
import re
from bottle import Bottle
import time
import urllib2
import shutil
import bottle
from ConfigParser import SafeConfigParser
import logging
import multiprocessing
logging.basicConfig()

app = Bottle()

_basedir = os.path.abspath(os.path.dirname(__file__))
config = SafeConfigParser()
try:
    config.read('%s/megaphone.conf' % _basedir)
    DEBUG = config.getboolean('settings', 'DEBUG')
    QUIET = config.getboolean('settings', 'QUIET')
    CACHEDIR = config.get('settings', 'CACHEDIR')
    CACHEFILE = config.get('settings', 'CACHEFILE')
    WSGISERVER = config.get('settings', 'WSGISERVER')
    CACHE = "%s/%s" % (CACHEDIR, CACHEFILE)
    LISTEN = config.get('settings', 'LISTEN')
    PORT = config.get('settings', 'PORT')
    TIMEOUT = float(config.get('settings', 'TIMEOUT'))
except:
    print "INFO: unable to find config file, skipping"
github quarkslab / irma / frontend / api / modules / docs / docsapi.py View on Github external
from bottle import Bottle
from frontend.api.modules.webapi import WebApi
from lib.irma.common.utils import IrmaFrontendReturn


docs_app = Bottle()


# ==========
#  Docs api
# ==========

class DocsApi(WebApi):
    _mountpath = "/docs"
    _app = Bottle()

    def __init__(self):
        self._app.route('/', callback=self._resource_listing)
        self._app.route('/', callback=self._api_declaration)
        self._base = 'frontend/api/modules/docs/specs'

    def _resource_listing(self):
        try:
            with open('{path}/api-docs.yml'.format(path=self._base)) as file:
                data = yaml.load(file)
            bottle.response.content_type = "application/json"
            return json.dumps(data)
        except Exception as e:
            return IrmaFrontendReturn.error(str(e))

    def _api_declaration(self, filename="files"):
github merenlab / anvio / anvio / bottleroutes.py View on Github external
__copyright__ = "Copyleft 2015-2018, the Meren Lab (http://merenlab.org/)"
__credits__ = ["A. Murat Eren"]
__license__ = "GPL 3.0"
__version__ = anvio.__version__
__maintainer__ = "Ozcan Esen"
__email__ = "ozcanesen@gmail.com"


run = terminal.Run()
progress = terminal.Progress()

# increase maximum size of form data to 100 MB
BaseRequest.MEMFILE_MAX = 1024 * 1024 * 100


class BottleApplication(Bottle):
    def __init__(self, interactive, mock_request=None, mock_response=None):
        super(BottleApplication, self).__init__()
        self.interactive = interactive

        if self.interactive:
            self.args = self.interactive.args
            A = lambda x: self.args.__dict__[x] if x in self.args.__dict__ else None
            self.read_only = A('read_only')
            self.browser_path = A('browser_path')
            self.export_svg = A('export_svg')
            self.server_only = A('server_only')
            self.user_server_shutdown = A('user_server_shutdown')
            self.password_protected = A('password_protected')
            self.password = ''
            self.authentication_secret = ''
            if self.password_protected:
github duckworthd / sqlrest / sqlrest / server.py View on Github external
def attach_routes(db, app=None, prefix=None, caching=None, editing=False):
  """Attach sqlrest routes to app"""

  # if connector isn't specified, choose one that's asynchronous
  if db.uri.startswith("mysql://"):
    db.uri = re.sub("^mysql://", "mysql+mysqlconnector://", db.uri)
  elif config.uri.startswith("postgresql://"):
    db.uri = re.sub("^postgresql://", "postgresql+psycopg2://", db.uri)

  if prefix is None:
    prefix = ''

  # create app, if necessary
  if app is None:
    app = bottle.Bottle()

  # connect to db
  db = Database(db)

  # add json routes
  app = JsonBottle(app)
  app.error(500)(error_handler)
  if caching is None:
    app.json_route(prefix + "/tables"           )(db.tables    )
    app.json_route(prefix + "/:table/columns"   )(db.columns   )
    app.json_route(prefix + "/:table/aggregate" )(db.aggregate )
    app.json_route(prefix + "/:table/select"    )(db.select    )
  else:
    # caching routes, too
    app = CachingBottle(app, RedisCache(**caching.config))
    app.json_route(prefix + "/tables"           )(app.memoize(caching.timeouts.tables    )(db.tables    ))
github osm-fr / osmose-frontend / bottle.py View on Github external
def merge(self, routes):
        ''' Merge the routes of another :class:`Bottle` application or a list of
            :class:`Route` objects into this application. The routes keep their
            'owner', meaning that the :data:`Route.app` attribute is not
            changed. '''
        if isinstance(routes, Bottle):
            routes = routes.routes
        for route in routes:
            self.add_route(route)
github bernard357 / shellbot / shellbot / server.py View on Github external
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
from bottle import Bottle

from .context import Context


class Server(Bottle):
    """
    Serves web requests
    """

    def __init__(self,
                 context=None,
                 httpd=None,
                 route=None,
                 routes=None,
                 check=False):
        """
        Serves web requests

        :param context: global context for this process
        :type context: Context
github ncornette / Python-Markdown-Editor / markdown_editor / web_edit.py View on Github external
ACTION_TEMPLATE = u"""\
<input value="{}" name="SubmitAction" class="btn btn-default" type="submit">"""

SAVE_ACTION_TEMPLATE = u"""\
<input value="{}" class="btn btn-default" type="button">"""


class WebAction(Action):

    def __init__(self, name, function, key=None, action_template=ACTION_TEMPLATE):
        Action.__init__(self, name, function, key)
        self.html = action_template.format(name)


app = Bottle()


def action_close(_):
    return "Server Stopped", False


def action_preview(_):
    return None, '/preview'


def handle_form_action(action):
    content, location = action(app.config['myapp.document'])
    if content and location:
        return content
    elif location is True:
        redirect('/')