def run(argv): parser = argparse.ArgumentParser(parents=[serverParser, genericParser]) parser.description = """ Launch an interactive web server that allows the user to interact with the images. Etc... """ conf = parser.parse_args(argv) tileServer = InteractiveTileServer.fromArgsConf(conf) bottle.route('/', 'GET', tileServer.home) bottle.route('/info', 'GET', tileServer.info) bottle.route('/create', 'POST', tileServer.create) bottle.route('/delete', 'POST', tileServer.delete) bottle.route('/do/<displayId>', 'POST', tileServer.do) bottle.route('/actions/<displayId>/<last:int>', 'GET', tileServer.actions) bottle.route('/tile/<displayId>/<z:int>/<x:int>/<y:int>', 'GET', tileServer.tile) bottle.route('/view/<displayId>', 'GET', tileServer.view) bottle.route('/static/<filename:path>', 'GET', tileServer.static) # bottle.route('/tile/<z:int>/<x:int>/<y:int>/<filename:path>', # 'GET', tileServer.getTile) bottle.run(host=conf.host, port=conf.port, debug=conf.debug, quiet=conf.quiet, server='gevent')
def main(): parser = argparse.ArgumentParser(description='Run the Web Console') parser.add_argument('--fd', help='FD', default=None) parser.add_argument('--host', help='Host', default='0.0.0.0') parser.add_argument('--port', help='port', default=8080) parser.add_argument('--server', help='web server to use', default=SocketIOServer) parser.add_argument('--endpoint', default=None, help='Circus Endpoint. If not specified, Circus will ask you which ' 'system you want to connect to') parser.add_argument('--version', action='store_true', default=False, help='Displays Circus version and exits.') args = parser.parse_args() if args.version: print(__version__) sys.exit(0) if args.endpoint is not None: global client client = connect_to_endpoint(args.endpoint) run(app, host=args.host, port=args.port, server=args.server, fd=args.fd)
def run(self): #create the logger try: self._smgr_log = ServerMgrlogger() except: print "Error Creating logger object" # Connect to the cluster-servers database try: self._status_serverDb = db( self._smgr_main._args.server_manager_base_dir+self._smgr_main._args.database_name) except: self._smgr_log.log(self._smgr_log.DEBUG, "Error Connecting to Server Database %s" % (self._smgr_main._args.server_manager_base_dir+self._smgr_main._args.database_name)) exit() #set the status related handlers status_bottle_app = Bottle() status_bottle_app.route('/server_status', 'POST', self.put_server_status) status_bottle_app.route('/server_status', 'PUT', self.put_server_status) self._base_obj = self._status_thread_config['base_obj'] try: bottle.run(status_bottle_app, host=self._status_thread_config['listen_ip'], port=self._status_thread_config['listen_port']) except Exception as e: # cleanup gracefully exit()
def run(self, config, middleware): bottle.run(app = middleware, host = config.wsgi.host, port = config.wsgi.port, debug = config.wsgi.debug)
def start(cfg, states, queue_handler, repo_cfgs, repos, logger, buildbot_slots, my_username, db, repo_labels, mergeable_que, gh): env = jinja2.Environment( loader=jinja2.FileSystemLoader(pkg_resources.resource_filename(__name__, 'html')), autoescape=True, ) tpls = {} tpls['index'] = env.get_template('index.html') tpls['queue'] = env.get_template('queue.html') def make_webhook_url(path, username=None, password=None): return utils.make_url(**utils.merge_dicts(g.cfg['external'], path=path, username=username, password=password)) # XXX: this smells g.cfg = cfg g.states = states g.queue_handler = queue_handler g.repo_cfgs = repo_cfgs g.repos = repos g.logger = logger.getChild('server') g.buildbot_slots = buildbot_slots g.tpls = tpls g.my_username = my_username g.db = db g.gh = gh g.make_webhook_url = make_webhook_url g.repo_labels = repo_labels g.mergeable_que = mergeable_que run(host=cfg['web'].get('hostname', ''), port=cfg['web']['port'], server='waitress')
def test_bottle(path, method='GET', form={}): from bottle import TEMPLATE_PATH TEMPLATE_PATH.insert(0, '../views') TEMPLATE_PATH.insert(0, 'views') app = XXX_mywebapp.XXX_setup_web_interface() data = '&'.join(['%s=%s' % (k, v) for k, v in form.items()]) from bottle import run, CGIServer from StringIO import StringIO import os os.environ['REQUEST_METHOD'] = method os.environ['PATH_INFO'] = path os.environ['SCRIPT_NAME'] = path os.environ['QUERY_STRING'] = '' os.environ['SERVER_PROTOCOL'] = 'HTTP/1.1' os.environ['CONTENT_LENGTH'] = str(len(data)) old_stdout = sys.stdout sys.stdout = new_stdout = StringIO() old_stdin = sys.stdin sys.stdin = new_stdin = StringIO(data) new_stdin.seek(0) run(app, server=CGIServer) sys.stdin = old_stdin sys.stdout = old_stdout return new_stdout.getvalue()
def run(self, host='localhost', port=80): """Run the moulinette Start a server instance on the given port to serve moulinette actions. Keyword arguments: - host -- Server address to bind to - port -- Server port to bind to """ try: if self.use_websocket: from gevent.pywsgi import WSGIServer from geventwebsocket.handler import WebSocketHandler server = WSGIServer((host, port), self._app, handler_class=WebSocketHandler) server.serve_forever() else: run(self._app, host=host, port=port) except IOError as e: if e.args[0] == errno.EADDRINUSE: raise MoulinetteError(errno.EADDRINUSE, m18n.g('server_already_running')) raise
def main(): GRAPH = 'build-graph.json' HOST = os.environ.get('HOST', '0.0.0.0') PORT = os.environ.get('PORT', 8080) with open(GRAPH) as f: build_graph = json.load(f) concourse_shim = ConcourseShim(build_graph) # API requests under /api/v1/ go to the Concourse shim root = bottle.Bottle() root.mount('/api/v1', concourse_shim.app) # Avoid 404 errors in these cases. @root.route('/') @root.route('/demo') @root.route('/demo/') def index_redirect(): return bottle.redirect('/demo/index.html') # Everything else is treated as a file path, in the parent directory # (so we can get at Concourse ATC's files inside the ../atc/ submodule. @root.route('/<filepath:path>') def serve_file(filepath): return bottle.static_file(filepath, root='..') bottle.run(root, host=HOST, port=PORT)
def startServer(box): @bottle.route("/<num>/on") def on(num): box.on(int(num)) @bottle.route("/<num>/off") def off(num): box.off(int(num)) @bottle.route("/<num>/state") def singleState(num): return box.state(int(num)) @bottle.route("/state") def state(): bottle.response.content_type = 'application/json' return json.dumps(box.allState()) @bottle.route("/") def root(): return bottle.static_file("index.html", root="/home/josh/pyRelay") @bottle.route("/magic.js") def js(): return bottle.static_file("magic.js", root="/home/josh/pyRelay") @bottle.route("/switch-off.jpg") def switchOff(): return bottle.static_file("switch-off.jpg", root="/home/josh/pyRelay") @bottle.route("/switch-on.jpg") def switchOn(): return bottle.static_file("switch-on.jpg", root="/home/josh/pyRelay") bottle.run(host='0.0.0.0')
def serve(): run( server='gevent', host=State.config['host'], port=State.config['port'], debug=True, )
def run(self, hostname, port, server='wsgiref'): """ Start a webserver on hostname & port. """ self._hostname = hostname self._port = port bottle.run(self._app, host=hostname, port=port, server=server)
def OnSeeAllRecords(self, event): dialog = wx.TextEntryDialog(None,"Cut Off?","See All Data ", "", style=wx.OK|wx.CANCEL) if dialog.ShowModal() == wx.ID_OK: searchVal = dialog.GetValue() connection = sqlite3.connect('student.db') cursor = connection.cursor() sql = "SELECT * FROM student WHERE current_cgpa >= '" + searchVal + "'" cursor.execute(sql) above_avg = cursor.fetchall() sql = "SELECT * FROM student WHERE current_cgpa < '" + searchVal + "'" cursor.execute(sql) below_avg = cursor.fetchall() cursor.close() if len(above_avg) == 0 and len(below_avg)==0: # A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets. dlg2 = wx.MessageDialog( self, "No Student In This Category", "student", wx.OK) dlg2.ShowModal() # Show it dlg2.Destroy() # finally destroy it when finished. else: def StartServer(self): thread.start_new_thread(self._Serve, ()) def _Serve(self): print "starting server thread..." @route('/') def index(): output=template('resumetemp1',rows1=above_avg,rows2=below_avg) return output #return '<b>enrollment no is</b> %s' % searchVal run(host='localhost',port=8080)
def pStart(self): log.debug("Starting HTTP server...") run(host=self.conf['host'], port=int(self.conf['port'])) # TODO return True
def main(argv=None): """Main Block - Configure and run the Bottle Web Server.""" cmd_opts = parse_cmdline(argv)[0] if cmd_opts.confpath is not None: if os.path.exists(cmd_opts.confpath): conf_paths = [cmd_opts.confpath,] else: return "Configuration file not found: %s" % cmd_opts.confpath else: conf_paths = [os.path.join(path, defaultConfFilename) for path in ('/etc', '.',)] try: conf.update(parse_conf_files(conf_paths)) except ConfigurationError: return(sys.exc_info()[1]) if cmd_opts.bindport is not None: conf['bindport'] = cmd_opts.bindport if cmd_opts.bindaddr is not None: conf['bindaddr'] = cmd_opts.bindaddr if cmd_opts.baseurl is not None: conf['baseurl'] = cmd_opts.baseurl if cmd_opts.devel: from bottle import debug debug(True) app = SessionMiddleware(bottle.app(), sessionOpts) bottle.run(app=app, host=conf['bindaddr'], port=conf['bindport'], reloader=cmd_opts.devel)
def OnSeeResume(self, event): dialog = wx.TextEntryDialog(None,"Enrollment no.?","See Resume ", "", style=wx.OK|wx.CANCEL) if dialog.ShowModal() == wx.ID_OK: searchVal = dialog.GetValue() connection = sqlite3.connect('student.db') cursor = connection.cursor() sql = "SELECT * FROM student WHERE Enrollment_no = '" + searchVal + "'" cursor.execute(sql) recordset = cursor.fetchall() cursor.close() if len(recordset) == 0: # A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets. dlg2 = wx.MessageDialog( self, "Student Record not found", "student", wx.OK) dlg2.ShowModal() # Show it dlg2.Destroy() # finally destroy it when finished. else: #webbrowser.open('file:///home/ashmeet/python/student/resumetemp.tpl') def StartServer(self): thread.start_new_thread(self._Serve, ()) def _Serve(self): print "starting server thread..." @route('/') def index(): output=template('resumetemp',rows=recordset) return output #return '<b>enrollment no is</b> %s' % searchVal #webbrowser.open('file:///home/ashmeet/python/student/resumetemp.tpl') run(host='localhost',port=8080)
def runserver(host='', port='', debug=None, user='', group='', settings_file='', compressed_static=None, version=False, paste_id_length=None): if version: print '0bin V%s' % settings.VERSION sys.exit(0) settings.HOST = host or settings.HOST settings.PORT = port or settings.PORT settings.USER = user or settings.USER settings.GROUP = group or settings.GROUP settings.PASTE_ID_LENGTH = paste_id_length or settings.PASTE_ID_LENGTH try: _, app = get_app(debug, settings_file, compressed_static, settings=settings) except SettingsValidationError as err: print >>sys.stderr, 'Configuration error: %s' % err.message sys.exit(1) thread.start_new_thread(drop_privileges, (settings.USER, settings.GROUP)) if settings.DEBUG: run(app, host=settings.HOST, port=settings.PORT, reloader=True, server="cherrypy") else: run(app, host=settings.HOST, port=settings.PORT, server="cherrypy")
def main(): args = get_user_arguments() if not os.path.exists(args.directory): if args.match != "example_match": logger.critical("Data directory does not exist, custom match cannot be loaded") raise Exception("Cannot find custom match") logger.info("Creating data directory") os.makedirs(args.directory, exist_ok=True) match_directory = os.path.join(args.directory, args.match) if not os.path.exists(match_directory): from tools import defaults logger.info("Creating example match data") defaults.create_example_match(match_directory) prepare_server(match_directory) server = 'cherrypy' if not config.get('ssl') else enable_ssl( key=config['ssl_key'], cert=config['ssl_cert'], host=config['host'], port=config['port']) website.config = config app.merge(website.app.routes) bottle.run(app, host=config['host'], port=config['port'], server=server)
def start(cfg, states, queue_handler, repo_cfgs, repos, logger, buildbot_slots, my_username, db, repo_labels, mergeable_que, gh): env = jinja2.Environment( loader=jinja2.FileSystemLoader(pkg_resources.resource_filename(__name__, 'html')), autoescape=True, ) tpls = {} tpls['index'] = env.get_template('index.html') tpls['queue'] = env.get_template('queue.html') g.cfg = cfg g.states = states g.queue_handler = queue_handler g.repo_cfgs = repo_cfgs g.repos = repos g.logger = logger.getChild('server') g.buildbot_slots = buildbot_slots g.tpls = tpls g.my_username = my_username g.db = db g.repo_labels = repo_labels g.mergeable_que = mergeable_que g.gh = gh # Synchronize all PR data on startup if cfg['web'].get('sync_on_start', False): Thread(target=synch_all).start() try: run(host=cfg['web'].get('host', ''), port=cfg['web']['port'], server='waitress') except OSError as e: print(e, file=sys.stderr) os._exit(1)
def start(): """ Start the global manager web service. """ config = read_and_validate_config([DEFAILT_CONFIG_PATH, CONFIG_PATH], REQUIRED_FIELDS) common.init_logging( config['log_directory'], 'global-manager.log', int(config['log_level'])) state = init_state(config) switch_hosts_on(state['db'], config['ether_wake_interface'], state['host_macs'], state['compute_hosts']) bottle.debug(True) bottle.app().state = { 'config': config, 'state': state} host = config['global_manager_host'] port = config['global_manager_port'] log.info('Starting the global manager listening to %s:%s', host, port) bottle.run(host=host, port=port)
def main(): global state p = argparse.ArgumentParser(description="Generate a DAGA auth context") p.add_argument("auth_context") p.add_argument("private_data") opts = p.parse_args() with open(opts.auth_context, "r", encoding="utf-8") as fp: ac_data = json.load(fp) uuid = ac_data["uuid"] ac = daga.AuthenticationContext( ac_data["client_public_keys"], ac_data["server_public_keys"], ac_data["server_randomness"], ac_data["generators"] ) with open(opts.private_data, "r", encoding="utf-8") as fp: priv_data = json.load(fp) server = daga.Server(priv_data["n"], priv_data["private_key"], priv_data["secret"]) state = GlobalState({uuid : (ac, server)}) run(port=server.id + 12345)
def run(self): try: database.checkdb() bottle.run(app=app,host='0.0.0.0', port =self.port) except Eception,e: print e sys.exit(1)
def run_webapp(): @route('/', method='GET') @view('search_template') def search_page(): """Main search page.""" query = request.GET.get('query', '').strip() # Convert query to unicode. query = query.decode('utf-8') log.info('Web query: ' + query) answers = [] if query: banana = Banana() answers = banana.search(query) return dict(answers=answers) @route('/static/<filepath:path>') def server_static(filepath): """Serve static files (css for instance).""" log.info(filepath) return static_file(filepath, root='./static') log = logging.getLogger(__name__) debug(True) run(host='localhost', port=8000, reloader=True)
def launch_server_manager( listen_ip, listen_port, config_file): # Use a local logger.conf file for server manager debug and transaction logging settings. flexmock(server_mgr_main.ServerMgrlogger._ServerMgrlogger, log_file='./logger.conf') flexmock(server_mgr_main.ServerMgrTlog, log_file='./logger.conf') # mock all prints to go to a file #f = file('out.txt', 'w') #flexmock(sys, stdout=f) # Use local up address and unused port, instead of configured one to run SM. args_list = [] args_list += ['--listen_ip_addr', '%s' %(listen_ip)] args_list += ['--listen_port', '%s' %(listen_port)] args_list += ['--config_file', config_file] with mock.patch('server_mgr_cobbler.xmlrpclib.Server') as mock_server: with mock.patch('server_mgr_cobbler.subprocess') as mock_subprocess: vnc_server_mgr = server_mgr_main.VncServerManager(args_list) pipe_start_app = vnc_server_mgr.get_pipe_start_app() server_ip = vnc_server_mgr.get_server_ip() server_port = vnc_server_mgr.get_server_port() try: bottle.run(app=pipe_start_app,server = 'gevent', host=server_ip, port=server_port) except Exception as e: # cleanup gracefully print 'Exception error is: %s' % e vnc_server_mgr.cleanup()
def main(): parser = ArgumentParser(description="Run Graph Explorer") parser.add_argument("configfile", metavar="CONFIG_FILENAME", type=str) parser.add_argument("--debug", type=bool) args = parser.parse_args() config.init(args.configfile) c = ConfigValidator(obj=config) if not c.validate(): print "Configuration errors (%s):" % args.configfile for (key, err) in c.errors.items(): print key, for e in err: print "\n %s" % e sys.exit(1) app_dir = os.path.dirname(__file__) if app_dir: os.chdir(app_dir) debug(args.debug) run('graph_explorer.app', reloader=True, host=config.listen_host, port=config.listen_port, server=PasteServer)
def main(): global config config = ConfigObj(CONFIG_PATH, configspec = CONFIG_SPEC) validator = Validator() result = config.validate(validator, copy = True) if result is False: print "Config file validation failed" sys.exit(1) api = API(app, config) TellstickAPI(api, config) ConfigAPI(api, config, validator) if config['webroot']: root_app.mount(config['webroot'], app) else: root_app.merge(app) bottle.run(root_app, host = config['host'], port = config['port'], debug = config['debug'], reloader = config['debug'], server = 'cherrypy') # Write out default values config.write()
def start(db, host, port, debug): """ Start the server """ global _db _db = db run(host=host, port=port, debug=debug)
def main(): parser = argparse.ArgumentParser(description='Run the Web Console') parser.add_argument('--fd', help='FD', default=None) parser.add_argument('--host', help='Host', default='0.0.0.0') parser.add_argument('--port', help='port', default=8080) parser.add_argument('--server', help='web server to use', default=SocketIOServer) parser.add_argument('--endpoint', default=None, help='Circus Endpoint. If not specified, Circus will ask you which ' 'system you want to connect to') parser.add_argument('--version', action='store_true', default=False, help='Displays Circus version and exits.') parser.add_argument('--log-level', dest='loglevel', default='info', choices=LOG_LEVELS.keys() + [key.upper() for key in LOG_LEVELS.keys()], help="log level") parser.add_argument('--log-output', dest='logoutput', default='-', help="log output") parser.add_argument('--ssh', default=None, help='SSH Server') args = parser.parse_args() if args.version: print(__version__) sys.exit(0) # configure the logger configure_logger(logger, args.loglevel, args.logoutput) if args.endpoint is not None: connect_to_circus(args.endpoint, args.ssh) run(app, host=args.host, port=args.port, server=args.server, fd=args.fd)
def main(): global DB_SERVER, DB_ADDRESS print 'Using YouFace server at', DB_ADDRESS DB_SERVER = xmlrpclib.ServerProxy(DB_ADDRESS, allow_none=True) debug(True) run(host='localhost', port=8080, reloader=True)
def main(host, port, verbose, debug): if debug: logging.basicConfig(level=logging.DEBUG) if verbose: logging.basicConfig(level=logging.INFO) run(host=host, port=int(os.getenv("PORT", port)), reloader=True)
def run(self): from bottle import run setup(getattr(self.args, 'releases', {}), self.args.env) if self.args.command in ('start', 'restart'): print("Starting Mongo Orchestration on port %d..." % self.args.port) run(get_app(), host=self.args.bind, port=self.args.port, debug=False, reloader=False, quiet=not self.args.no_fork, server=self.args.server)
from bottle import route, run def tell_me_your_secret(): return 42 @route("/<top:int>/<bottom:int>") def danger(top, bottom): return { "result": top / bottom, "error": None, "secret": tell_me_your_secret() } print("[server] __name__ =", __name__) run(host="localhost", port="8080")
import bottle @bottle.route('/hello/<name>') def index(name): return template('<b>Hello {{name}}</b>!', name=name) @bottle.route('/') def root(): return "Kappa ZUppa" bottle.debug(True) bottle.run(host='localhost', port=8080, reloader=True)
from bottle import run, route @route('/') def index(): return '<h1>Hello, World!</h1>' if __name__ == '__main__': run()
def main(): run(host='localhost', port=7000)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import jieba #导入包 cut = jieba.cut # bottle 是一个http 的开发工具 from bottle import route,run # sentence :待拆分的字符串 中华人民共和国 -> #返回值: 以空格分隔的 字符串 def token(sentence): seg_list = list( cut(sentence) ) return " ".join(seg_list) #路由设置 @route('/token/:sentence') def index(sentence): print( "====",sentence ) result = token(sentence) return "{\"ret\":0, \"msg\":\"OK\", \"terms\":\"%s\"}" % result #相当于 java 中的 main if __name__ == "__main__": #以 http://localhost:8282/token/今天是星期天 访问 run(host="localhost",port=8282)
from bottle import Bottle, run, request, response, HTTPResponse APP1 = Bottle() @APP1.hook('before_request') def before_request(): print "APP 1 - Before Request {}".format(request.url) @APP1.hook('after_request') def after_request(): print "APP 1 - After Request {} - status code: {}".format( request.url, response.status_code) @APP1.route('/error') def error(): raise HTTPResponse(status=400) if __name__ == "__main__": run(APP1, host='localhost', port=8080)
@post('/metrics') def index(): body = request.body.read() jsonObj = json.loads(body) nova_metrica = { "umidade": jsonObj["umidade"], "temperatura": jsonObj["temperatura"] } metricasdb.insert_one(nova_metrica) return "sucesso" @get('/metrics') def lista(): itens = "<ul>" for x in metricasdb.find(): itens += "<li>Umidade: " + str( x['umidade']) + " | Temperatura: " + str( x['temperatura']) + "</li>" itens += "</ul>" return itens run(host='localhost', port=8083)
@route('/') def index(): return template(index_html, author='your name here') @route('/') @route('/hello/<name>') def greet(name='Stranger'): return template('Hello {{name}}, how are you?', name=name) @route('/:anything') def something(anything=''): return template(index_html, author=anything) @route('/object/<id:int>') def callback(id): assert isinstance(id, int) @route('/show/<name:re:[a-z]+>') def callback(name): assert name.isalpha() if __name__ == '__main__': run(host='localhost', port=9000, debug=True, reload=True)
@route('/edit/<no:int>', method="GET") def edit_item(no): if request.GET.save: edit = request.GET.task.strip() status = request.GET.status.strip() if status == 'open': status = 1 else: status = 0 conn = sqlite3.connect('todo.db') c = conn.cursor() c.execute("UPDATE todo SET task = ?, status = ? WHERE id LIKE ?", (edit, status, no)) conn.commit() return '<p>The item number %s was successsfully updated</p>' % no else: conn = sqlite3.connect('todo.db') c = conn.cursor() c.execute("SELECT task FROM todo WHERE id LIKE ?", (str(no))) cur_data = c.fetchone() return template('edit_task', old=cur_data, no=no) run(debug=True)
c_low = request.forms.get('low') c_script = request.forms.get('script') print("input parms are ", c_high, c_low, c_script) subprocess.Popen(["./lwcycler_test2.py", c_script, c_high, c_low], stdout=subprocess.PIPE) redirect("/lw14ask") @route('/spawn') def spawn(): return '<pre>%s</pre>' % subprocess.Popen( ["./lwturnboxon.py", "c5"], stdout=subprocess.PIPE).communicate()[0] #subprocess.run('sudo','python','./lwturnboxon','c5') #return template('<b>Spawned {{name}}</b>!',name='lwturnboxon') run(host='0.0.0.0', port=80, debug=True) print("in bottlepy after run ") """ #if some arguments given, use this as data. #len = 3, because filename is [0], dali-address is [1], dali-data is[2] if len(sys.argv) == 3: dali_device = int(sys.argv[1]) dali_value = int(sys.argv[2]) #print out the args #for eachArg in sys.argv: # print eachArg #If no arguments ar set or to much send this to dali else: dali_device = 1 #0...63 for single, or 0...16 for group
def post_update_item(): id = int(request.forms.get("id").strip()) updated_item = request.forms.get("updated_item").strip() connection = sqlite3.connect("todo.db") cursor = connection.cursor() cursor.execute("update todo set task=? where id=?", ( updated_item, id, )) connection.commit() cursor.close() redirect('/') @get('/delete_item/<id:int>') def get_delete_item(id): print("we want to delete #" + str(id)) connection = sqlite3.connect("todo.db") cursor = connection.cursor() cursor.execute("delete from todo where id=?", (id, )) connection.commit() cursor.close() redirect('/') if ON_PYTHONANYWHERE: application = default_app() else: debug(True) run(host="localhost", port=8080)
result = _db_adapter.add_category() return result @delete('/category/<catId:path>') def delete_category(catId): _db_adapter.delete_category(catId) @delete('/product/<id:int>') def delete_product(id): delete_product = _db_adapter.delete_product(id) return delete_product @post('/product') def add_product(): category_id = request.forms.get('category') title = request.forms.get('title') description = request.forms.get('desc') favorite = request.forms.get('favorite') price = request.forms.get('price') img_url = request.forms.get('img_url') product = Product(category_id, description, price, title, favorite, img_url) result = _db_adapter.add_product(product) return result run(host='localhost', port=4000, debug=True, reloader=True)
from bottle import route, run from dropbox import session @route('/hello') def hello(): return "Hello World!" run(host='localhost', port=8080, debug=True)
channelname = channel.name break if channelname is None: return "Unknown channel." print("cannelid:", channelid, "channelname:", channelname) if checkNewTask(taskname, channelname) is False: return "Failed to create task." else: task = None global tasks for t in tasks: if t.name == unquotedtaskname: task = t break if task is None: task = Task(name=unquotedtaskname) task.newsdata = NewsData(newsapi, name=task.name, channelName=channelname) task.newsdata.save() tasks.insert(0, task) redirect('/tasks/' + taskname) @bottle.route('/') def root(): return template('newsmind', tasks=tasks, channels=newsapi.channels) run(bottle, host='127.0.0.1', port=8000, debug=True, reloader=True)
return 'Missing Access Token' try: api = client.InstagramAPI(access_token=access_token, client_secret=CONFIG['client_secret']) tag_search, next_tag = api.tag_search(q="backclimateaction") tag_recent_media, next = api.tag_recent_media(tag_name=tag_search[0].name) photos = [] for tag_media in tag_recent_media: photos.append('<img src="%s"/>' % tag_media.get_standard_resolution_url()) content += ''.join(photos) except Exception as e: print(e) return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit) @route('/realtime_callback') @post('/realtime_callback') def on_realtime_callback(): mode = request.GET.get("hub.mode") challenge = request.GET.get("hub.challenge") verify_token = request.GET.get("hub.verify_token") if challenge: return challenge else: x_hub_signature = request.header.get('X-Hub-Signature') raw_response = request.body.read() try: reactor.process(CONFIG['client_secret'], raw_response, x_hub_signature) except subscriptions.SubscriptionVerifyError: print("Signature mismatch") bottle.run(app=app, host='localhost', port=8515, reloader=True)
if files: file_name_string = '[ ' for file in files: if file_name_string == '[ ': file_name_string = file_name_string + '"' + file + '"' else: file_name_string = file_name_string + ', "' + file + '"' file_name_string += ' ],' some_string = some_string + '"file": ' + file_name_string some_string += '"children": [\n' some_string = populate_child_tags(some_string, root, dirs) some_string += ']}\n' break with open(DATAFILE, "w") as outfile: outfile.write(some_string) if __name__ == '__main__': port_parser = argparse.ArgumentParser() port_parser.add_argument('-p', help='enter a port number here') result = port_parser.parse_args() try: if result.p: run(host='0.0.0.0', port=int(result.p), debug=True, reloader=True) else: run(host='0.0.0.0', port=5000, debug=True, reloader=True) except: print "The selected port is already in use, please use -p port_number to choose another port" exit(1)
errors['email_error'] = "" if not USER_RE.match(username): errors['username_error'] = "invalid username. try just letters and numbers" return False if not PASS_RE.match(password): errors['password_error'] = "invalid password." return False if password != verify: errors['verify_error'] = "password must match" return False if email != "": if not EMAIL_RE.match(email): errors['email_error'] = "invalid email address" return False return True connection_string = "mongodb://localhost" connection = pymongo.MongoClient(connection_string) database = connection.blog posts = blogPostDAO.BlogPostDAO(database) users = userDAO.UserDAO(database) sessions = sessionDAO.SessionDAO(database) bottle.debug(True) bottle.run(host='localhost', port=8082) # Start the webserver running and wait for requests
def run_webserver_as_thread(self): run(host='0.0.0.0', port=self.port)
singer_prod SET cd = %s, tragoudistis = %s, title = %s """ try: cursor.execute(sql, ( cd, singer, title, )) success = cursor.rowcount == 1 except db.IntegrityError: pass return {'results': {'cds': cds, 'artists': artists, 'success': success}} if __name__ == '__main__': url = urlparse.urlparse(os.environ.get('DATABASE_URL')) db = pymysql.connect(host=url.hostname, user=url.username, password=url.password, port=url.port, db=url.path[1:], charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor, autocommit=True) run(host='0.0.0.0', port=os.environ.get('PORT', 8080))
{"text": "Longitude", "type": "number"}, {"text": "Latitude", "type": "number"}, {"text": "PM 1.0", "type": "number"}, {"text": "PM 2.5", "type": "number"}, {"text": "PM 10", "type": "number"} ], "rows": get_all_rows(max_points, 357518080231251), "type": "table" }], '17dh0cf43jg7ka': [{ "columns":[ {"text": "Date", "type": "time"}, {"text": "Temperature", "type": "number"}, {"text": "Humidity", "type": "number"}, {"text": "Longitude", "type": "number"}, {"text": "Latitude", "type": "number"}, {"text": "PM 1.0", "type": "number"}, {"text": "PM 2.5", "type": "number"}, {"text": "PM 10", "type": "number"} ], "rows": get_all_rows(max_points, 357518080231095), "type": "table" }]} body = dumps(bodies[series]) return HTTPResponse(body=body, headers={'Content-Type': 'application/json'}) if __name__ == '__main__': run(app=app, host='localhost', port=8091)
def runServer(): run(host='192.168.43.60', port=9999)
# ,"flickr":{"url":"ss","words":["car"],"vote":0}}) # # # print ReceiveFeedback(feedback={"synsets":[u'red.n.02', u'fire.n.07',u'love.n.01'] # ,"flickr":{"url":"ss","words":["love"],"vote":0}}) # # # print ReceiveFeedback(feedback={"synsets":[u'red.n.02', u'fire.n.07',u'love.n.01'] # ,"flickr":{"url":"ss","words":["love"],"vote":0}}) @route('/static/<path:path>') def static(path): return static_file(path, os.getcwd() + '/static') @route('/words/<words>') def GetWords(words): words_list_ = words.split('+') return ReceiveFirstWords(words=words_list_) @post('/vote/<vote>') def Vote(vote): in_json_ = request.json in_json_["flickr"]["vote"] = vote return ReceiveFeedback(feedback=in_json_) run(host='localhost', port=8080, reloader=False)
if request.method == 'POST': data = dict(request.forms) Assignation().reassignation(data['current'],data['newtime']) return "Turno reasignado!!!, <a href='/operator/reassignation/{}'>volver atras</a>".format(ops) return dict(context=alldata) @route('/user') @db_session @view('user.tpl', template_lookup=['views']) def main_doctor_index(): """ User Main Index """ medics_patients = [] #Get Complete list of Patients patients = select(p for p in Patient)[:] data_patient = {'patient_data': [p.to_dict() for p in patients]} return dict(context=medics_patients) run(**settings['framework'])
return HTTPResponse(status=201) except ClientException: traceback.print_exc(sys.stderr) abort(500, "Could not upload file") except AttributeError: abort(400, "Request malformed, probably object is not sent with the file_content identifier") else: abort(401, 'Unknown user') @route('/register', method='POST') def post_central_server(): """ Registers the central server so local pop knows where to look for objects Content-Type: application/json Requires JSON string body containing central server url such as '{"url":"http://central.mcn.org:8182"}' """ # This is currently unused # TODO: Add authentication for admin # username = request.headers.get('X-Username') # password = request.headers.get('X-Password') jreq = request.json if jreq is not None: url = jreq.get('url') if url is not None: # TODO: Clean this global cdn_central_address cdn_central_address = url run(host='0.0.0.0', port=local_port, debug=True)
import bottle from app import views @bottle.route('/assets/<filepath:path>') def server_static(filepath): return bottle.static_file(filepath, root='assets') bottle.debug(True) bottle.run(host='0.0.0.0', port=8080)
pass except Exception as e: print(e) #删除任务 @route('/deleteTsk',method='POST') def deleteTsk(): try: params = request.body.read() try: params = json.loads(params) except: params = {} if 'TaskID' not in params: return {'result': 1, 'desc': 'Missing parameter TaskID'} ret = db.deleteTask(params) if ret['result'] != 0: res = {'result': 1, 'desc': ret['desc']} else: res = {'result': 0, 'desc': ret['desc']} return json.dumps(res, cls=JsonEncoder) except Exception as e: print(e) run(host='', port=8080, debug=False, interval=15, server='wsgiref')
import json from bottle import route, run, request @route("/webhook", method="POST") def webhook_handler(): body = request.json print('REQUEST BODY: ') print(json.dumps(body, indent=2)) run(host="localhost", port=5050, debug=True)
logger.debug("Have Exception,Error is : \n %s" % e) if __name__ == "__main__": # do the UNIX double-fork magic, see Stevens' "Advanced # Programming in the UNIX Environment" for details (ISBN 0201563177) try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError, e: print >> sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid > 0: # exit from second parent, print eventual PID before print "Daemon PID %d" % pid sys.exit(0) except OSError, e: print >> sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) # start the daemon main loop run(host="0.0.0.0", port=8089)
password = request.forms.get('password') insert_user(username, password) return template('verificacao_cadastro', nome=username) def check_login(username, password): d = {'adriano': 'python', 'jhon': 'java', 'peter': 'uhu'} if username in d.keys() and d[username] == password: return True return False @route('/', method='POST') #@post('/') def acao_login(): username = request.forms.get('username') password = request.forms.get('password') return template('verificacao_login', sucesso=check_login(username, password), nome=username) @error(404) def error404(error): return template('pagina404') if __name__ == '__main__': if os.environ.get('APP_LOCATION') == 'heroku': run(host='0.0.0.0', port=int(os.environ.get('PORT', 5000))) else: run(host='localhost', port=8080, debug=True, reloader=True)
def update_battery_states(charge, state): supply = SupplySide() data = supply.updateBatteryStates(charge, state) return json.dumps(data) @route( '/updateBatteryDetails/<efficiency:float>/<timeInterval:int>/<chargeSpecs:int>/<dischargeSpecs:int>/<energySpecs:int>/<initialEnergy:int>/<selfDischargeRate:float>/', method='GET') @enable_cors def update_battery_data(efficiency, timeInterval, chargeSpecs, dischargeSpecs, energySpecs, initialEnergy, selfDischargeRate): supply = SupplySide() data = supply.updateBatteryData(efficiency, timeInterval, chargeSpecs, dischargeSpecs, energySpecs, initialEnergy, selfDischargeRate) return json.dumps(data) @route('/history', method='GET') @enable_cors def get_history(): supply = SupplySide() data = supply.getHistoricalEnergyData() return json.dumps(data) # Run Server if __name__ == "__main__": run(host="0.0.0.0", port=4000, debug=True, reloader=True)