Beispiel #1
0
def main():
    # imported here to avoid cycles
    import httpshare

    # get the QR code to display properly on MS platforms
    if sys.platform.startswith(('win', 'cygwin')):
        import colorama
        colorama.init()

    print('httpshare version {}'.format(httpshare.version))
    print()
    print('You can use {} to exit the program.'.format(THE_INTERRUPT_KEY))
    print()

    options = docopt.docopt(__doc__)

    addr = options['--address']
    if addr is None:
        s = socket.socket()
        try:
            s.connect(LANDMARK)
            addr = s.getsockname()[0]
        except socket.error:
            print("Guessing my network address failed.")
            print(
                "You can provide a network address to serve on using --address"
            )
            traceback.print_exc(file=sys.stdout)
            sys.exit(1)
        finally:
            s.close()

    app = bottle.load_app('httpshare.app')
    app.config.update(
        'httpshare',
        directory=options['--directory'],
        all=options['--all'],
    )

    httpd = wsgiref.simple_server.make_server(addr, 0, app)
    url = 'http://{}:{}'.format(addr, httpd.server_port)

    if sys.stdout.isatty():
        q = qrcode.QRCode()
        q.add_data(url)
        try:
            q.print_ascii(tty=True)
        except UnicodeError:
            q.print_tty()
    print(url)

    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
Beispiel #2
0
def build_application(conf):
    """Do some setup and return the wsgi app."""
    if isinstance(conf.adapter_options, list):
        conf['adapter_options'] = {
            key: val
            for _dict in conf.adapter_options for key, val in _dict.items()
        }
    elif conf.adapter_options is None:
        conf['adapter_options'] = {}
    else:
        conf['adapter_options'] = copy.copy(conf.adapter_options)

    # get wsgi app the same way bottle does if it receives a string.
    conf['app'] = conf.app or bottle.default_app()
    if isinstance(conf.app, six.string_types):
        conf['app'] = bottle.load_app(conf.app)

    def _find_bottle_app(_app):
        """Lookup the underlying Bottle() instance."""
        while hasattr(_app, 'app'):
            if isinstance(_app, bottle.Bottle):
                break
            _app = _app.app
        assert isinstance(_app, bottle.Bottle), 'Could not find Bottle app.'
        return _app

    bottle_app = _find_bottle_app(conf.app)
    bottle_app.route(path='/_simpl', method='GET', callback=_version_callback)

    def _show_routes():
        """Conditionally print the app's routes."""
        if conf.app and not conf.quiet:
            if conf.reloader and os.getenv('BOTTLE_CHILD'):
                LOG.info("Running bottle server with reloader.")
            elif not conf.reloader:
                pass
            else:
                return
            routes = fmt_routes(bottle_app)
            if routes:
                print('\n{}'.format(routes), end='\n\n')

    _show_routes()
    return conf.app
Beispiel #3
0
def play(ctx, mode="development"):
    """ Start Application """
    import bottle
    from package.utils.loader import Loader
    from package.tasks import main

    config = Loader().configuration()

    if mode in config["api"]:
        print(f"Starting with {config['api'][mode]}")

        # https://docs.python.org/3/library/tracemalloc.html
        if mode == "development":
            import tracemalloc

            tracemalloc.start()

        # Start App
        bottle.run(bottle.load_app("package.main:app"), **config["api"][mode])

    # Default Message
    else:
        print(f"Please {mode} key under config.yml")
Beispiel #4
0
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# --------------------------------------------------------------------------- #
# Imports
# --------------------------------------------------------------------------- #

# Framework
import bottle

# --------------------------------------------------------------------------- #
# Application
# --------------------------------------------------------------------------- #

app = bottle.Bottle()

app.mount("/v1", bottle.load_app("package.v1:app"))
app.mount("/v2", bottle.load_app("package.v2:app"))

app.mount("/doc", bottle.load_app("package.doc:app"))

# --------------------------------------------------------------------------- #
# END
# --------------------------------------------------------------------------- #

# EOF
Beispiel #5
0
import bottle
from bottle import Bottle, run, debug
from bottle import route, request, response, abort, error
from bottle import BaseTemplate, view, template
from bottle import static_file

# Bottle application
app = bottle.app()

# Loads and mounts api app
# FIXME: Mounted routes issue with app.get_url()
#        The response object within mounted app does has no effect
#        - try app.load_app() ?
from api import api
app.mount("/api/", bottle.load_app('api.api:app'))

# Makes get_url available to templates
BaseTemplate.defaults['get_url'] = app.get_url

