def start(self): # setup routing route("/display/brightness", method=['OPTIONS', 'POST'])(self.set_brightness) route("/mode", method=['OPTIONS', 'POST'])(self.set_mode) route("/moodlight/mode", method=['OPTIONS', 'POST'])(self.set_moodlight_mode) route("/text", method=['OPTIONS', 'POST'])(self.set_text) route("/gameframe", method=['OPTIONS', 'GET'])(self.get_gameframes) route("/gameframe", method=['OPTIONS', 'DELETE'])(self.delete_gameframe) route("/gameframe/next", method=['OPTIONS', 'POST'])(self.next_gameframe) route("/gameframe/current", method=['OPTIONS', 'POST'])(self.set_next_gameframe) get("/gameframe/<gameframe>")(self.get_gameframe) post("/gameframe/upload/<name>")(self.upload_gameframe) post("/gameframe")(self.select_gameframes) # run server install(EnableCors()) threading.Thread(target=run, kwargs=dict(host='127.0.0.1', port=8081, server=CustomWSGIRefServer, quiet=True)).start()
def test_decorators(self): def foo(): return bottle.request.method bottle.get('/')(foo) bottle.post('/')(foo) bottle.put('/')(foo) bottle.delete('/')(foo) for verb in 'GET POST PUT DELETE'.split(): self.assertBody(verb, '/', method=verb)
def do_del(): get = request.forms.getunicode if get('password') != PASSWORD: return 'wrong password, get out!' selected = collection.find_one({'id': get('id'), 'date': get('date')}) if not selected: return 'no result, check your id & date and try again' collection.remove({'id': get('id'), 'date': get('date')}) return 'OK. <a href="/">Bring me home</a>'
def main(): urls = [line.strip() for line in sys.stdin] extract = Extract(sys.argv[2], urls, int(sys.argv[1])) get("/")(extract.start_page) post("/")(extract.annotate_page) print("Hello human annotator. Visit http://localhost:8080 in your browser.") run(host='localhost', port=8080, quiet=True)
def test_decorators(self): app = bottle.Bottle() app.route('/g')('foo') bottle.route('/g')('foo') app.route('/g2', method='GET')('foo') bottle.get('/g2')('foo') app.route('/p', method='POST')('foo') bottle.post('/p')('foo') app.route('/p2', method='PUT')('foo') bottle.put('/p2')('foo') app.route('/d', method='DELETE')('foo') bottle.delete('/d')('foo') self.assertEqual(app.routes, bottle.app().routes)
def routeapp(server): # print dir(server) for kw in dir(server): # print "kw: ", kw attr = getattr(server, kw) if hasattr(attr, 'get'): print "- attr: ", attr print "- attr.get: ", attr.get # traceback.print_exc() bottle.get(attr.get)(attr) if hasattr(attr, 'delete'): print "- attr: ", attr print "- attr.delete: ", attr.delete # traceback.print_exc() bottle.delete(attr.delete)(attr)
def post(request): posi_text = request.forms.get("posi_text") nega_text = request.forms.get("nega_text") posi_text = urllib.unquote(posi_text) nega_text = urllib.unquote(nega_text) #posi_text=unicode(posi_text,"utf-8") #nega_text=unicode(nega_text,"utf-8") logging.debug(type(posi_text)) logging.debug(posi_text) #posi_text=urllib2.unquote(posi_text).encode('raw_unicode_escape').decode('utf-8') #return posi_text #nega_text=urllib2.unquote(nega_text).encode('raw_unicode_escape').decode('utf-8') posi = [] nega = [] for t in posi_text.split(" "): print(t) posi.append(unicode(t, "utf-8")) for t in nega_text.split(" "): nega.append(unicode(t, "utf-8")) logging.debug(posi) logging.debug(nega) logging.debug(len(nega)) logging.debug(len(nega_text)) if len(posi_text) == 0: return "invalid positive text" err_str = "" out = None try: if len(nega_text) > 0: out = model.most_similar(positive=posi, negative=nega) else: out = model.most_similar(positive=posi) logging.debug(out) except KeyError: err_str = "Keyword Error" ret = get() ret = ret + "<br><br>Wikipedia keyword" ret = ret + "<br><br>" ret = ret + "positive text:" + posi_text + "<br>" ret = ret + "negative text:" + nega_text + "<br>" if len(err_str) > 0: ret = ret + "<font color='red'><b>" + err_str + "</b></font><br><br>" else: ret = ret + "<table border='1'><tr><th>word</th><th>score</th></tr>" for x in out: ret = ret + "<tr>" ret = ret + "<td>" + str(x[0].encode('utf-8')) + "</td>" ret = ret + "<td>" + str(x[1]) + "</td>" ret = ret + "</tr>" ret = ret + "</table>" return ret
def complete(client, word): for t, get in ("EI", lambda t: t.name), ("EAI", lambda t: t.alias[0]), \ ("FI", lambda t: t.name), ("FAI", lambda t: t.alias[0]): tags = client.find_tags(t, word) if len(tags) == 1: t = tags[0] return (get(t), t.type), [] if len(tags) > 1: break aliases = [[(a, t.type) for a in t.alias] or [] for t in tags] aliases = chain(*aliases) tags = [(t.name, t.type) for t in tags] inc = lambda t: t[0][:len(word)] == word candidates = filter(inc, tags) + filter(inc, aliases) if not candidates: word = _completefuzz(word) inc = lambda t: _completefuzz(t[0])[:len(word)] == word candidates = filter(inc, tags) + filter(inc, aliases) return (commonprefix([n for n, t in candidates]), ""), candidates
def __new__(cls, *args, **kwargs): obj = super(Ouroboros, cls).__new__(cls, *args, **kwargs) bottle.get("/status.json")(obj.http_status_handler) return obj
@post('/addHymn') def addHymn(): uuid, is_admin = get_uuid() if not is_admin: response.status = 401 return '<html><body><h1>401 Unauthorized</h1></body></html>' try: print(request.forms.get('date')) date = datetime.date(*map(int, request.forms.get('date').split('-'))) except (ValueError, TypeError): response.status = 400 return '<html><body><h1>400 Bad Request</h1></body></html>' hymn = request.forms.get('hymn') db = pymysql.connect(autocommit=True, **auth.auth) with db.cursor() as cursor: cursor.execute('SELECT count(*) FROM history WHERE date=%s', date) next_idx = cursor.fetchone()[0] cursor.execute('INSERT INTO history (date, idx, num) VALUES (%s, %s, %s)', (date, next_idx, hymn)) application = default_app() if __name__ == '__main__': from bottle import run get('/audio/<filename>')(lambda filename: static_file(filename, root='audio/')) get('/css/<filename:path>')(lambda filename: static_file(filename, root='css/')) get('/js/<filename:path>')(lambda filename: static_file(filename, root='js/')) run(app=application, host='127.0.0.1', port=8080, debug=True, reloader=True)
print "The real-time status of this benchmark can be viewed at 'http://localhost:%s/status' and" % args.port print "The final report, once complete, can be found at 'http://localhost:%s/report'." % args.port print "------------------------------------------------------------------------------------------------------------" s = Server( args.client_hostnames, args.benchmark_time, args.chunk_size, args.file_size, args.heartbeat_interval, args.monitoring_interval, args.port, args.log ) # Initialize routes bottle.get("/")(s.main) bottle.get("/status")(s.status) bottle.get("/report")(s.report) bottle.get("/logs")(s.logs) bottle.get("/about")(s.about) bottle.route('/static/:file_path#.+#')(s.static) bottle.get("/favicon.ico")(s.get_favicon) bottle.post("/hello")(s.hello) bottle.post(HEARTBEAT_PATH)(s.client_heartbeat) bottle.post(START_PATH)(s.client_start) bottle.post(STOP_PATH)(s.client_stop) bottle.post(RESOURCES_PATH)(s.client_resources) bottle.post(ROLLOVER_PATH)(s.client_rollover) s.run_benchmarks()
} code, data = call(config, method, args) if code == 0: data = dict(success=True, result=data) else: data = dict(success=False) return data def client_response(*args): def req(): return call_client(*args) return req for cmd in ('printers', 'profiles', 'jobs', 'drivers'): bottle.get('/api/' + cmd, callback=client_response(cmd)) for cmd in ('connect', 'disconnect'): bottle.get('/api/' + cmd, callback=client_response(cmd)) def ng(value): return '{{ %s }}' % value @bottle.get('/') @bottle.view('index') def index(): return {'ng': ng}
def run(self): get("/history")(self.getHistory) get("/exit")(self.getExitPlan) run(host='0.0.0.0', port=8080, server='paste', debug=True)
import os # Change working directory so relative paths (and template lookup) work again os.chdir(os.path.dirname(__file__)) from bs4 import BeautifulSoup import bottle from bottle import route, get, template, static_file, request from mainweb import get application = get()
def bottle_get(url_path: str) -> Callable[[AnyFunction], AnyFunction]: return bottle.get(url_path) # type: ignore
def multi(method_): return get(path)(self.build_method(timeout, method_))
try: return cli_output(device.set_state(state)) except ValueError: return bottle.HTTPError(400, "Invalid state: %s" % (state,)) _wrapped.__name__ = 'put_%s' % (device.get_name(),) return _wrapped def rest_list_states(device): """ Inside an HTTP OPTIONS, list a device's acceptable inputs """ def _wrapped(*args, **kwargs): bottle.response.content_type = 'text/plain' return '\n'.join(device.get_acceptable_states()) + '\n' _wrapped.__name__ = 'options_%s' % (device.get_name(),) return _wrapped for device in DEVICES: path = '/' + device._state_path() bottle.get(path)(rest_get_state(device)) bottle.post(path)(rest_set_state(device)) # openhab can only post bottle.put(path)(rest_set_state(device)) bottle.route(path, method='OPTIONS')(rest_list_states(device)) # check for subdevices for name,subdev in device.subdevices.items(): subpath = '/' + subdev._state_path() bottle.get(subpath)(rest_get_state(subdev)) bottle.post(subpath)(rest_set_state(subdev)) # openhab can only post bottle.put(subpath)(rest_set_state(subdev)) bottle.route(subpath, method='OPTIONS')(rest_list_states(subdev)) # save to index klass = device.get_class() name = device.get_name() klass_devices = device_list.get(klass, {}) klass_devices[name] = device
def run(_args: argparse.Namespace): """ Execute webserver :param _args: Parsed CLI args :return: None """ client = sql.Client("sqlite:///:memory:") client.competitions().append(Name="Kevät ranking 2020", CompetitionDate=datetime.date(2020, 3, 3), IsActive=False) client.competitions().append(Name="Syys ranking 2020", CompetitionDate=datetime.date(2020, 9, 3), IsActive=False) bottle.get(r"/css/<filename>")(serve_css) bottle.get("/")(serve_index) bottle.get("/favicon.ico")(serve_favicon) bottle.get(r"/tables/<tablename>")( lambda tablename: serve_tables(tablename, client)) bottle.get(r"/script/<filename>")(serve_script) bottle.get(r"/websocket")(lambda: wshandler.serve_websocket(client)) gevent.monkey.patch_all() # Magic bottle.run(server="gevent", host="localhost", port=8080, debug=True, handler_class=geventwebsocket.handler.WebSocketHandler)
def http_server(): bottle.run(app=get(), host='0.0.0.0', port=8000, server="gevent", debug=True)
print "File size (%s) must be larger than %s. Bailing!" % ( args.file_size, largest_chunk) sys.exit(1) print "Server logs will be saved to '%s'." % args.log print "A much nicer view of these logs can be accessed at 'http://localhost:%s/logs' though." % args.port print "" print "The real-time status of this benchmark can be viewed at 'http://localhost:%s/status' and" % args.port print "The final report, once complete, can be found at 'http://localhost:%s/report'." % args.port print "------------------------------------------------------------------------------------------------------------" s = Server(args.client_hostnames, args.benchmark_time, args.chunk_size, args.file_size, args.heartbeat_interval, args.monitoring_interval, args.port, args.log) # Initialize routes bottle.get("/")(s.main) bottle.get("/status")(s.status) bottle.get("/report")(s.report) bottle.get("/logs")(s.logs) bottle.get("/about")(s.about) bottle.route('/static/:file_path#.+#')(s.static) bottle.get("/favicon.ico")(s.get_favicon) bottle.post("/hello")(s.hello) bottle.post(HEARTBEAT_PATH)(s.client_heartbeat) bottle.post(START_PATH)(s.client_start) bottle.post(STOP_PATH)(s.client_stop) bottle.post(RESOURCES_PATH)(s.client_resources) bottle.post(ROLLOVER_PATH)(s.client_rollover) s.run_benchmarks()
def create_rest_api(base_collection, url_base, restricted=False, override_={}, post_={}): def list_collection(**context): collection = base_collection.fetch(**context) bottle.response.context.update({'collection': collection}) return collection def update_collection(**context): pass def add_to_collection(**context): new_item = bottle.request.json new_item['user'] = context['user'] item = base_collection.new(**new_item) bottle.response.context.update({'item': item}) return item def delete_collection(**context): pass def show_item(id, **context): item = base_collection.get(_id=id) bottle.response.context.update({'item': item}) return item def update_item(id, **context): updated_item = bottle.request.json updated_item['_id'] = id item = base_collection.update(**updated_item) bottle.response.context.update({'item': item}) return item def add_to_item(id, **context): pass def delete_item(id, **context): base_collection.remove(_id=id) return list_collection(**context) route_map = { # Collections '%s' % url_base: list_collection, '>%s' % url_base: update_collection, '#%s' % url_base: add_to_collection, 'X%s' % url_base: delete_collection, # Entities '%s/:id' % url_base: show_item, '>%s/:id' % url_base: update_item, '#%s/:id' % url_base: add_to_item, 'X%s/:id' % url_base: delete_item, } template_map = { # Collections list_collection: 'list', update_collection: 'list', add_to_collection: 'show', delete_collection: 'list', # Entities show_item: 'show', update_item: 'show', add_to_item: 'show', delete_item: 'list', } # Create the full callback for a route and action def make_templated_callback(callback): template_base = 'generic/' def wrapper(**context): #print context context['user'] = bottle.response.context.user.id cb=callback if override_.has_key(callback.__name__): cb = override_[callback.__name__] result = cb(**context) if post_.has_key(callback.__name__): result = post_[cb.__name__](**result) return render(template_base + template_map[callback], **result) if restricted: wrapper = require_auth(wrapper) return wrapper # Make a JSON version too def make_json_callback(callback): def wrapper(**context): context['user'] = bottle.response.context.user.id cb=callback if override_.has_key(callback.__name__): cb = override_[callback.__name__] #print "CONTEXT: %s" % context result = cb(**context) if post_.has_key(callback.__name__): result = post_[cb.__name__](**result) #print "RESULT: %s" % result return pymongo_to_json(result) if restricted: wrapper = require_auth(wrapper) return wrapper # Generate the routes for route in route_map.items(): path, callback = route if path.startswith('#'): bottle.post(path[1:] + '.json')(make_json_callback(callback)) bottle.post(path[1:])(make_templated_callback(callback)) elif path.startswith('X'): bottle.delete(path[1:] + '.json')(make_json_callback(callback)) bottle.delete(path[1:])(make_templated_callback(callback)) elif path.startswith('>'): bottle.put(path[1:] + '.json')(make_json_callback(callback)) bottle.put(path[1:])(make_templated_callback(callback)) else: bottle.get(path + '.json')(make_json_callback(callback)) bottle.get(path)(make_templated_callback(callback))
def init(): route('/')(Main_H) route('/:argument')(Main_H) route('/test/:argument')(Main_H) get('/a/b')(Main_H) post('/a/b')(Main_H)
'X/'+_node_id_: [authenticate, delete_node], } # Define routes from the route map def make_route_callback(callback): if type(callback) == list: callback = partial(*callback) def wrapper(**context): return callback(**get_session(**start_context(**context))) return wrapper for route in route_map.items(): path, callback = route if path.startswith('#'): bottle.post(path[1:])(make_route_callback(callback)) elif path.startswith('X'): bottle.delete(path[1:])(make_route_callback(callback)) elif path.startswith('>'): bottle.put(path[1:])(make_route_callback(callback)) else: bottle.get(path)(make_route_callback(callback)) # Static fallback @bottle.route('/<filepath:path>') def static_file(filepath): return bottle.static_file(filepath, root='./static/') # Run the server bottle.debug(config.debug) bottle.run(server=config.server, host='0.0.0.0', port=config.port, reloader=config.debug)
def song_handler(): get = request.forms.getunicode if get('password') != PASSWORD: return 'wrong password, get out!' try: if not get('title') or not get('date'): raise Exception if not get('status') in ('checked', 'pending'): raise Exception except Exception: return '''illegal input please go back checking your input and submit again''' if collection.find({'id': get('_id')}).count(): id = get('_id') collection.update_one({'id': get('_id')}, { '$set': { 'title': get('title'), 'status': get('status'), 'date': get('date'), 'comment': get('comment') } }) else: id = gen_valid_id(collection) collection.insert_one({ 'id': id, 'title': get('title'), 'status': get('status'), 'date': get('date'), 'comment': get('comment') }) redirect('/song/{0}'.format(id))
import sqlite3 import bottle_session import bottle from datetime import time, datetime, date from bottle import route, run, template, request, static_file, get, redirect import string from random import * adminSession = "" get('/<filename:re:.*\.*>') def server_static(filename): return static_file(filename, root='./static/') @route('/logout') def logout(): session = bottle.request.environ.get('beaker.session') session['sp_user'] = '' session['usertype'] = '' return redirect('/') def getSession(): session = bottle.request.environ.get('beaker.session') if (session != ""): return session.get('sp_user') else: return ""
# See https://www.python.org/dev/peps/pep-0476/ for background try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that doesn't verify HTTPS certificates by default pass else: # Handle target environment that doesn't support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context l.warn(f'Monkey-patching command-line args for gunicorn') sys.argv = sys.argv[:1] bottle_args['server'] = 'gunicorn' # -- Configure the web server --------------------------------------------- c = Client(args.client_id, args.client_secret, args.base_url, args.token_url, l) s = Server(c, l, args.debug) # Initialize routes bottle.get("/")(s.main) bottle.get("/logs")(s.logs) bottle.route('/static/:file_path#.+#')(s.static) bottle.get("/favicon.ico")(s.get_favicon) bottle.get('/compositeUsers/<userId>')(s.compositeUsers) # Start honoring requests! l.info( f'Server logs may also be found online at http{"s" if args.ssl else ""}://localhost:{args.port}/logs' ) bottle.run(**bottle_args)