def test_redirect(self): urls = ( "/(.*)", "blog" ) class blog: def GET(self, path): if path == 'foo': raise web.seeother('/login', absolute=True) else: raise web.seeother('/bar') app_blog = web.application(urls, locals()) urls = ( "/blog", app_blog, "/(.*)", "index" ) class index: def GET(self, path): return "hello " + path app = web.application(urls, locals()) response = app.request('/blog/foo') self.assertEquals(response.headers['Location'], 'http://0.0.0.0:8080/login') response = app.request('/blog/foo', env={'SCRIPT_NAME': '/x'}) self.assertEquals(response.headers['Location'], 'http://0.0.0.0:8080/x/login') response = app.request('/blog/foo2') self.assertEquals(response.headers['Location'], 'http://0.0.0.0:8080/blog/bar') response = app.request('/blog/foo2', env={'SCRIPT_NAME': '/x'}) self.assertEquals(response.headers['Location'], 'http://0.0.0.0:8080/x/blog/bar')
def testCustomNotFound(self): urls_a = ("/", "a") urls_b = ("/", "b") app_a = web.application(urls_a, locals()) app_b = web.application(urls_b, locals()) app_a.notfound = lambda: web.HTTPError("404 Not Found", {}, "not found 1") urls = ( "/a", app_a, "/b", app_b ) app = web.application(urls, locals()) def assert_notfound(path, message): response = app.request(path) self.assertEquals(response.status.split()[0], "404") self.assertEquals(response.data, message) assert_notfound("/a/foo", b"not found 1") assert_notfound("/b/foo", b"not found") app.notfound = lambda: web.HTTPError("404 Not Found", {}, "not found 2") assert_notfound("/a/foo", b"not found 1") assert_notfound("/b/foo", b"not found 2")
def test_processors(self): urls = ( "/(.*)", "blog" ) class blog: def GET(self, path): return 'blog ' + path state = web.storage(x=0, y=0) def f(): state.x += 1 app_blog = web.application(urls, locals()) app_blog.add_processor(web.loadhook(f)) urls = ( "/blog", app_blog, "/(.*)", "index" ) class index: def GET(self, path): return "hello " + path app = web.application(urls, locals()) def g(): state.y += 1 app.add_processor(web.loadhook(g)) app.request('/blog/foo') assert state.x == 1 and state.y == 1, repr(state) app.request('/foo') assert state.x == 1 and state.y == 2, repr(state)
def test_subdirs(self): urls = ( "/(.*)", "blog" ) class blog: def GET(self, path): return "blog " + path app_blog = web.application(urls, locals()) urls = ( "/blog", app_blog, "/(.*)", "index" ) class index: def GET(self, path): return "hello " + path app = web.application(urls, locals()) self.assertEquals(app.request('/blog/foo').data, 'blog foo') self.assertEquals(app.request('/foo').data, 'hello foo') def processor(handler): return web.ctx.path + ":" + handler() app.add_processor(processor) self.assertEquals(app.request('/blog/foo').data, '/blog/foo:blog foo')
def test_redirect(self): urls = ("/(.*)", "blog") class blog: def GET(self, path): if path == "foo": raise web.seeother("/login", absolute=True) else: raise web.seeother("/bar") app_blog = web.application(urls, locals()) urls = ("/blog", app_blog, "/(.*)", "index") class index: def GET(self, path): return "hello " + path app = web.application(urls, locals()) response = app.request("/blog/foo") self.assertEquals(response.headers["Location"], "http://0.0.0.0:8080/login") response = app.request("/blog/foo", env={"SCRIPT_NAME": "/x"}) self.assertEquals(response.headers["Location"], "http://0.0.0.0:8080/x/login") response = app.request("/blog/foo2") self.assertEquals(response.headers["Location"], "http://0.0.0.0:8080/blog/bar") response = app.request("/blog/foo2", env={"SCRIPT_NAME": "/x"}) self.assertEquals(response.headers["Location"], "http://0.0.0.0:8080/x/blog/bar")
def get_app(config_file): """ Get the application. config_file is the path to the configuration file """ frontend.configuration.INGIniousConfiguration.load(config_file) if frontend.configuration.INGIniousConfiguration.get("maintenance", False): appli = web.application(urls_maintenance, globals(), autoreload=False) return appli appli = web.application(urls, globals(), autoreload=False) frontend.base.init_database() update_database() frontend.session.init(appli) def not_found(): """ Display the error 404 page """ return web.notfound(frontend.base.renderer.notfound('Page not found')) appli.notfound = not_found plugin_manager = PluginManager(appli, frontend.configuration.INGIniousConfiguration.get("plugins", [])) # Plugin Manager is also a Hook Manager backend_interface.init(plugin_manager) # Loads template_helper TemplateHelper() # Loads plugins plugin_manager.load() # Start the backend backend_interface.start() return appli
def main(): """<comment-ja> Web Application 起動処理 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ # logging load karesansui.lib.log.logger.reload_conf(karesansui.config['application.log.config']) if karesansui.lib.log.logger.is_ready() is False: raise karesansui.lib.log.logger.KaresansuiLogError("""Warning!! Logging set initial startup failed. example : Does the log configuration file exist? The present file path : %s """ % karesansui.config['application.log.config']) logger = logging.getLogger('karesansui.app') logger_trace = logging.getLogger('karesansui_trace.app') if not os.popen("ps -eo cmd | grep -e ^libvirtd -e ^/usr/sbin/libvirtd").read(): logger.error('libvirtd not running."/etc/init.d/libvirtd start" Please start.') print >>sys.stderr, '[Error] libvirtd not running."/etc/init.d/libvirtd start" Please start.' sys.exit(1) if web.wsgi._is_dev_mode() is True and env.has_key('FCGI') is False: logger.info('Start Mode [development]') app = web.application(urls, globals(), autoreload=True) app.internalerror = web.debugerror sys.argv = [] # argv clear else: logger.info('Start Mode [fastcgi]') web.config.debug = False app = web.application(urls, globals(), autoreload=False) #sys.argv = [] # argv clear # load processor! # - karesansui database! app.add_processor(load_sqlalchemy_karesansui) logger.info('The load was added. - load_sqlalchemy_karesansui') # - pysilhouette database! app.add_processor(load_sqlalchemy_pysilhouette) logger.info('The load was added. - load_sqlalchemy_pysilhouette') # http://domain/(../..)/hoge if karesansui.config['application.url.prefix']: mapping = (karesansui.config['application.url.prefix'], app) app = web.subdir_application(mapping) try: if (not opts is None) and opts.shell is True: # shell mode!! shell() else: app.run() # Web Application Start! except Exception, e: logger_trace.critical(traceback.format_exc()) print >>sys.stderr, "[ERROR] %s" % str(e.args) print >>sys.stderr, traceback.format_exc() return 1
def main(): #if __name__=="__main__": #sys.argv.append("5940") #Because web.py expects the port to be passed on argv[1] I will replace it here. The original argv[1] is '--genconf' sys.argv[1]='5940' print "Starting web.py at port 5940..." web.internalerror = web.debugerror # Start timer thread to run after 5 seconds print 'Waiting for page to load in browser...' threading.Timer(5.0, open_page).start() web.application(urls, globals()).run()
def main(): #/ PYTHONPATH bootstrap my_pp_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ## |pp| means PYTHONPATH if my_pp_dir not in sys.path: sys.path.insert(0, my_pp_dir) #/ import aoikwebpystart.urlstohdlrs as urlstohdlrs #/ parser = ArgumentParser(add_help=False) parser.add_argument( '-o', '--host', default='127.0.0.1', ) parser.add_argument( '-p', '--port', type=int, default=8000, ) parser.add_argument( '-w', '--wsgi', dest='wsgi_on', action='store_true', ) args_obj, _ = parser.parse_known_args() #/ wsgi_on = args_obj.wsgi_on if wsgi_on: host = args_obj.host port = args_obj.port wsgi_app = web.application(urlstohdlrs.SPEC_S).wsgifunc() #/ print('HTTP is on: {}:{}'.format(host, port)) srvr = make_server(host, port, wsgi_app) srvr.serve_forever() else: app = web.application(urlstohdlrs.SPEC_S) app.run()
def setUp(self): middleware = [] self.logger = logging.getLogger('restapi') urls = karesansui.urls.urls app = web.application(urls, globals(), autoreload=False) from karesansui.app import load_sqlalchemy_karesansui,load_sqlalchemy_pysilhouette app.add_processor(load_sqlalchemy_karesansui) app.add_processor(load_sqlalchemy_pysilhouette) self.prefix = "" if karesansui.config['application.url.prefix']: mapping = (karesansui.config['application.url.prefix'], app) app = web.subdir_application(mapping) self.prefix = karesansui.config['application.url.prefix'] self.app = TestApp(app.wsgifunc(*middleware)) self.headers = {} if username != None and password != None: from base64 import b64encode base64string =b64encode("%s:%s" % (username, password)) self.headers = {"Authorization": "Basic %s" % base64string} return True
def main(): print 'version:', settings.__version__ print 'git version:', settings.__git_version__ print 'release time', settings.__release_time__ app = web.application(urls, globals()) app.run()
def serve_http(hostname, port): """Starts the HTTP web server at the specified socket.""" sys.argv.insert(1, "%s:%s" % (hostname, port)) logging.info("Starting the ardj web service at http://%s:%s/" % (hostname, port)) if "--debug" not in sys.argv: ScrobblerThread().start() app = web.application(( "/", IndexController, "/api/auth(?:\.json)?", AuthController, "/api/status\.js(?:on)?", StatusController, "/api/tag/cloud\.json", TagCloudController, "/api/track/info\.json", InfoController, "/api/track/rocks\.json", RocksController, "/api/track/sucks\.json", SucksController, "/commit\.json", CommitController, "/raise", RaiseController, "/track/info\.js(?:on)?", InfoController, "/track/next\.json", NextController, "/track/queue\.json", QueueController, "/track/recent\.js(?:on)?", RecentController, "/track/search\.json", SearchController, )) app.run(ExceptionHandlingMiddleWare)
def main(): reload = os.environ.get('ARMADA_AUTORELOAD') == 'true' urls = ( '/health', Health.__name__, '/name', _get_module_path_to_class(Name), '/join', _get_module_path_to_class(Join), '/promote', _get_module_path_to_class(Promote), '/shutdown', _get_module_path_to_class(Shutdown), '/create', _get_module_path_to_class(Create), '/start', _get_module_path_to_class(Start), '/run', _get_module_path_to_class(Run), '/stop', _get_module_path_to_class(Stop), '/restart', _get_module_path_to_class(Restart), '/recover', _get_module_path_to_class(Recover), '/ssh-address', _get_module_path_to_class(SshAddress), '/hermes_address', _get_module_path_to_class(HermesAddress), '/env/(.*)/(.*)', _get_module_path_to_class(GetEnv), '/version', _get_module_path_to_class(GetVersion), '/images/(.*)', _get_module_path_to_class(Images), '/list', _get_module_path_to_class(List), '/info', _get_module_path_to_class(Info), ) app = web.application(urls, globals(), autoreload=reload) app.run()
def init_app(root, logger): abs_root = abspath(root) node = root_node(abs_root) URLS = ('/(.*)', 'handler') return application(URLS, { 'handler': Handler(node, logger) })
def run(self): port = 8080 app = web.application(self.urls, { 'bot':self.bot, 'bot_commands':self.bot_commands, 'bot_status_all':self.bot_status_all}) web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", self.port))
def webpy_run(msg): print msg webpy_app = web.application(urls,globals()) webpy_app.notfound = nf#自定义未找到页面 webpy_app.internalerror = ine#自定义 500 错误消息 webpy_app.run() print 'webpy bay!'
def application(urls, env): ''' A pythonic web.py application def hello(ctx, name): if not name: name = 'World' return 'Hello, ' + name + '!' urls = ('GET', '/(.*)', hello) app = application(urls, locals()) ''' def webpy_handler_class(method, pattern, handler): ''' convert functional view to class based view consumable by rest of webpy ''' class _Handler: pass def wrap(_handler): def wrapped(self, *args, **kwargs): return _handler(web.ctx, *args, **kwargs) return wrapped _Handler.__dict__[method] = wrap(handler) env[handler.__name__] = _Handler return pattern, handler.__name__ def compile_to_webpy(urls): ''' convert to webpy format ''' return [component for method, pattern, handler in urls for component in webpy_handler_class(method, pattern, handler) ] app = web.application(compile_to_webpy(chunk_urls(urls)), env) app.add_processor(web.loadhook(hook_less(app))) return app
def init_app(): app = web.application(urls, globals()) #app.notfound = api_notfound #app.internalerror = api_internalerror app.add_processor(web.loadhook(api_loadhook)) app.add_processor(web.unloadhook(api_unloadhook)) return app
def _load_fake_context(self): app = web.application() env = { 'PATH_INFO': '/', 'HTTP_METHOD': 'GET' } app.load(env)
def __init__(self, config, services_list): self.config = config urls = [] for each in services_list: if hasattr(each, 'uri'): # this is the old middleware and dataservice uri, cls = each.uri, each else: # this is middleware_app (soon to be deprecated) uri, cls = each if isinstance(uri, basestring): uri = (uri, ) for a_uri in uri: urls.append(a_uri) urls.append(classWithPartialInit(cls, config)) self.urls = tuple(urls) web.webapi.internalerror = web.debugerror web.config.debug = False self._identify() self._wsgi_func = web.application(self.urls, globals()).wsgifunc()
def testUnicodeInput(self): urls = ( "(/.*)", "foo" ) class foo: def GET(self, path): i = web.input(name='') return repr(i.name) def POST(self, path): if path == '/multipart': i = web.input(file={}) return i.file.value else: i = web.input() return repr(dict(i)) app = web.application(urls, locals()) def f(name): path = '/?' + urllib.urlencode({"name": name}) self.assertEquals(app.request(path).data, repr(name)) f(u'\u1234') f(u'foo') response = app.request('/', method='POST', data=dict(name='foo')) self.assertEquals(response.data, "{'name': u'foo'}") data = '--boundary\r\nContent-Disposition: form-data; name="x"\r\nfoo\r\n--boundary\r\nContent-Disposition: form-data; name="file"; filename="a.txt"\r\nContent-Type: text/plain\r\n\r\na\r\n--boundary--\r\n' headers = {'Content-Type': 'multipart/form-data; boundary=boundary'} response = app.request('/multipart', method="POST", data=data, headers=headers) self.assertEquals(response.data, 'a')
def getApplication(orm_cls): class lst(BaseListController): ORM_CLS = orm_cls class show(BaseShowController): ORM_CLS = orm_cls class deletectl(BaseDeleteController): ORM_CLS = orm_cls class new(BaseController): ID = orm_cls.__name__.lower() TITLE = 'New %s'%orm_cls.__name__ ORM_CLS = orm_cls urls = ( "/", lst, "/new", new, "/([0-9]+)", show, "/delete", deletectl ) return web.application(urls, locals())
def webpy(): urls = ( r'/', Index, r'/auth/0/', YOracleWebAuth, ) app = web.application(urls, globals()) app.run()
def main(): url_map = ( '/', 'TestRunner' ) app = web.application(url_map, globals()) app.run()
def server_thread(urls, funcs): """ thread for running the web server """ from x84.bbs import ini from web.wsgiserver import CherryPyWSGIServer from web.wsgiserver.ssl_pyopenssl import pyOpenSSLAdapter from OpenSSL import SSL cert, key, chain = None, None, None if ini.CFG.has_option('web', 'cert'): cert = ini.CFG.get('web', 'cert') if ini.CFG.has_option('web', 'key'): key = ini.CFG.get('web', 'key') if ini.CFG.has_option('web', 'chain'): chain = ini.CFG.get('web', 'chain') CherryPyWSGIServer.ssl_adapter = pyOpenSSLAdapter(cert, key, chain) CherryPyWSGIServer.ssl_adapter.context = SSL.Context(SSL.SSLv23_METHOD) CherryPyWSGIServer.ssl_adapter.context.set_options(SSL.OP_NO_SSLv3) CherryPyWSGIServer.ssl_adapter.context.use_certificate_file(cert) CherryPyWSGIServer.ssl_adapter.context.use_privatekey_file(key) if chain: CherryPyWSGIServer.ssl_adapter.context.use_certificate_chain_file(chain) CherryPyWSGIServer.ssl_adapter.context.set_cipher_list('ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS') app = web.application(urls, funcs) addr = (ini.CFG.get('web', 'addr'), ini.CFG.getint('web', 'port')) web.httpserver.runsimple(app.wsgifunc(), addr)
def init_web(dbcon, jira_priority_map): import sys sys.argv[1:] = ['8888'] app = web.application(urls, globals()) app.add_processor(add_global_hoSUCCESS({'dbcon':dbcon,'jira_priority_map': jira_priority_map})) print 'Serving on:' application = app.run()
def run(self): """ 启动网站 """ # 初始化 Common.init(); # 创建web应用 Logger.info('创建web应用') Common.app = web.application(Common.urls, globals()) # 创建session Logger.info('创建session') Common.initSession(Common.app); Common.session.menu = MenuManagement(); # 加载模板 Logger.info('加载模板') Common.render = web.template.render('templates/', base='baseframe', globals={'context': Common.session}) # # 设置错误页面 # Common.app.notfound = Common.notfound # Common.app.internalerror = Common.internalerror # 加载设置 Logger.info('加载设置') # Common.app.add_processor(Common.error_precessor); Common.app.add_processor(web.loadhook(Common.session_hook)); # Common.app.add_processor(web.loadhook(Common.session.menu.setSelectedMenu)); Common.app.add_processor(web.loadhook(AuthorityManagement.checkAuthority)) # Common.app.add_processor(web.unloadhook(AuthorityManagement.checkAuthority)) Logger.debug('网站启动') Common.initFinish = True Common.app.run();
def run(self): urls = [] views = {} for id, view in self._views.iteritems(): for pattern in view['patterns']: urls.extend([pattern, id]) views[id] = makeBoundedViewType(self, view['view']) web.config.debug = self._conf['debug'] if not urls: raise Exception("No Url registered") elif not views: raise Exception("No views registered") it = iter(urls) print "Published urls:" for url in it: print " - '%s'" % url it.next() app = web.application(urls, views) if self._conf['debug']: app.internalerror = web.debugerror # enable fastcgi if self.conf.get('fastcgi') is True: web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr) self._is_running = True app.run()
def __new__(cls, *args, **kwargs): app = web.application(*args, **kwargs) app.add_processor(web.loadhook(cls._connect)) app.add_processor(web.unloadhook(cls._disconnect)) return app
def main(): handle = None try: pifglobs.pif = ctypes.CDLL("libpif.so") strBuf = create_string_buffer(1000) rv = pifglobs.pif.pifVersion(strBuf, sizeof(strBuf)) print('Using pif library version: %s\n' % repr(strBuf.value)) handle = c_int(pifglobs.pif.pifInit()) dev = showDeviceID(handle) if dev != UNRECOGNIZED: print('pif detected') pifglobs.handle = handle pifglobs.state = STR_LEDS_ALT setMiscRegister(LED_ALTERNATING) app = web.application(urls, globals()) app.run() except: e = sys.exc_info()[0] print("\nException caught %s\n" % e) if handle: pifglobs.pif.pifClose(handle)
'/', 'Index', '/upload_file', 'Router.upload_file.UploadFile', '/upload_danmaku', 'Router.upload_danmaku.UploadDanmaku', '/upload_comment', 'Router.upload_comment.UploadComment', '/download_danmaku', 'Router.download_danmaku.DownloadDanmaku', '/download_comment', 'Router.download_comment.DownloadComment', # test url '/g36k', 'Router.test.Hello', ) class Index: def GET(self): return u'你想干嘛?' def POST(self): return None if __name__ == "__main__": app = web.application(router, globals()) app.run()
import web # import grid import position def is_test(): """check if run the test condition""" if 'WEBPY_ENV' in os.environ: return os.environ['WEBPY_ENV'] == 'test' urls = ( # pylint: disable=C0103 '/location', 'Location') app = web.application(urls, globals()) # pylint: disable=C0103 class Location(object): ''' the location service ''' def __init__(self): """the init function""" self.hello_ = "hello world!" # self.grid_ = grid.GridFile("gridFile_1209.data") self.position_ = position.Position() web.header('Content-Type', 'text/html') def GET(self): # pylint: disable=C0103
b = y1 - m*x1 m1 = (y3-y4)*1.0/(x3-x4) b1 = y3-m1*x3 for i in range(240): for j in range(352): if (m*j+b > i) or (m1*j+b1 > i): img[i, j, 0] = 0 img[i, j, 1] = 0 img[i, j, 2] = 0 return img def drawBox(self, img, x1, x2, y1, y2, colors): R = colors[0] G = colors[1] B = colors[2] img[y1:y2, x1, 0] = R img[y1:y2, x1, 1] = G img[y1:y2, x1, 2] = B img[y1:y2, x2, 0] = R img[y1:y2, x2, 1] = G img[y1:y2, x2, 2] = B img[y1, x1:x2, 0] = R img[y1, x1:x2, 1] = G img[y1, x1:x2, 2] = B img[y2, x1:x2, 0] = R img[y2, x1:x2, 1] = G img[y2, x1:x2, 2] = B return img DOTstream = web.application(urls, locals());
conn = getConnection() cur = conn.cursor() _row = cur.execute(strQuery).fetchone() if _row: strContent = '<html>\n' \ '<head>\n' \ '<meta charset="UTF-8">\n' \ '<style>body{background-color:#a5cbf7;}</style>\n' \ '</head>\n' \ '<body>\n' \ '<h1>%s</h1>\n' \ '<p><strong>Date:</strong> %s</p>\n' \ '<p><strong>From:</strong> %s</p>\n' \ '<p><strong>FromLink:</strong> %s</p>\n' \ '<pre>%s</pre>\n' \ '<p><strong>DateCreated:</strong> %s</p>\n' \ '<p><strong>DateModified:</strong> %s</p>\n' \ '</body>\n' \ '</html>' % (HtmlEncode(_row[0]), _row[1], HtmlEncode(_row[2]), HtmlEncode(_row[3]), HtmlEncode(_row[4]), _row[5], _row[6]) strContent = strContent.encode('utf-8') else: strContent = 'Empty' else: strContent = 'None' return strContent if __name__ == '__main__': web.application(urls, globals()).run()
return render.newpass({'code': 0, 'message': '', 'params': params}) class Register: def GET(self): login.Login.logout() return render.register(None) def POST(self): post = web.input() post.u_create_time = int(time.time()) post.u_email = web.utf8(post.get('u_email')) post.u_name = web.utf8(post.get('u_name')) #change to md5 post.u_pass = md5.new(web.utf8(post.u_pass)).hexdigest() try: idlist = pduser.insert_by_list([post]) newid = idlist.pop() if newid: #表示注册成功 login.Login.encode_cookie(newid) #保存注册信息 #return web.seeother(web.ctx.sitehost+"/me/setting/basic") # go to accounts index return web.seeother(web.ctx.sitehost) # go to accounts index except: pass return render.register(post) app_account = web.application(urls, locals())
#return web.notfound("Sorry, the page you were looking for was not found.") return json.dumps({'ok': 0, 'errcode': 404}) def internalerror(): #return web.internalerror("Bad, bad server. No donut for you.") return json.dumps({'ok': 0, 'errcode': 500}) def badData(): return json.dumps({'ok': 0, 'errcode': 400}) urls = ('/translate(.*)', 'translate') app = web.application(urls, globals()) app.notfound = notfound app.internalerror = internalerror # class configuration: # ConfigurationFile = 'configuration.json' # def GET( self, params ): # queryString = web.input() # print( queryString ) # if( not os.path.isfile( configuration.ConfigurationFile ) ): # print( 'Configuration file "{}" not found, exiting.'.format( configuration.ConfigurationFile ) ) # return internalerror() # with open( configuration.ConfigurationFile ) as json_file: # configurationTxt = json.load( json_file ) # # print( 'Configuration: \n{}', json.dumps( configurationTxt ) )
print "Creating sensor_logs table" dbcur.execute(create_table) if not dbcur.execute(check_table).fetchone(): print "Unable to create sensor_log table" exit() conn.close() urls = ( urls = ( '/sensorcurrentanalog/(.*)', 'sensor_current_analog', '/sensorcurrentbinary/(.*)', 'sensor_current_binary' ) app = web.application(urls, globals()) sensor_gas = sensors.sensor_PCF8591('Gas',19,0,10,0) sensor_water = sensors.sensor_water('Water', 17,None,None,0) sensor_flame = sensors.sensor_PCF8591('Flame', 16,2,10,0) sensor_smoke = sensors.sensor_PCF8591('Smoke', 20,1,10,0) sensor_co = sensors.sensor_PCF8591('CO', 18,3,15,0) sensor_temp = sensors.sensor_temp('Temp', None,None,20,0) class hello: def sensor_current_analog(self, sensor_name): if not sensor_name: print "No Name" exit() elif sensor_name == 'gas':
def __init__(self, cl): global client client = cl app = web.application(urls, globals()) app.run()
def run_web(): if __name__ == "__main__": import web vms_info = print_vms() app = web.application(urls, globals()) app.run()
delete_edge(edge_name=edge_name) except exceptions.NoObject as error: raise self.generate_http_response(HTTP_STATUS_CODE.NotFound, exc_cls=error.__class__.__name__, exc_msg=error) except exceptions.ESSException as error: raise self.generate_http_response(HTTP_STATUS_CODE.InternalError, exc_cls=error.__class__.__name__, exc_msg=error) except Exception as error: print(error) print(format_exc()) raise self.generate_http_response( HTTP_STATUS_CODE.InternalError, exc_cls=exceptions.CoreException.__name__, exc_msg=error) raise self.generate_http_response(HTTP_STATUS_CODE.OK, data={ 'status': 0, 'message': 'deleted successfully' }) """---------------------- Web service startup ----------------------""" APP = application(URLS, globals()) application = APP.wsgifunc()
sys.path.append(os.path.join(filedir)) class AppURLopener(urllib.FancyURLopener): version = "LLIN /1.0" urllib._urlopener = AppURLopener() logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', filename='/tmp/llin_sms.log', datefmt='%Y-%m-%d %I:%M:%S', level=logging.DEBUG) urls = ("/cgi-bin/sendsms", "Sendsms", "/test", "Test") app = web.application(urls, globals()) # web.config.smtp_server = 'mail.mydomain.com' web.config.debug = False render = render_jinja('templates', encoding='utf-8') class Sendsms: def GET(self): params = web.input(fuuid='', district='') print params return "Accepted" def POST(self): pass
import urllib reload(sys) sys.setdefaultencoding('UTF-8') # @UndefinedVariable urls = ( '/white/agency?', 'agency', '/white/view?', 'view', '/white/home?', 'home', '/.*', 'home', ) app = web.application(urls, locals()) class White: ''' Redis key 说明 HSET H:phonenumber phonenumber username,预申请通过的手机号码和用户名白名单 HSET S:ip:%s phonenumber username,申请有效IP映射手机号码和用户名,有效时间 3*24*60*60 H:admin:%s author,backend,memo 后台信息存储 ''' _HOST = '122.144.167.76' _ADMIN_DENY_FILE = '/usr/local/nginx/conf/admin/deny/dynamic.white.list' _TIMEDELTA = 3 * 24 * 60 * 60 _KEY_HSET_PHONENUMBER = 'H:phonenumber'
import web urls = ("/", "c") app = web.application(urls, globals(), autoreload=True) class c: def GET(self): return "c"
import web, app.controller # Application urls urls = ( '/staff', 'app.controller.Staff', '/staff/edit/([0-9]+)', 'app.controller.Staff', '/staff/delete/([0-9]+)', 'app.controller.DeleteStaff', '/error', 'app.controller.Error', '/success', 'app.controller.Success', ) if __name__ == '__main__': app = web.application(urls) web.internalerror = web.debugerror app.run()
#Required for mod_wsgi in a random folder. CURDIR = os.path.dirname(__file__) if CURDIR not in sys.path: sys.path.append(CURDIR) logging_config_path = os.path.abspath(os.path.join(CURDIR, "logging.conf")) logging.config.fileConfig(logging_config_path) from app.common.common import is_test, debug, debug_sql web.config.debug = debug web.config.debug_sql = debug_sql import app.index # @UnusedImport import app.vaisalaobs import app.datex2 import app.admin import app.tables MAPPING = ('/', 'app.index.Index', '/jpglist.html', 'app.vaisalaobs.ListJpg', '/datex2', app.datex2.APP, '/export', app.vaisalaobs.APP, '/admin', app.admin.APP, '/table', app.tables.APP) APP = web.application(MAPPING, globals(), autoreload=False) application = APP.wsgifunc() if (not is_test()) and __name__ == "__main__": web.config.debug_sql = True web.config.debug = True APP.run()
def build_app(): app = web.application(urls, locals()) app.add_processor(load_db_driver) app.add_processor(forbid_client_caching) return app
class reportdayjson: @Sesion def GET(self): import simplejson as json from db import reportday i = web.input(id=None, fecha=None) print "VEHICLE ID: ", i.id print "FECHA: ", i.fecha web.header('content-Type', 'application/json') def dthandler(obj): obj.fecha = obj.fecha.strftime("%F %H:%M:%S") return obj return json.dumps([dthandler(row) for row in reportday(i.id, i.fecha)]) class listeventjson: @Sesion def GET(self): import simplejson as json from db import countEventClient web.header('content-Type', 'application/json') return json.dumps( [row for row in countEventClient(web.ctx.session.clienteId)]) app_user = web.application(urls, locals())
def _run_web_server(): try: P.web_app = web.application(P.urls, globals()) web.httpserver.runsimple(P.web_app.wsgifunc(), ("0.0.0.0", P.WEB_PORT)) except Exception as ex: L.l.error("Start accel raw data webserver failed, ex={}".format(ex))
import json import web import cloudserver urls = ( "/(.+)", "UserRecommendations", ) class UserRecommendations: def POST(self, Id): raw_data = web.data() name = cloudserver.db.PID2Name(Id) recommendations = cloudserver.db.get_recommendations(name) return recommendations UserRecs = web.application(urls, locals())
def run_data_server(): sys.argv.append('0.0.0.0:%s' % config.data_port) app = web.application(urls, globals()) app.run()
def run(self): from api.urls import urls self.app = web.application(urls, {}) self.app.run()
form.Button("submit", type="submit", description="Search"), validators=[form.Validator("blah", lambda x: True)]) class index: def GET(self): f = searchfor_form() return render.index(f) def POST(self): f = searchfor_form() f.validates() (books, pages) = search_for(f.d.findthis) return render.results(books, f.d.findthis, pages) class error: def GET(self): return render.error() class results: def GET(self, books, term, pages): return render.results(books, term, pages) web.debug = False app = web.application(urls, globals(), autoreload=False).wsgifunc()
""" async_task = consumer_group.unbind.apply_async( (group_id, repo_id, distributor_id, {})) raise pulp_exceptions.OperationPostponed(async_task) # web.py application ----------------------------------------------------------- _URLS = ( '/$', ConsumerGroupCollection, '/search/$', ConsumerGroupSearch, # resource search '/([^/]+)/$', ConsumerGroupResource, '/([^/]+)/bindings/$', ConsumerGroupBindings, '/([^/]+)/bindings/([^/]+)/$', ConsumerGroupBindings, '/([^/]+)/bindings/([^/]+)/([^/]+)/$', ConsumerGroupBinding, '/([^/]+)/actions/associate/$', ConsumerGroupAssociateAction, '/([^/]+)/actions/unassociate/$', ConsumerGroupUnassociateAction, '/([^/]+)/actions/content/(install|update|uninstall)/$', ConsumerGroupContentAction, ) application = web.application(_URLS, globals())
@strategy('/complete/%(backend)s/') def _auth(self, backend): return do_auth(self.strategy) class complete(BaseViewClass): def GET(self, backend, *args, **kwargs): return self._complete(backend, *args, **kwargs) def POST(self, backend, *args, **kwargs): return self._complete(backend, *args, **kwargs) @strategy('/complete/%(backend)s/') def _complete(self, backend, *args, **kwargs): return do_complete(self.strategy, login=lambda strat, user: self.login_user(user), user=self.get_current_user(), *args, **kwargs) class disconnect(BaseViewClass): @strategy() def POST(self, backend, association_id=None): return do_disconnect(self.strategy, self.get_current_user(), association_id) app_social = web.application(urls, locals())
def background_hook_service(urls, g_vars): # run app and respond to agent webhook callbacks (run in background) # port number has to be the first command line arguement # pass in urls app = web.application(urls, g_vars) app.run()
class index: ''' Return web form to trigger lambda service. ''' def GET(self): form = myform() return render.index(form) ''' Post to start container to run user code ''' def POST(self): # Parse post parameter parameters = web.input() print(parameters) # Example: "python27" runtime = parameters.get("Runtime") # Start lambda container if runtime == RUNTIME_PYTHON27: containerRuntime = python27_container.Python27Container() elif runtime == RUNTIME_PYTHON35: containerRuntime = python35_container.Python35Container() elif runtime == RUNTIME_GOLANG: containerRuntime = golang_container.GolangContainer() elif runtime == RUNTIME_UBUNTU: containerRuntime = ubuntu_container.UbuntuContainer() elif runtime == RUNTIME_CENTOS: containerRuntime = centos_container.CentosContainer() elif runtime == RUNTIME_C: containerRuntime = c_container.CContainer() elif runtime == RUNTIME_CPP: containerRuntime = cpp_container.CppContainer() elif runtime == RUNTIME_RUBY: containerRuntime = ruby_container.RubyContainer() elif runtime == RUNTIME_ERLANG: containerRuntime = erlang_container.ErlangContainer() elif runtime == RUNTIME_NODE: containerRuntime = node_container.NodeContainer() elif runtime == RUNTIME_PHP: containerRuntime = php_container.PhpContainer() elif runtime == RUNTIME_JAVA9: containerRuntime = java9_container.Java9Container() elif runtime == RUNTIME_JAVAOPENJDK9: containerRuntime = javaopenjdk9_container.JavaOpenjdk9Container() elif runtime == RUNTIME_R: containerRuntime = r_container.RContainer() elif runtime == RUNTIME_HASKELL: containerRuntime = haskell_container.HaskellContainer() elif runtime == RUNTIME_PERL: containerRuntime = perl_container.PerlContainer() elif runtime == RUNTIME_LUA: containerRuntime = lua_container.LuaContainer() elif runtime == RUNTIME_SWIFT: containerRuntime = swift_container.SwiftContainer() elif runtime == RUNTIME_OBJECTIVEC: containerRuntime = objectivec_container.ObjectiveCContainer() elif runtime == RUNTIME_ELIXIR: containerRuntime = elixir_container.ElixirContainer() elif runtime == RUNTIME_RUST: containerRuntime = rust_container.RustContainer() else: containerRuntime = basic_container.BasicContainer() # Example: True if click the checkbox is_edit_online_code = parameters.has_key("Edit online code") if is_edit_online_code == False: # Example: "/home/tobe/code/lambda-docker/example/" load_file_path = parameters.get("Load local file") user_code_path = load_file_path else: # Example: "print('test python runtime')" online_code = parameters.get("Online code") tmp_path = "/tmp/" user_code_file_name = "main" + containerRuntime.file_extension with open(tmp_path + user_code_file_name, "w") as text_file: text_file.write(online_code) user_code_path = tmp_path # Example: "python27" runtime = parameters.get("Runtime") # TODO(tobe): Make is configurable for users to set cpu and memory container_memory = "1g" container_cpu_shares = 1024 # Start lambda container container = containerRuntime.create_lambda_container( user_code_path, container_memory, container_cpu_shares) containerRuntime.start_lambda_container(container) # Wait for logs of container time.sleep(1) log = containerRuntime.get_container_log(container) if log: return log else: return "Success to run lambda container" if __name__ == "__main__": app = web.application(urls, globals()) app.run()
def create_app(ref): global hub_ref hub_ref = ref return web.application(urls, globals(), autoreload=False).wsgifunc()
'DEF:freezer=%s:freezer:AVERAGE' % (RRD_FILE, ), 'DEF:fridge=%s:fridge:AVERAGE' % (RRD_FILE, ), 'DEF:light=%s:light:AVERAGE' % (RRD_FILE, ), 'CDEF:light_offset=light,11,-', 'HRULE:4.45#000000::dashes', 'HRULE:1.67#000000::dashes', 'HRULE:-12.0#000000::dashes', 'HRULE:-18.0#000000::dashes', 'HRULE:0#000000', 'LINE2:ambient#00ff00:ambient ', 'GPRINT:ambient:LAST:Cur\:%8.2lf', 'GPRINT:ambient:AVERAGE:Avg\:%8.2lf', 'GPRINT:ambient:MAX:Max\:%8.2lf', r'GPRINT:ambient:MIN:Min\:%8.2lf\j', 'LINE2:freezer#0000ff:freezer ', 'GPRINT:freezer:LAST:Cur\:%8.2lf', 'GPRINT:freezer:AVERAGE:Avg\:%8.2lf', 'GPRINT:freezer:MAX:Max\:%8.2lf', r'GPRINT:freezer:MIN:Min\:%8.2lf\j', 'LINE2:fridge#ff0000:fridge ', 'GPRINT:fridge:LAST:Cur\:%8.2lf', 'GPRINT:fridge:AVERAGE:Avg\:%8.2lf', 'GPRINT:fridge:MAX:Max\:%8.2lf', r'GPRINT:fridge:MIN:Min\:%8.2lf\j', 'LINE2:light_offset#000000:light on/off ') file = open(path, 'rb') data = file.read() file.close() os.close(fd) os.unlink(path) web.header('Content-Type', 'image/png') return data if __name__ == "__main__": web.application(URLS, globals()).run()
def app(): return web.application(urls, _locals)
def start_api_server(): logger.info(">>>>>> API 服务启动!端口:%d" % config.API_PORT) sys.argv.append('0.0.0.0:%s' % config.API_PORT) app = web.application(urls, globals()) app.run()