def run_rest_server(manager, debug, num_processes, num_threads): """Runs the REST server.""" host = manager.config['server']['rest_host'] port = manager.config['server']['rest_port'] install(SaveEnvironmentPlugin(manager)) install(CheckJsonPlugin()) install(LoggingPlugin()) install(oauth2_provider.check_oauth()) install(CookieAuthenticationPlugin()) install(UserVerifiedPlugin()) install(ErrorAdapter()) for code in xrange(100, 600): default_app().error(code)(error_handler) root_app = Bottle() root_app.mount('/rest', default_app()) bottle.TEMPLATE_PATH = [os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'views')] # We use gunicorn to create a server with multiple processes, since in # Python a single process uses at most 1 CPU due to the Global Interpreter # Lock. sys.argv = sys.argv[:1] # Small hack to work around a Gunicorn arg parsing # bug. None of the arguments to cl should go to # Gunicorn. run(app=root_app, host=host, port=port, debug=debug, server='gunicorn', workers=num_processes, worker_class='gthread', threads=num_threads, timeout=5 * 60)
def testWithStatement(self): default = bottle.default_app() inner_app = bottle.Bottle() self.assertEqual(default, bottle.default_app()) with inner_app: self.assertEqual(inner_app, bottle.default_app()) self.assertEqual(default, bottle.default_app())
def run_rest_server(manager, debug, num_processes, num_threads): """Runs the REST server.""" host = manager.config['server']['rest_host'] port = manager.config['server']['rest_port'] install(SaveEnvironmentPlugin(manager)) install(CheckJsonPlugin()) install(LoggingPlugin()) install(oauth2_provider.check_oauth()) install(CookieAuthenticationPlugin()) install(UserVerifiedPlugin()) install(PublicUserPlugin()) install(ErrorAdapter()) # Replace default JSON plugin with one that handles datetime objects # Note: ErrorAdapter must come before JSONPlugin to catch serialization errors uninstall(JSONPlugin()) install(JSONPlugin(json_dumps=DatetimeEncoder().encode)) # JsonApiPlugin must come after JSONPlugin, to inspect and modify response # dicts before they are serialized into JSON install(JsonApiPlugin()) for code in xrange(100, 600): default_app().error(code)(error_handler) root_app = Bottle() root_app.mount('/rest', default_app()) # Look for templates in codalab-worksheets/views bottle.TEMPLATE_PATH = [ os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'views' ) ] # Increase the request body size limit to 8 MiB bottle.BaseRequest.MEMFILE_MAX = 8 * 1024 * 1024 # We use gunicorn to create a server with multiple processes, since in # Python a single process uses at most 1 CPU due to the Global Interpreter # Lock. sys.argv = sys.argv[:1] # Small hack to work around a Gunicorn arg parsing # bug. None of the arguments to cl should go to # Gunicorn. run( app=root_app, host=host, port=port, debug=debug, server='gunicorn', workers=num_processes, worker_class='gthread', threads=num_threads, worker_tmp_dir='/tmp', # don't use globally set tempdir timeout=5 * 60, )
def main(): opts = parse_args() if opts.debug: bottle.debug(True) if opts.config: cfdict = yaml.load(open(opts.config, 'r')) bottle.default_app().config.update(cfdict) run(host=opts.host, port=int(opts.port), reloader=opts.reload)
def main(): sys.path.append(os.path.dirname(os.path.abspath(__file__))) os.chdir(os.path.dirname(os.path.abspath(__file__))) cwd = os.getcwd() print(cwd) # Start the Bottle webapp bottle.debug(True) bottle.default_app() # bottle.run(host='localhost', port=8080, app=app, quiet=False, reloader=True) print("Starting bottle...") bottle.run(host='localhost', port=8080, app=app, quiet=False)
def setUp(self): ''' Create a new Bottle app set it as default_app and register it to urllib2 ''' self.port = 61382 self.host = 'localhost' self.app = bottle.Bottle() self.oldapp = bottle.default_app() bottle.default_app(self.app) self.server = TestServer(host=self.host, port=self.port) self.urlopen = self.server.urlopen self.thread = threading.Thread(target=bottle.run, args=(), kwargs=dict(app=self.app, server=self.server, quiet=True)) self.thread.start() self.server.event_running.wait()
def main(): """Function run when the tool is called.""" print(__doc__) args = parse_args() application = default_app() application.mount('/cgi/', webapp.application) run(host=args.bind_address, port=args.port, debug=DEBUG)
def do_init(): logging.basicConfig(format='%(asctime)s: [%(levelname)s]: %(message)s', level=logging.DEBUG) parser = ArgumentParser('netcapsule browser manager') parser.add_argument('--my-ip') parser.add_argument('--pywb-ip') parser.add_argument('--start-url') parser.add_argument('--start-ts') r = parser.parse_args() global my_ip my_ip = r.my_ip global pywb_ip pywb_ip = r.pywb_ip global start_url start_url = r.start_url if '://' not in start_url: start_url = 'http://' + start_url # not used here for now global start_ts start_ts = r.start_ts global redis redis = StrictRedis(REDIS_HOST) return default_app()
def web_main(): app = bottle.default_app() app.config['cfg'] = utils.cfg app.config['db.engine'] = utils.engine app.config['db.session'] = utils.sess session_opts = { 'session.type': 'ext:database', 'session.url': utils.cfg.get('db', 'url'), 'session.lock_dir': '/var/lock', 'session.cookie_expires': 3600, 'session.auto': True } application = SessionMiddleware(app, session_opts) from urlparse import urlparse u = urlparse(utils.cfg.get('web', 'baseurl')) app.config['baseurl'] = u app.config['basepath'] = u.path @bottle.route(path.join(u.path, 'static/<filename:path>')) def _static(filename): return bottle.static_file(filename, root='static/') import usr import mgr return application
def startServer(): import bottle app = bottle.default_app() # create bottle app loadErrors(app) loadWebUI(app) app = bottle.app() session_opts = { 'session.type': 'file', 'session.cookie_expires': 9000, 'session.data_dir': 'data', 'session.auto': True } app = SessionMiddleware(app, session_opts) bottle.run(app=app, server='paste', host="0.0.0.0", port=8030, debug=True, interval=1, quiet=False)
def v_home(): phase, season, week = nfldb.current(db) params = { 'season': season, 'phase': phase, 'week': week } url = bottle.default_app().get_url('v_games', **params) bottle.response.status = 302 bottle.response.set_header('Location', url) return ''
def init(configfile='config.yaml', redis_url=None): logging.basicConfig(format='%(asctime)s: [%(levelname)s]: %(message)s', level=logging.DEBUG) logging.debug('') # set boto log to error boto_log = logging.getLogger('boto') if boto_log: boto_log.setLevel(logging.ERROR) config = load_yaml_config(configfile) if not redis_url: redis_url = expandvars(config['redis_url']) redis_obj = StrictRedis.from_url(redis_url) config['redis_warc_resolver'] = DynRedisResolver(redis_obj, remote_target=config['remote_target'], proxy_target=config['proxy_target']) bottle_app = default_app() final_app, cork = init_cork(bottle_app, redis_obj, config) webrec = WebRec(config, cork, redis_obj) bottle_app.install(webrec) pywb_dispatch = PywbDispatcher(bottle_app) init_routes(webrec) pywb_dispatch.init_routes() return final_app
def application(environ, start_response): # how to propagate static resources # default_app().mount('/static', static_app) p = environ.get('PATH_INFO', '') f = os.path.join(STATIC_ROOT, 'root') + p if '.' in p and '..' not in p and '/' not in p[1:] and \ os.path.isfile(f): environ['PATH_INFO'] = '/root' + p return static_app(environ, start_response) hostname = environ.get('HTTP_HOST', '').lower() all_apps = [tools_app, dict_app]+default_app for app in all_apps: """ https://github.com/defnull/bottle/blob/0.11.6/bottle.py#L3226 default_app() will be the the last registered BottlePy App iteration ends at default_app() """ hostnames = getattr(app, 'hostnames', []) # print hostname, hostnames, all_apps if filter(lambda x:fnmatch(hostname, x), hostnames): return app(environ, start_response) return default_app()(environ, start_response)
def start(locust, hatch_rate, max): global _locust, _hatch_rate, _max _locust = locust _hatch_rate = hatch_rate _max = max app = bottle.default_app() wsgi.WSGIServer(('', 8089), app).start()
def mx_init_app(): import sqlite3 global G_app G_app = bottle.default_app() model.G_db = sqlite3.connect(os.path.join(PROJECT_ROOT, 'mixopterus.db')) # TODO: make connection pool... model.q_sqlite_init() def mx_routes(): G_app.route('/error', callback=mx_error500, metohd='GET') G_app.route('/', callback=mx_home, method='GET') G_app.route('/quiz', callback=mx_quiz, method='GET') G_app.route('/quiz/<quiz_id:int>', callback=mx_quiz_mark, method='GET') G_app.route('/quiz/<quiz_id:int>/<n:int>', callback=mx_quiz_mark, method=['POST', 'GET']) G_app.route('/quiz/<quiz_id:int>/end', callback=mx_quiz_finish, method=['POST', 'GET']) G_app.route('/static/<filename>', callback=mx_static, method='GET') G_app.route('/login', callback=mx_login, method=['POST', 'GET']) G_app.route('/logout', callback=mx_logout, method='GET') G_app.route('/admin', callback=mx_admin, method='GET') G_app.route('/admin/add_yaml_quiz', callback=mx_admin_add_yaml_quiz, method=['POST', 'GET']) G_app.route('/admin/delete_quiz', callback=mx_admin_del_quiz, method='POST') G_app.route('/admin/add_email_template', callback=mx_admin_add_email_template, method=['POST', 'GET']) G_app.route('/admin/edit_email_template/<etpl_id:int>', callback=mx_admin_edit_email_template, method=['POST', 'GET']) G_app.route('/admin/delete_email_template', callback=mx_admin_del_email_template, method='POST') G_app.route('/admin/add_quiz', callback=mx_admin_add_quiz, method=['POST', 'GET']) G_app.route('/admin/add_question', callback=mx_admin_add_question, method=['POST', 'GET']) G_app.route('/admin/add_answer', callback=mx_admin_add_answer, method=['POST', 'GET']) G_app.route('/admin/add_quiz_summary', callback=mx_admin_add_quiz_summary) G_app.route('/admin/edit_quiz/<quiz_id:int>', callback=mx_admin_add_quiz, method=['POST', 'GET']) G_app.route('/admin/edit_question', callback=mx_admin_add_question, method=['POST', 'GET']) G_app.route('/admin/edit_answer', callback=mx_admin_add_answer, method=['POST', 'GET']) mx_routes()
def get_template_path(): app = default_app() base_templates = os.path.join( app.config.home_path, 'share/share-python/templates/jinja2') app_templates = os.path.join(app.config.app_path, 'templates') return [base_templates, app_templates]
def get_api_routes(): # TODO: import modules individually and sort these routes by their # module name. This will keep Bundles and Bundle Permissions API together. # Then we can also load the docstrings of the modules themselves and print # those on each page. app = default_app() base2routes = defaultdict(list) bases = set() for route in app.routes: path = route.rule.split('/') base = path[1] if base in EXCLUDED_APIS: continue base2routes[base].append(route) bases.add(base) api_specs = [] for base in bases: default_name = ' '.join(base.title().split('-')) name = {'oauth2': 'OAuth2', 'cli': 'CLI', 'interpret': 'Worksheet Interpretation'}.get( base, default_name ) anchor = '-'.join(name.lower().split()) api_specs.append(APISpec(name, anchor, base2routes[base])) return api_specs
def test_503(self): """ WSGI: Server stopped (HTTP 503) """ @bottle.route('/') def test(): return 'bla' self.assertEqual(200, self.urlopen('/').code) bottle.default_app().serve = False self.assertEqual(503, self.urlopen('/').code)
def load_configs(filename): app = bottle.default_app() try: app.config.load_config(filename) except Exception as e: logging.error("Exception {0} in load_config".format(e)) exit(-1) logging.debug("Config : \n {0}".format(app.config)) for keys in app.config: if keys.startswith('keys.'): print keys keyfile = app.config[keys].replace('\"', '') logging.debug("Keyfile : {0}".format(keyfile.replace('\"', ''))) if not os.path.isfile(keyfile): print "Key file {0} missing!".format(keyfile) logging.error("Key file {0} missing!".format(keyfile)) exit(-1) with open(keyfile, 'r') as kf: ks = kf.readlines() sp = ks[1].split(',') app.config[keys] = kf.read() app.config["keys.key_id"] = sp[1] app.config["keys.key_secret"] = sp[2] app.config["keys.key_token"] = '' #print "keys : ", app.config[keys] if 'metadata.credurl' in app.config: update_creds_from_metadata_server(app) init(app) return app
def __init__(self): self.app = default_app() @hook('after_request') def log_all(): log_request(request, "%s %s " % (request.method, request.fullpath), logging.INFO) self.routes = {} files = os.listdir("routes") files.remove("__init__.py") for _file in files: if _file.endswith(".py"): module = _file.rsplit(".", 1)[0] try: log("Loading routes module '%s'..." % module, logging.INFO) mod = __import__("routes.%s" % module, fromlist=["Routes"]) self.routes[module] = mod.Routes(self.app, self) except Exception as e: log("Error loading routes module '%s': %s" % (module, e), logging.INFO) log("Finished loading routes modules.", logging.INFO)
def redirect_unauthenticated(redirect_url=None): redirect_url = redirect_url or reverse("index") no_auth = bottle.default_app().config.get("no_auth", False) def write_message(): messages.info(_("You have been logged out due to longer inactivity.")) if not no_auth and not is_user_authenticated(): # test silent silent = bottle.request.GET.get("silent", "false") == "true" silent = silent or bottle.request.POST.get("silent", "false") == "true" if not silent: write_message() if bottle.request.is_xhr: # "raise" JSON response if requested by XHR res = bottle.response.copy(cls=bottle.HTTPResponse) res.content_type = "application/json" res.body = json.dumps(dict(success=False, loggedOut=True, loginUrl=redirect_url)) res.status = 403 raise res # "raise" standard bottle redirect login_url = "%s?next=%s" % (redirect_url, bottle.request.fullpath) bottle.redirect(login_url)
def make_app(): app = make_middleware(default_app(), { 'toscawidgets.middleware.inject_resources': True, }, stack_registry=True, ) return app
def get_app(): app = default_app() default_config = { "nestegg_dir" : "{}/.nestegg".format(opath.expanduser('~')), "index_url": "https://pypi.python.org/simple", "port": 7654, "fresh": "0", } ini_file = lookup_config_file("nestegg.ini") if ini_file : logging.config.fileConfig(ini_file) config_file = lookup_config_file("nestegg.yml") if config_file : with open(config_file,"r") as in_config : config = get_config(load(in_config)) for key, value in default_config.items() : if not hasattr(config.nestegg,key): setattr(config.nestegg,key,value) else : config = get_config(default_config) neconfig = config.nestegg neconfig.pypi_dir = os.path.join(neconfig.nestegg_dir,"pypi") neconfig.checkout_dir = os.path.join(neconfig.nestegg_dir,"checkout") neconfig.source_dir = os.path.join(neconfig.nestegg_dir,"source_builds") neconfig.private_packages = set() os.makedirs(neconfig.pypi_dir,0o755, exist_ok=True) app.config['config'] = config return app
def _setup (self): self.application = bottle.default_app() bottle.debug(True) self.application.catchall = False server_setup.setup_server(self.application) self.http = Client(self.application, BaseResponse) self.reset_values_sent() self._cached_previous_response = None
def load_config(filename): app = bottle.default_app() try: app.config.load_config(filename) except Exception as e: logging.error("Exception {0} in load_config".format(e)) exit(-1) return app
def __init__(self, path, obj=None, app=None): self.path = path self.app = app or bottle.default_app() self.methods = {} if obj is not None: self.add_object(obj) self._make_handler()
def create_bottle(body, headers): path = '/hello/<account_id>/test' @bottle.route(path) def hello(account_id): limit = bottle.request.query.limit or '10' # NOQA return bottle.Response(body, headers=headers) return bottle.default_app()
def get_application(**kargs): ''' Takes configuration params for creating middleware app. @return: middleware app ''' Server.initialize(app=bottle.default_app(), **kargs) logging.debug('Main Web Service Started') return Server.get_application()
def application(environ=None, start_response=None): import bottle _setup_bottle(bottle, environ) _application = bottle.default_app() _application = session_start(bottle.default_app(), '/admin') from bottle import Jinja2Template from esteapp.controllers import test names = [] for m in [test]: names.append(m.__name__) if environ and start_response: _application = _application(environ, start_response) return _application
def main(): arguments = docopt(__doc__, version='PhotoBackup ' + __version__) if (arguments['init']): init_config() elif (arguments['run']): global config, app config = read_config() app = bottle.default_app() run(host="0.0.0.0", port=config['Port'], reloader=True)
#!/usr/bin/python3 import bottle import sqlite3 import datetime import calendar import os def parse_bool(string): return string.lower() in ['true', 't', 'yes', 'y'] dir_path = os.path.dirname(os.path.realpath(__file__)) bottle.default_app().config.load_config(os.path.join(dir_path, 'config.ini')) RESAMPLING = parse_bool(bottle.default_app().config['charts.resampling']) RESAMPLING_FREQUENCY = bottle.default_app( ).config['charts.resampling_frequency'] DATABASE_PATH = bottle.default_app().config['sqlite.db'] ROOT = bottle.default_app().config['server.root'] PORT = int(bottle.default_app().config['server.port']) BIND_ADDRESS = bottle.default_app().config['server.bind_address'] def resample(readings, start, end, frequency): import pandas as pd from resample import resample def write_reading(i, v):
def startServer(level='info', server='paste', host='0.0.0.0', port='8080', base='', cors=False, tls=False, certpath='/etc/pki/tls/certs/localhost.crt', keypath='/etc/pki/tls/certs/localhost.key', pempath='/etc/pki/tls/certs/localhost.pem', devel=False, coffee=False, opts=None, **kwas): ''' Starts up and runs web application server and salt api server Parameters: level = logging level string, default is 'info' server = server name string, default is 'paste' host = host address or domain name string, default is '0.0.0.0' port = port number string, default is '8080' base = url path base prefix string, default is '' cors = enable CORS if truthy, default is False tls = use tls/ssl if Truthy, default is False certpath = pathname string to ssl certificate file, default is '/etc/pki/tls/certs/localhost.crt' keypath = pathname string to ssl private key file, default is '/etc/pki/tls/certs/localhost.key' pempath = pathname string to ssl pem file with both cert and private key, default is '/etc/pki/tls/certs/localhost.pem' devel = generate main.html if truthy on each request in support of development default is False coffee = generate main.html to load and compile coffeescript if truthy when devel is true. Default is False kwas = additional keyword arguments dict that are passed as server options Does not return. ''' #so when using gevent can monkey patch before import bottle global gevented, gevent, bottle logger.setLevel(aiding.LOGGING_LEVELS[level]) gevented = False if server in ['gevent']: try: import gevent from gevent import monkey monkey.patch_all() gevented = True except ImportError as ex: #gevent support not available server = 'paste' # use default server tlsOptions = {} tlsOptions['paste'] = {'ssl_pem': pempath} tlsOptions['gevent'] = {'keyfile': keypath, 'certfile': certpath} tlsOptions['cherrypy'] = {'keyfile': keypath, 'certfile': certpath} options = dict(**kwas) if tls and server in tlsOptions: options.update(**tlsOptions[server]) # retrieve ssl options for server import bottle app = bottle.default_app() # create bottle app loadErrors(app) loadWebUI(app, devel=devel, coffee=coffee) loadSaltApi(app, opts) if cors: loadCors(app) app = rebase(base=base) logger.info("Running web application server '{0}' on {1}:{2}.".format( server, host, port)) if base: logger.info("URL paths rebased after base '{0}".format(base)) logger.info("CORS is {0}.".format('enabled' if cors else 'disabled')) logger.info("TLS/SSL is {0}.".format('enabled' if tls else 'disabled')) logger.info("Server options: \n{0}".format(options)) bottle.run(app=app, server=server, host=host, port=port, debug=devel, reloader=devel and not gevented, interval=1, quiet=False, **options)
# Simple in-memory key-value store # # Inspired by <https://docs.repl.it/misc/database> # import sys import logging.config import bottle from bottle import request, get, put, delete, abort # Set up app and logging app = bottle.default_app() app.config.load_config('./etc/kv.ini') logging.config.fileConfig(app.config['logging.config']) DB = {} # 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})
def do_signup(): if request.user.is_authenticated: return redirect(default_app().get_url( 'success', message="You are already logged into your account.")) success_uri = request.forms.get('success_uri') error_uri = request.forms.get('error_uri') username = request.forms.get('username') email = request.forms.get('email') first_name = request.forms.get('first_name') last_name = request.forms.get('last_name') password = request.forms.get('password') affiliation = request.forms.get('affiliation') errors = [] if request.user.is_authenticated: errors.append("You are already logged in as %s, please log out before " "creating a new account." % request.user.user_name) if request.forms.get('confirm_password') != password: errors.append("Passwords do not match.") if not spec_util.NAME_REGEX.match(username): errors.append( "Username must only contain letter, digits, hyphens, underscores, and periods." ) try: User.validate_password(password) except UsageError as e: errors.append(e.message) # Only do a basic validation of email -- the only guaranteed way to check # whether an email address is valid is by sending an actual email. if not spec_util.BASIC_EMAIL_REGEX.match(email): errors.append("Email address is invalid.") if local.model.user_exists(username, email): errors.append("User with this username or email already exists.") if not NAME_REGEX.match(username): errors.append( "Username characters must be alphanumeric, underscores, periods, or dashes." ) if errors: return redirect_with_query( error_uri, { 'error': ' '.join(errors), 'next': success_uri, 'email': email, 'username': username, 'first_name': first_name, 'last_name': last_name, 'affiliation': affiliation }) # If user leaves it blank, empty string is obtained - make it of NoneType. if not affiliation: affiliation = None # Create unverified user _, verification_key = local.model.add_user( username, email, first_name, last_name, password, affiliation, ) # Send key send_verification_key(username, email, verification_key) # Redirect to success page return redirect_with_query(success_uri, {'email': email})
HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Cache-Control: no-store Pragma: no-cache { "access_token":"2YotnFZFEjr1zCsicMWpAA", "token_type":"example", "expires_in":3600, "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", "example_parameter":"example_value" } """ pass @post('/oauth2/revoke') @oauth2_provider.revoke_handler def revoke_token(): """Revoke OAuth2 token.""" pass @get('/oauth2/errors', name='oauth2_errors') def show_errors(): return template('oauth2_errors', **request.query) default_app().config['OAUTH2_PROVIDER_ERROR_ENDPOINT'] = 'oauth2_errors'
if string.strip(line) != '': splitted = string.split(line) url = splitted[-1] name = string.join(splitted[:-1]) c.execute( ''' INSERT INTO search_engine (name, url, rank) VALUES (?, ?, ?) ''', (name, url, rank)) conn.commit() conn.close() bo.redirect('/') if __name__ == '__main__': web_app = WebApp() app = bo.default_app() app.get('/assets/<filename:path>', name='get_static', callback=web_app.get_static) app.get('/', name='get_index', callback=web_app.get_index) app.get(['/search', '/search/'], name='get_search', callback=web_app.get_search) app.post(['/search', '/search/'], name='post_search', callback=web_app.post_search) app.get(['/engines', '/engines/'],
def makeboard(rows, cols): board = [] for r in range(rows): brow = [] for c in range(cols): if r == c == 0: brow.append(' ') elif r == 0: brow.append(str(c-1)) elif c == 0: brow.append(str(r-1)) else: brow.append('*') board.append(brow) return board #b = makeboard(20,20) #for row in b: # print ' '.join(row) ## # Expose WSGI app (so gunicorn can find it) application = bottle.default_app() if __name__ == '__main__': bottle.run(application, host=os.getenv('IP', '0.0.0.0'), port=os.getenv('PORT', '8080'))
def get_app(): return default_app()
def wsgi_app(): """Returns the application to make available through wfastcgi. This is used when the site is published to Microsoft Azure.""" return bottle.default_app()
""" Author: donsky For: www.donskytech.com Purpose: Create a REST Server Interface using Bottle for future IOT Projects """ from bottle import route, run, request, get, response, default_app from paste import httpserver import sqlite3 import json from pathlib import Path #NOTE: CHANGE THIS TO WHERE YOU DOWNLOAD YOUR GIT REPO db_folder = Path("D:/git/database-project/StudentDB.db") application = default_app() @get('/student/isauthorized') def message(): rf_id_code = request.query.rf_id_code.lstrip().rstrip() length = len(rf_id_code) print( f"Received the following query parameter rf_id_code={rf_id_code}, len={length}" ) conn = sqlite3.connect(db_folder) cursor = conn.cursor() cursor.execute("SELECT COUNT(*) FROM STUDENTS WHERE RF_ID_CODE=?",
TOP = '01000000000000000000' def log(message): stdout.write( datetime.now().strftime('%Y/%m/%d %H:%M:%S') + ' ' + str(request.remote_addr) + ' ' + message + '\n' ) stdout.flush() @route('/') def index(): return template('index', path=TOP) @route('/<path:re:[0-9a-f]{20}>') def next(path): return template('index', path=path) @route('/js/three.min.js') def threejs(): return static_file('three.min.js', root="./js") @route('/images/<file_path:path>') def image(file_path): if file_path.endswith('_B.png'): log(file_path) return static_file(file_path, root='./images') import bjoern bjoern.run(default_app(), host=HOST, port=PORT)
Description: web服务工具模块 """ import json import re import urllib from bottle import response, HTTPResponse, request, default_app from common import json_util, log_util, convert_util from common.install_plugin import * from i18n.i18n import getLangInst from web_db_define import USER_API_ACCESS_TABLE, API_BLACK_SET, USER_API_EXPIRE import inspect import redis conf = default_app().config def get_ip(): """ 获取当前客户端IP """ try: ip = request.remote_addr except: ip = request.environ.get('REMOTE_ADDR') if not ip: ip = '' return ip
except: pass # 处理ajax提交的put、delete等请求转换为对应的请求路由(由于AJAX不支持RESTful风格提交,所以需要在这里处理一下,对提交方式进行转换) if request.method == 'POST' and request.POST.get('_method'): request.environ['REQUEST_METHOD'] = request.POST.get('_method', '') # 过滤不用进行登录权限判断的路由(登录与退出登录不用检查是否已经登录) url_list = ["/api/login/", "/api/logout/"] if path_info in url_list: pass else: # 已经登录成功的用户session肯定有值,没有值的就是未登录 session = web_helper.get_session() # 获取用户id manager_id = session.get('id', 0) login_name = session.get('login_name', 0) # 判断用户是否登录 if not manager_id or not login_name: web_helper.return_raise( web_helper.return_msg(-404, "您的登录已失效,请重新登录")) # 函数主入口 if __name__ == '__main__': app_argv = SessionMiddleware(default_app(), session_opts) run(app=app_argv, host='0.0.0.0', port=9090, debug=True, reloader=True) else: # 使用uwsgi方式处理python访问时,必须要添加这一句代码,不然无法访问 application = SessionMiddleware(default_app(), session_opts)
def wsgi_app(engine): app = bottle.default_app() app.error_handler = error_handler_callback app.install(errors_handler_plugin) app.install(SQLAlchemyPlugin(engine)) return app
def test(): self.assertEqual(bottle.request.app, bottle.default_app()) self.assertEqual(bottle.request.route, bottle.default_app().routes[0]) return 'foo'
def import_apps(): """import or reimport modules and exposed static files""" reloader.enable() folder = os.environ['WEB3PY_APPS_FOLDER'] app = bottle.default_app() app.routes.clear() new_apps = [] for app_name in os.listdir(folder): path = os.path.join(folder, app_name) init = os.path.join(path, '__init__.py') if os.path.isdir( path) and not path.endswith('__') and os.path.exists(init): module_name = 'apps.%s' % app_name try: module = Reloader.MODULES.get(app_name) if not module: print('[ ] loading %s ...' % app_name) module = importlib.machinery.SourceFileLoader( module_name, init).load_module() Reloader.MODULES[app_name] = module new_apps.append(path) print('\x1b[A[OK] loaded %s ' % app_name) else: print('[ ] reloading %s ...' % app_name) reloader.reload(module) print('\x1b[A[OK] loaded %s ' % app_name) Reloader.ERRORS[app_name] = None except: print('\x1b[A[FAILED] loading %s ' % app_name) print('\n'.join( ' ' + line for line in traceback.format_exc().split('\n'))) Reloader.ERRORS[app_name] = traceback.format_exc() reloader.disable() # expose static files for path in new_apps: @bottle.route('/%s/static/<filename:path>' % path.split(os.path.sep)[-1]) def server_static(filename, path=path): return bottle.static_file(filename, root=os.path.join(path, 'static')) # register routes routes = [] def to_filename(module): filename = os.path.join(*module.split('.')[1:]) filename = os.path.join(filename, '__init__.py') if not filename.count( os.sep) else filename + '.py' return filename for route in app.routes: func = route.callback routes.append({ 'rule': route.rule, 'method': route.method, 'filename': to_filename(func.__module__), 'action': func.__name__ }) Reloader.ROUTES = sorted(routes, key=lambda item: item['rule'])
#!/usr/bin/env python import os import sys import bottle SCRIPT_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) sys.path.append(os.path.abspath(os.path.join(SCRIPT_DIRECTORY, '..'))) import server.routes app_routes = [x for x in bottle.default_app().routes] for route in app_routes: if route.method == "OPTIONS": # Ignore CORS handling continue print(route.rule) print(''.join('=' for _ in route.rule)) print(route.callback.__doc__) print('')
#!/usr/bin/evn python # 这是标识当前脚本指定用python来执行它,为了防止用户没有将python装在默认的/usr/bin路径里,系统执行时首先会到env设置里查找python的安装路径,再调用对应路径下的python程序来执行 # coding=utf-8 from bottle import default_app, get, run # 由于bottle框架自身并没有提供Session的支持,所以使用beaker中间件来实现。 from beaker.middleware import SessionMiddleware # 设置session参数 session_opts = { 'session.type': 'file', 'session.cookie_expires': 3600, 'session.data_dir': '/tmp/sessions/simple', 'session.auto': True } # 第7到第13行,是创建一个session配置的字典,用来存储session的存储类型为文件类型,session过期时间为3600秒,session文件存放路径为/tmp/sessions/simple @get('/index/') def callback(): return 'Hello World! jxp' # 函数主入口 if __name__ == '__main__': app_argv = SessionMiddleware(default_app(), session_opts) #启动WSGI WEB程序,地址为本机地址,访问端口为909 run(app=app_argv, host='0.0.0.0', port=9090, debug=True, reloader=True) # Bottle框架,它是一个快速的,简单的,非常轻量级的 Python WSGI Web 框架
item2 = request.forms.get('email') item3 = request.forms.get('comment') text = str(item1) + " " + str(item2) + " " + str(item3) requests.post( "https://api.mailgun.net/v3/sandbox92b6c85a89974c7380478939171df4ea.mailgun.org/messages", auth=("api", "key-03e2b73105e6602305dc18d34cb19e5c"), data={ "from": "Mailgun Sandbox <*****@*****.**>", "to": "End Police Brutality <*****@*****.**>", "subject": subject, "html": text }) return ''' <meta http-equiv="refresh" content="4; url=/"> <p>Received - Thank you! Redirecting ...</p> ''' @route('/post', method="POST") def show_it(): connection = sqlite3.connect("/home/berlinab/mysite/users.db") c = connection.cursor() c.execute("SELECT * from account") row = c.fetchall() return template("/home/berlinab/mysite/post", row=row) #application = default_app() application = SessionMiddleware(bottle.default_app(), session_opts)
def run(self): self.setup() self._server.run(app=default_app())
""" Author:$Author$ Date:$Date$ Revision:$Revision$ Description: 平台入口 """ import bottle from create_server import makeHsioeServer from i18n.i18n import initializeWeb #实例化语言包 initializeWeb() #初始化应用 hsioe = makeHsioeServer(bottle.default_app())#bottle.default_app() #设置bottle的最大文件上传内容 hsioe.set_memfile_max(1024*1024*2) hsioe.set_template_path('server/template/%s'%('default')) #初始化app hsioe._init_app() @hsioe.app.error(404) def get_error_404(code): """ 返回404 """ return 'not found' @hsioe.app.error(500) def get_error_500(code): """ 返回500 """ return "Server Error"
import os import bottle ROOT = os.path.join(os.environ.get('HTML_PATH', '.')) AUTH = os.environ.get('BASIC_AUTH', None) PORT = int(os.environ.get('PORT', '8080')) def check(username, password): return ':'.join([username, password]) == AUTH def server_static(path): if path.endswith('/'): path += 'index.html' return bottle.static_file(path, root=ROOT) if AUTH is not None: server_static = bottle.auth_basic(check)(server_static) server_static = bottle.route('<path:path>')(server_static) application = bottle.default_app() # for WSGI if __name__ == '__main__': bottle.run(host='0.0.0.0', port=PORT)
def application(environ, start_response): return bottle.default_app().wsgi(environ, start_response)
'host': 'localhost', # Hostname use for Bottle server 'port': 8000, # Port used for Bottle server (use 0 for auto) 'block': True, # Whether start() blocks calling thread 'jinja_templates': None, # Folder for jinja2 templates 'cmdline_args': ['--disable-http-cache'], # Extra cmdline flags to pass to browser start 'size': None, # (width, height) of main window 'position': None, # (left, top) of main window 'geometry': {}, # Dictionary of size/position for all windows 'close_callback': None, # Callback for when all windows have closed 'app_mode': True, # (Chrome specific option) 'all_interfaces': False, # Allow bottle server to listen for connections on all interfaces 'disable_cache': True, # Sets the no-store response header when serving assets 'app': btl.default_app( ), # Allows passing in a custom Bottle instance, e.g. with middleware } # == Temporary (suppressable) error message to inform users of breaking API change for v1.0.0 === _start_args['suppress_error'] = False api_error_message = ''' ---------------------------------------------------------------------------------- 'options' argument deprecated in v1.0.0, see https://github.com/ChrisKnott/Eel To suppress this error, add 'suppress_error=True' to start() call. This option will be removed in future versions ---------------------------------------------------------------------------------- ''' # =============================================================================================== # Public functions
def run_rest_server(manager, debug, num_processes, num_threads, redis_connection_pool): """Runs the REST server.""" host = manager.config['server']['rest_host'] port = manager.config['server']['rest_port'] if redis_connection_pool: cache.init(redis_connection_pool) install(SaveEnvironmentPlugin(manager)) install(InitCachePlugin()) install(CheckJsonPlugin()) install(LoggingPlugin()) install(oauth2_provider.check_oauth()) install(CookieAuthenticationPlugin()) install(UserVerifiedPlugin()) install(PublicUserPlugin()) install(ErrorAdapter()) # Replace default JSON plugin with one that handles datetime objects # Note: ErrorAdapter must come before JSONPlugin to catch serialization errors uninstall(JSONPlugin()) install(JSONPlugin(json_dumps=DatetimeEncoder().encode)) # JsonApiPlugin must come after JSONPlugin, to inspect and modify response # dicts before they are serialized into JSON install(JsonApiPlugin()) for code in xrange(100, 600): default_app().error(code)(error_handler) root_app = Bottle() root_app.mount('/rest', default_app()) # Look for templates in codalab-cli/views bottle.TEMPLATE_PATH = [ os.path.join( os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'views') ] # Increase the request body size limit to 8 MiB bottle.BaseRequest.MEMFILE_MAX = 8 * 1024 * 1024 # We use gunicorn to create a server with multiple processes, since in # Python a single process uses at most 1 CPU due to the Global Interpreter # Lock. sys.argv = sys.argv[:1] # Small hack to work around a Gunicorn arg parsing # bug. None of the arguments to cl should go to # Gunicorn. run( app=root_app, host=host, port=port, debug=debug, server='gunicorn', workers=num_processes, worker_class='gthread', threads=num_threads, worker_tmp_dir='/tmp', # don't use globally set tempdir timeout=5 * 60)
def wsgi(**args): """Initializes everything, loads apps, returns the wsgi app""" initialize(**args) Reloader.import_apps() return bottle.default_app()
def catch_all(path, db): static_root = os.path.abspath(default_app().config["general.web_path"]) html_root = os.path.join(static_root, 'html') return static_file('index.html', html_root)
def import_apps(): """Import or reimport modules and exposed static files""" folder = os.environ['PY4WEB_APPS_FOLDER'] app = bottle.default_app() app.routes.clear() new_apps = [] # if first time reload dummy top module if not Reloader.MODULES: path = os.path.join(folder, '__init__.py') module = importlib.machinery.SourceFileLoader('apps', path).load_module() # Then load all the apps as submodules for app_name in os.listdir(folder): action.app_name = app_name path = os.path.join(folder, app_name) init = os.path.join(path, '__init__.py') if os.path.isdir( path) and not path.endswith('__') and os.path.exists(init): module_name = 'apps.%s' % app_name try: module = Reloader.MODULES.get(app_name) if not module: print('[ ] loading %s ...' % app_name) module = importlib.machinery.SourceFileLoader( module_name, init).load_module() new_apps.append(path) print('\x1b[A[X] loaded %s ' % app_name) else: print('[ ] reloading %s ...' % app_name) names = [ name for name in sys.modules if (name + '.').startswith(module_name + '.') ] for name in names: try: importlib.reload(sys.modules[name]) except ModuleNotFoundError: pass print('\x1b[A[X] reloaded %s ' % app_name) Reloader.MODULES[app_name] = module Reloader.ERRORS[app_name] = None except: tb = traceback.format_exc() print('\x1b[A[FAILED] loading %s \n%s\n' % (app_name, tb)) Reloader.ERRORS[app_name] = tb # Expose static files with support for static asset management for path in new_apps: static_folder = os.path.join(path, 'static') if os.path.exists(static_folder): app_name = path.split(os.path.sep)[-1] prefix = '' if app_name == '_default' else ('/%s' % app_name) @bottle.route(prefix + '/static/<filename:path>') @bottle.route( prefix + '/static/_<version:re:\\d+\\.\\d+\\.\\d+>/<filename:path>') def server_static(filename, static_folder=static_folder, version=None): return bottle.static_file(filename, root=static_folder) # Register routes list routes = [] def to_filename(module): filename = os.path.join(*module.split('.')[1:]) filename = os.path.join(filename, '__init__.py') if not filename.count( os.sep) else filename + '.py' return filename for route in app.routes: func = route.callback routes.append({ 'rule': route.rule, 'method': route.method, 'filename': to_filename(func.__module__), 'action': func.__name__ }) Reloader.ROUTES = sorted(routes, key=lambda item: item['rule']) ICECUBE.update(threadsafevariable.ThreadSafeVariable.freeze())
import logging import requests from datetime import datetime, timedelta from json import JSONDecodeError from . import BaseAPI from bottle import default_app app = default_app() class BaiduAIP(BaseAPI): access_token = None at_expire = datetime.now() def __init__(self, client_id=None, client_secret=None): super().__init__() if client_id is None: client_id = app.config['baidu.aip.client_id'], if client_secret is None: client_secret = app.config['baidu.aip.client_secret'], self.client_id = client_id self.client_secret = client_secret def before_request(self, kwargs): self.check_access_token() kwargs['url'] += '?access_token=' + BaiduFace.access_token if 'timeout' not in kwargs:
result = "/ ".join(jieba4j.cut_search(text)) else: result = "" return template("cut_form",content=result,userdict=sample_userdict,selected=functools.partial(match,int(request.forms.opt))) @get('/adddict') def cut_action_1(): return template("cut_form",content=sample_sentences,userdict=sample_userdict,selected=functools.partial(match,1)) @post('/adddict') def cut_action_2(): return template("cut_form",content=sample_sentences,userdict=sample_userdict,selected=functools.partial(match,1)) if __name__ == "__main__": # Interactive mode #debug(True) #run() from wsgiref.simple_server import make_server httpd = make_server('localhost', 8080, default_app()) jieba4j.init() # Wait for a single request, serve it and quit. httpd.serve_forever() jieba4j.shutdown() else: # Mod WSGI launch os.chdir(os.path.dirname(__file__)) application = default_app()