# Application methods
@app.route('/')
@app.route('/live')
@view('live')
def home():
    return {}

@app.route('/calendar')
@view('calendar')
def calendar():
    return {}
Beispiel #6
0
        os.mkdir(DIR_LOGS)
    logging.basicConfig(filename=os.path.join(
        DIR_LOGS,
        datetime.datetime.today().strftime('%Y-%m-%d %H.%M.%S.log')),
                        format='%(asctime)s '
                        '%(levelname)-8s '
                        '%(filename)-25s '
                        'line: %(lineno)-5d '
                        '%(funcName)-30s '
                        'pid: %(process)-8d '
                        '%(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.DEBUG)

    logging.debug('Loading application app_webquery')
    root_app = bottle.load_app('app_webquery.app:setup()')
    logging.debug('Loaded application app_webquery')

    logging.debug('Loading configuration')
    general_configuration = configuration.get_config_obj(FILE_CONFIGURATION)
    startup_options = {
        'host': general_configuration.get(SECTION_SETTINGS, 'LISTEN'),
        'port': general_configuration.getint(SECTION_SETTINGS, 'PORT_NUMBER'),
        'debug': general_configuration.getboolean(SECTION_SETTINGS, 'DEBUG'),
        'reloader': general_configuration.getboolean(SECTION_SETTINGS,
                                                     'RELOADER'),
        'server': general_configuration.get(SECTION_SETTINGS, 'SERVER_TYPE')
    }
    # Parse command line arguments to override configuration settings
    cmd_parser = optparse.OptionParser(option_class=OptParseTypeFlag)
    cmd_parser.add_option('-s',
Beispiel #7
0
    os.mkdir(DIR_LOGS)
  logging.basicConfig(
    filename=os.path.join(DIR_LOGS, 
      datetime.datetime.today().strftime('%Y-%m-%d %H.%M.%S.log')),
    format='%(asctime)s '
      '%(levelname)-8s '
      '%(filename)-25s '
      'line: %(lineno)-5d '
      '%(funcName)-30s '
      'pid: %(process)-8d '
      '%(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    level=logging.DEBUG)
  
  logging.debug('Loading application app_webquery')
  root_app = bottle.load_app('app_webquery.app:setup()')
  logging.debug('Loaded application app_webquery')

  logging.debug('Loading configuration')
  general_configuration = configuration.get_config_obj(FILE_CONFIGURATION)
  startup_options = {
    'host': general_configuration.get(SECTION_SETTINGS, 'LISTEN'),
    'port': general_configuration.getint(SECTION_SETTINGS, 'PORT_NUMBER'),
    'debug': general_configuration.getboolean(SECTION_SETTINGS, 'DEBUG'),
    'reloader': general_configuration.getboolean(SECTION_SETTINGS, 'RELOADER'),
    'server': general_configuration.get(SECTION_SETTINGS, 'SERVER_TYPE')
  }
  # Parse command line arguments to override configuration settings
  cmd_parser = optparse.OptionParser(option_class=OptParseTypeFlag)
  cmd_parser.add_option('-s', '--server',
    action='store', choices=bottle.server_names.keys(),
Beispiel #8
0
    today = datetime.datetime.today()
    logging.basicConfig(filename=os.path.join(
        DIR_LOGS, today.strftime('%Y-%m-%d '
                                 '%H.%M.%S.log')),
                        format='%(asctime)s '
                        '%(levelname)-8s '
                        '%(filename)-25s '
                        'line: %(lineno)-5d '
                        '%(funcName)-30s '
                        'pid: %(process)-8d '
                        '%(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.DEBUG)

    logging.debug('Loading application app_webtools')
    root_app = bottle.load_app('app_webtools.app:setup()')
    logging.debug('Loaded application app_webtools')

    logging.debug('Loading configuration')
    general_config = configuration.get_config_obj(FILE_CONFIGURATION)
    general_options = {
        'host': general_config.get(SECTION_SETTINGS, 'LISTEN'),
        'port': general_config.getint(SECTION_SETTINGS, 'PORT_NUMBER'),
        'debug': general_config.getboolean(SECTION_SETTINGS, 'DEBUG'),
        'reloader': general_config.getboolean(SECTION_SETTINGS, 'RELOADER'),
        'server': general_config.get(SECTION_SETTINGS, 'SERVER_TYPE')
    }
    # Parse command line arguments to override configuration settings
    cmd_parser = optparse.OptionParser(option_class=OptParseTypeFlag)
    cmd_parser.add_option('-s',
                          '--server',