def daemon(): try: port = bot.config('webserver_port', 8888) output.info('Starting server [%s] [%s]' % (host, str(port)), 'WEBSERVER') run(host=host, port=int(port), quiet=True) except Exception as e: if bot.debug: output.error(str(e), "WEBSERVER")
def main(): '''main method''' from optparse import OptionParser parser = OptionParser() parser.add_option('-s', '--server', dest='server', help='bottle.py WSGI server backend') parser.add_option('-p', '--port', dest='port', help='server port') parser.add_option('-b', '--buildsdir', dest='builds_directory', help='directory for builds') optargs = parser.parse_args() for key in SETTINGS.keys(): if optargs[0].__dict__.get(key): SETTINGS[key] = optargs[0].__dict__[key] os.chdir(os.path.dirname(os.path.abspath(__file__))) run(server=SETTINGS['server'], host='0.0.0.0', port=SETTINGS['port'])
def daemon_run(host="0.0.0.0", port="80", pidfile=None, logfile=None): """ Get the bottle 'run' function running in the background as a daemonized process. :host: The host interface to listen for connections on. Enter 0.0.0.0 to listen on all interfaces. Defaults to localhost. :port: The host port to listen on. Defaults to 8080. :pidfile: The file to use as the process id file. Defaults to "bottle.pid" :logfile: The file to log stdout and stderr from bottle to. Defaults to "bottle.log" """ parser = argparse.ArgumentParser() parser.add_argument("action", choices=["start", "stop"]) args = parser.parse_args() if pidfile is None: pidfile = os.path.join( os.getcwd(), "pid/bottle.pid" ) if logfile is None: logfile = os.path.join( os.getcwd(), config["paths"]["dir_webserver_root"] + 'log/bottle.log' ) if args.action == "start": log = open(logfile,"w+") context = daemon.DaemonContext( pidfile=__locked_pidfile(pidfile), stdout=log, stderr=log ) with context: srv = SSLWSGIRefServer(host="0.0.0.0", port=config["paths"]["server_port"]) run(server=srv) if args.action == "stop": with open(pidfile,"r") as p: pid = int(p.read()) os.kill(pid, signal.SIGTERM)
if agency: if type(agency) is type: agency = agency() agencies[agency.name] = agency if agency.routes: return agency return None @bottle.route('/<agency>/times/<orig>/<dest>') def times_handler(agency, orig, dest): agency = get_agency(agency) if agency: return get_times_response(agency, orig, dest) raise bottle.HTTPError(404) @bottle.route('/<agency>/stops') @bottle.route('/<agency>/stops/<route>') def stops_handler(agency, route=None): agency = get_agency(agency) if agency and not route: return '\r\n'.join(agency.stops.keys() + agency.station_replacements.keys()) raise bottle.HTTPError(404) bottle.debug(True) if __name__ == "__main__": bottle.run(host='localhost', port=8080) else: bottle.run(server='gae') application = bottle.app()
@get('/sort') def sort(): f = file(filename) ws = Website() for eachLine in f: line = eachLine.strip().decode('utf-8') data = json.loads(line) ws.sort(data) f.close html = '<html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"></head>' html += '<table border-spacing="0" border="1">\n<tr>' html += '<tr><th>Tags</th><th>Target</th></tr>' data = ws.to_sort() for i in data: html += '<tr><td>' + i + '</td><td>' + data[i] + '</td></tr>' html += "\n</table></html>" return html @post('/scan') def scan(): targets = request.forms.get('targets') return targets run(host='0.0.0.0', port=5000)
def runserver(host, port): """ Start the server """ run(app=app, host=host, port=port, server='gevent')
from lib.bottle import run, PasteServer from app.utils.logger import DCLogger from app.utils.config import Config from app.api import * import traceback config = Config.getConfig() logger = DCLogger.get_default_logger() assert config != None if logger == None: try: log_file = config['log']['log_file'] log_level = config['log']['log_level'] logger = DCLogger(log_file, log_level) except Exception, e: traceback.print_exc() logger = DCLogger() DCLogger.set_default_logger(logger) assert logger != None if __name__ == '__main__': logger.info("start rest api server") run(host='0.0.0.0', port=8888, server=PasteServer)
from lib.bottle import route, run @route('/') def index(): return '<b>Hello World!</b>' run(host='localhost', port=8080)
"*****@*****.**", "admin", create_hash_password("pass"), datetime.datetime.utcnow()) c.execute("""INSERT INTO user (name, email, role, password, creation_date) VALUES (?, ?, ?, ?, ?)""", user_data) article_data = ("Home", "this is the home page", "public", datetime.datetime.utcnow()) c.execute("""INSERT INTO article (title, text, publicity, creation_date) VALUES (?, ?, ?, ?)""", article_data) conn.commit() # Run ################################### setup() if __name__ == '__main__': parser = argparse.ArgumentParser(description='starts the jabawiki server') parser.add_argument('--config', help='specifies the config file location (default: ./config.json)', default="./config.json") args = parser.parse_args() run(host='0.0.0.0', port=PORT) app = default_app()
@route('/favicon.ico') def favicon(): return static_file('favicon.ico', root='files') @error(403) @view('error') def error403(code=None): return {'code': code} @error(404) @view('error') def error404(code=None): return {'code': code} # E X E C U T I O N ########################################################### process_blog_posts() if HEROKU: run(host="0.0.0.0", port=int(os.environ.get("PORT", 80))) else: run(host="localhost", port=8080) # E N D O F F I L E #######################################################
from lib.bottle import run import routes run(host='localhost', port=8080, debug=True)
#!/usr/bin/python # -*- coding: utf-8 -*- from module import app from lib.bottle import run,static_file,debug,request from gevent import monkey; monkey.patch_all() from setting import STATIC_PATH @app.route('/static/<filename:path>') def static(filename): return static_file(filename,STATIC_PATH) if __name__ == '__main__': debug(True) # run(app, host="0.0.0.0",port=7070,reloader=True) run(app, host="0.0.0.0",port=7070,reloader=True,server='gevent')
'pubpercent': pubpercent, 'prvpercent': prvpercent } #render home page @route('/') @view('index') def show_home(): contr = Control() schools = contr.get_selected_schools() publictotal = contr.get_category_all_total('Public') privatetotal = contr.get_category_all_total('Private') return { 'schools': schools, 'publictotal': publictotal, 'privatetotal': privatetotal, 'pubpercent': 0, 'prvpercent': 0 } #render static files i.e js,css @route('/staticfiles/<filepath:path>') def static_serve(filepath): return static_file(filepath, root='staticfiles') if __name__ == '__main__': run()
events = {} now = datetime.datetime.utcnow() for d in range(days_in_advance): tm = now + datetime.timedelta(days=d) events[tm.strftime("%A")] = get_event_for_day(tm.date()) return events def get_news(): d = feedparser.parse(NEWS_FEED) return d['entries'] tpl_path = os.path.join(get_script_rel_path("templates")) TEMPLATE_PATH.insert(0, tpl_path) if __name__ == '__main__': parser = argparse.ArgumentParser(description='starts a lists server') parser.add_argument( '--config', help='specifies the config file location (default: ./config.json)', default="./config.json") args = parser.parse_args() with open(args.config) as f: config = json.load(f) run(host='0.0.0.0', port=config['port'], reloader=True) app = default_app()
def run_test_server(): reload(routes) run(host='localhost', port=TestPort.value, quiet=True)
unzip_diskio = zip(*show_agent_diskio_temp) once_agent_res['agent_diskio'] = unzip_diskio # ---------------------------start: 采集此节点的硬盘存储信息------------------------------------- show_agent_disk = """SELECT max(capturetime), disk FROM ns_disk WHERE ip = "{IP_H}" or hostname = "{IP_H}" ORDER BY capturetime;""".format(IP_H=ip_hostname) db.cur.execute(show_agent_disk) show_agent_disk_temp = db.cur.fetchall() show_agent_disk_json = json.loads(show_agent_disk_temp[0][1]) once_agent_res['agent_disk'] = show_agent_disk_json # ---------------------------start: 采集此节点的sockets连接信息------------------------------------- show_agent_sockets = """SELECT max(capturetime), sockets FROM ns_net WHERE ip = "{IP_H}" or hostname = "{IP_H}" ORDER BY capturetime;""".format(IP_H=ip_hostname) db.cur.execute(show_agent_sockets) show_agent_sockets_temp = db.cur.fetchall() show_agent_sockets_json = json.loads(show_agent_sockets_temp[0][1]) # 因为是表格,不需要时间列,所以直接取[1] once_agent_res['agent_sockets'] = show_agent_sockets_json all_agent_data = {"result": once_agent_res} return all_agent_data except BaseException as e: print e if __name__ == '__main__': ns = NSConf() run(app, host="0.0.0.0", port=int(ns.server_port), debug=ns.debug)
return False ''' Determine if API Key is valid ''' def isValidKey(key): if key in keys: return True return False ''' catch some request errors ''' @error(404) @error(403) def httperror(code): return errorJson('request_error','invalid API request') ''' start from here ''' if __name__ == "__main__": ##load up options from config file access = getattr(cfg, 'access') network = getattr(cfg, 'network') keys = access['apikeys'].strip().split(',') run(host=network['address'], port=int(network['port']), debug=True, reloader=True)
title = request.forms.title body = request.forms.body name = request.forms.name password = request.forms.password save_entry( title, body, name, password) return redirect( "/") @post( "/delete/") def delete_view(): entry_id = request.forms.entry_id password = request.forms.password entry = load_entry( entry_id) if entry[0].password == password or master_password == password: delete_entry( entry[0]) return redirect( "/") @get( "/static/<filename:path>") def static_view( filename): return static_file( filename, root=STATIC_DIR) if __name__ == "__main__": if not os.path.exists( db_filename): create_db() run( host="localhost")
# extracts the number and body and dumps to disk # in correct format for SMSD to hoover up. @route('/sendsms', method='PUT') def send_sms(): recipient = request.json['recipient'] body = request.json['body'] file_name = rand_fname("alert") outbound_path = outbound_queue_path + file_name print "Outbound Path: " + outbound_path if not recipient: abort(400, 'No Recipient Defined') if not body: abort(400, 'No Message Body Defined') try: #return {"recipient": recipient, "body": body} sms_message = open(outbound_path, 'w') print recipient print body sms_message.write("To: " + str(recipient) + '\n\n') sms_message.write(body + '\n') sms_message.close() except: print("epic fail") run(host=local_ip, port=8080)
def start(): """start server""" try: run(server="cherrypy", host=utils.SERVER_HOST, port=utils.SERVER_PORT, reloader=False) except: raise
from lib import bottle import api # FIXME: App wrapper aims at providing an url prefix to the main app # App wrapper #wrapper = bottle.app() #wrapper.mount('/api/', bottle.load_app('app:app')) # Server instance bottle.run(api.app, host='0.0.0.0', port=8000, reloader=True, debug=True)
#!/usr/bin/python # -*- coding: utf-8 -*- from module import app from lib.bottle import run,static_file,debug,request from setting import STATIC_PATH @app.route('/static/<filename:path>') def static(filename): return static_file(filename,STATIC_PATH) if __name__ == '__main__': debug(True) run(app, host="0.0.0.0",port=9090,reloader=True)
conf.read(os.path.join(CUCKOO_ROOT,"conf","vmware.conf")) #print os.path.join(CUCKOO_ROOT, "conf", "vmware.conf") machines = conf.get("vmware", "machines") #print conf,machines # Finally real store and submit analid = store_and_submit_fileobj(data.file, data.filename, desc=desc, timeout=timeout, priority=priority, options=options, machines=machines, package=package) # Show result template = lookup.get_template("success.html") return template.render(analid=analid, submitfile=data.filename) # Find an HTML report and render it @route("/view/<task_id>") def view(task_id): # Check if the specified task ID is valid if not task_id.isdigit(): return HTTPError(code=404, output="The specified ID is invalid") report_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", task_id, "reports", "report.html") # Check if the HTML report exists if not os.path.exists(report_path): return HTTPError(code=404, output="Report not found") # Return content of the HTML report return open(report_path, "rb").read() if __name__ == "__main__": run(host="0.0.0.0", port=8080, debug=True, reloader=True)
import threading from threading import Thread import lib.Ngrok from lib import bottle from lib.MicrophoneStream import MicrophoneStream from lib.Server import Server myapp = Server() bgm_thread = threading.Thread(target=myapp.play_bgm) ngrok = lib.Ngrok.Ngrok() threading.Thread(target=myapp.stream_speach).start() bottle.route("/messenger", method=['POST'])(myapp.messengerFromFirebase) bottle.route("/appNotification", method=['POST'])(myapp.app_notification) bottle.run(host='localhost', port=9000) #time.sleep(10)
def editar(pagina): dados_view['form'] = True dados_view['pagina'] = pagina dados_view['conteudo'] = None pagina = './wiki/%s.md' % pagina if (path.exists(pagina)): arquivo = open(pagina, 'r') dados_view['conteudo'] = arquivo.read() arquivo.close() return dados_view @post('/salvar/<pagina>') def salvar(pagina): conteudo = request.forms.get('texto') arquivo = open('./wiki/%s.md' % pagina, 'w') arquivo.write(conteudo) arquivo.close() redirect('/wiki/' + pagina) @route('/<pagina>') def redirecionar(pagina): redirect('/wiki/%s' % pagina) if __name__ == '__main__': run(host='localhost', port=8080, reloader=True)
from lib.bottle import run,route,response,request import urllib2 bufsize=2048 @route('/down') def down(): try: for one in request.headers(): print one+"----"+ request.headers().get(one) response.content_type='video/mp4' f=urllib2.urlopen("http://114.80.122.39/work/51/150/017/479/51.20120819122713.mp4") while True: buf = f.read(bufsize) if buf: yield buf else: break except Exception,data: print Exception,data run(host="10.151.20.48",port=8080)
def get_script_rel_path(filepath): script_dir = os.path.dirname(os.path.realpath(__file__)) return path.join(script_dir, filepath) # remove ending slash from requests @hook('before_request') def strip_path(): request.environ['PATH_INFO'] = request.environ['PATH_INFO'].rstrip('/') tpl_path = path.join(get_script_rel_path("templates")) bottle.TEMPLATE_PATH.insert(0, tpl_path) try: with open(get_script_rel_path("config.json")) as f: config = json.load(f) except: pass if __name__ == '__main__': parser = argparse.ArgumentParser(description='starts a lists server') parser.add_argument('--config', help='specifies the config file location (default: ./config.json)', default="./config.json") args = parser.parse_args() with open(args.config) as f: config = json.load(f) run(host='0.0.0.0', port=config['port']) app = default_app()
def do_api(): bottle.run(host='0.0.0.0', port=8082)
username = "" if username is None else username password = "" if password is None else password return ''' <form action="/login" method="post"> Username: <input name="username" type="text" value="{username}"/> Password: <input name="password" type="password" value="{password}"/> <input value="Login" type="submit" /> </form> '''.format(username=username, password=password) @route('/login', method='POST') # or @post('/login') def do_login(): username = request.forms.get('username') password = request.forms.get('password') return "{username} {password}".format(username=username, password=password) @error(404) def error404(error): return ''' <img src="/static/error.jpg"> {error} '''.format(error=error) if __name__ == '__main__': run(host='localhost', port=8080, debug=True, reloader=True)
return html @get('/sort') def sort(): f = file(filename) ws = Website() for eachLine in f: line = eachLine.strip().decode('utf-8') data = json.loads(line) ws.sort(data) f.close html = '<html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"></head>' html += '<table border-spacing="0" border="1">\n<tr>' html += '<tr><th>Tags</th><th>Target</th></tr>' data = ws.to_sort() for i in data: html += '<tr><td>'+i+'</td><td>'+ data[i] +'</td></tr>' html += "\n</table></html>" return html @post('/scan') def scan(): targets = request.forms.get('targets') return targets run(host='0.0.0.0', port=5000)
# ---------------------------------------------------------------------------------------------------------- # 查询数据库中tornado入库数据量 try: stk = stattornado_daytable_increment() tt_time = 7 tornado_data = {} for i in range(tt_time): list_tmp = [] today_tt = datetime.date.today() + datetime.timedelta( days=-i) # 当日 20170822 day_tt = ''.join(str(today_tt).split('-')) for field in [ 'REC_TOTL', 'SUC_NUM', 'FAILED_NUM', 'TOKFK_TOTAL', 'TOKFK_SUC', 'TOKFK_FAILED' ]: list_tmp.append(stk.stat_tornado_readnum(day_tt, field)) tornado_data[day_tt] = list_tmp # print "tornado_data:", tornado_data result['TORNADO'] = tornado_data # ---------------------------------------------------------------------------------------------------------- return result except Exception, e: print "tornado统计出错", e if __name__ == '__main__': ns = NSSTATConf() run(app, host="0.0.0.0", port=ns.server_port, debug=True)
@route('/t/:topic/:link_id') def comments(topic, link_id): cursor = get_cursor() cursor.execute( "select address, headline, description, user_email, topic_name from link where id='" + link_id + "' and topic_name='" + topic + "'") link = cursor.fetchall() cursor.execute( "select user_email, contents, id from comment where link_topic='" + topic + "' and link_address='" + str(link[0][0]) + "'") comments = cursor.fetchall() comments = render_comments(comments, 0) return template('comments', link=link[0], comments=comments) # Serve assets @route('/assets/:filename') def asset(filename): return static_file(filename, root='./assets/') # Run like the wind if len(sys.argv) > 1: p = sys.argv[1] else: p = 3030 run(host='0.0.0.0', port=p)
output = template('src/IHM/img.tpl') return output except Exception as err: print("Unexpected error: {0}".format(err)) return ("clé périmée ou erreur encodage requête") @route('/') #permet de créer la liste des villes et des activités disponibles. def installation(): db = sqlite3.connect('test.db') c = db.cursor() c.execute("SELECT numero, nom from activite order by nom asc;") data = c.fetchall() c.execute("SELECT DISTINCT ville from installation order by ville asc;") databis = c.fetchall() c.close() liste = [data, databis] output = template('src/IHM/Interface.tpl', rows=liste) return output @route('/static/img/:filename') #emplacement pour le stockage des images importées def serve_static(filename): return static_file(filename, root='src/IHM/img/') run(host='localhost', port=9999, debug=True)
import sys from time import localtime, strftime from lib.bottle import route, run from utilities import port @route('/live') def live(): return "Date & time here" @route('/') def date_and_time(): return str(strftime("%a, %d %b %Y %H:%M:%S", localtime())) print('----------- ' + sys.argv[0] + " starting on port: " + str(port(sys.argv[0], 8210))) run(host='localhost', port=port(sys.argv[0], 8210), debug=True)
#! /usr/bin/env python # encoding:utf-8 from lib.bottle import run from lib.action import index, fetch, test, upload, init_dir, read import sys if((len(sys.argv) > 1) and (sys.argv[1] == 'init')): init_dir(); else: run(host='0.0.0.0', port=8983);
str(row['alt']) ] cur.execute("insert into wifis values(" + ','.join(values) + ")") con.commit() return "success" # interval API, takes integer times for start and end, and a mac address @route('/api/i') @route('/api/i/:start') @route('/api/i/:start/:end') @route('/api/i/:start/:end/:mac') def interval(start="0", end=str(time.time()), mac=''): cur = con.cursor() if (mac == ''): cur.execute("SELECT * FROM wifis WHERE time>" + start + " AND time<" + end) else: cur.execute("SELECT * FROM wifis WHERE time>" + start + " AND time<" + end + " AND mac=\"" + mac + "\"") return json.dumps(cur.fetchall()) # serve static files @route('/static/:filename') def static(filename): return static_file(filename, root='./static/') run(host='0.0.0.0', port=3030)
def doApi(): bottle.run(host=socket.gethostname(), port=8082)
if len(child_comments) > 0: html_string += render_comments(child_comments, 1) html_string += "</div>" return html_string @route('/t/:topic/:link_id') def comments(topic, link_id): cursor = get_cursor() cursor.execute("select address, headline, description, user_email, topic_name from link where id='"+link_id+"' and topic_name='"+topic+"'") link = cursor.fetchall() cursor.execute("select user_email, contents, id from comment where link_topic='"+topic+"' and link_address='"+str(link[0][0])+"'") comments = cursor.fetchall() comments = render_comments(comments, 0) return template('comments', link=link[0], comments=comments) # Serve assets @route('/assets/:filename') def asset(filename): return static_file(filename, root='./assets/') # Run like the wind if len(sys.argv) > 1: p = sys.argv[1] else: p = 3030 run(host='0.0.0.0', port=p)
def server_static(filepath): return static_file(filepath, root='files') @route('/favicon.ico') def favicon(): return static_file('favicon.ico', root='files') @error(403) @view('error') def error403(code=None): return {'code': code} @error(404) @view('error') def error404(code=None): return {'code': code} # E X E C U T I O N ########################################################### process_blog_posts() if USE_HEROKU: run(host="0.0.0.0", port=int(os.environ.get("PORT", 80))) else: run(host="localhost", port=8080) # E N D O F F I L E #######################################################
@route('/favicon.ico') def favicon(): return static_file('favicon.ico', root='files') @error(403) @view('error') def error403(code=None): return {'code': code} @error(404) @view('error') def error404(code=None): return {'code': code} # E X E C U T I O N ########################################################### process_blog_posts() # if running wsgi then avoid run() in any form if __name__ == '__main__': if USE_HEROKU: run(host="0.0.0.0", port=int(os.environ.get("PORT", 80)), debug=IS_DEBUG) else: run(host="localhost", port=8080) # E N D O F F I L E #######################################################
timeout=timeout, priority=priority, options=options, machines=machines, package=package) # Show result template = lookup.get_template("success.html") return template.render(analid=analid, submitfile=data.filename) # Find an HTML report and render it @route("/view/<task_id>") def view(task_id): # Check if the specified task ID is valid if not task_id.isdigit(): return HTTPError(code=404, output="The specified ID is invalid") report_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", task_id, "reports", "report.html") # Check if the HTML report exists if not os.path.exists(report_path): return HTTPError(code=404, output="Report not found") # Return content of the HTML report return open(report_path, "rb").read() if __name__ == "__main__": run(host="0.0.0.0", port=8080, debug=True, reloader=True)
# remove ending slash from requests @hook('before_request') def strip_path(): request.environ['PATH_INFO'] = request.environ['PATH_INFO'].rstrip('/') tpl_path = path.join(get_script_rel_path("templates")) bottle.TEMPLATE_PATH.insert(0, tpl_path) try: with open(get_script_rel_path("config.json")) as f: config = json.load(f) except: pass if __name__ == '__main__': parser = argparse.ArgumentParser(description='starts a lists server') parser.add_argument( '--config', help='specifies the config file location (default: ./config.json)', default="./config.json") args = parser.parse_args() with open(args.config) as f: config = json.load(f) run(host='0.0.0.0', port=config['port']) app = default_app()
@route('/api/interval/<start>/<end>') @route('/api/interval/<start>/<end>.json') def api_interval(start, end): cur = con.cursor() cur.execute("SELECT * FROM Times WHERE Time > " + start + " AND Time < " + end) return json.dumps(cur.fetchall()) @route('/graph') def graph(): return static_file('graph.html', root='./static/') @route('/customgraph') def graph(): return static_file('customgraph.html', root='./static/') @route('/humans.txt') def humans(): return static_file('humans.txt', root='./static/') @route('/') def index(): return static_file('home.html', root='./static/') # for any files in static/ @route('/static/:filename') def send_static(filename): return static_file(filename, root='./static/') run(host='0.0.0.0', port=80)
def main(): '''main method''' bottle.run(server=OPT['server'], host='0.0.0.0', port=OPT['port'])
@view('index') def handle_submit(): school = request.forms.get('school') contr = Control() schools = contr.get_selected_schools() publictotal = contr.get_category_all_total('Public') privatetotal = contr.get_category_all_total('Private') pubpercent, prvpercent = contr.get_public_private_ratio(school) return {'schools': schools, 'publictotal': publictotal, 'privatetotal': privatetotal, 'pubpercent': pubpercent, 'prvpercent': prvpercent} #render home page @route('/') @view('index') def show_home(): contr = Control() schools = contr.get_selected_schools() publictotal = contr.get_category_all_total('Public') privatetotal = contr.get_category_all_total('Private') return {'schools': schools, 'publictotal': publictotal, 'privatetotal': privatetotal, 'pubpercent': 0, 'prvpercent': 0} #render static files i.e js,css @route('/staticfiles/<filepath:path>') def static_serve(filepath): return static_file(filepath, root='staticfiles') if __name__ == '__main__': run()
def default(): run(host = '127.0.0.1' , port = 80)