def init_application(dbconf=None,consconf=None): log.startLogging(sys.stdout) TEMPLATE_PATH.append("./admin/views/") ''' install plugins''' engine,metadata = models.get_engine(dbconf) sqla_pg = sqla_plugin.Plugin(engine,metadata,keyword='db',create=False,commit=False,use_kwargs=False) _sys_param_value = functools.partial(get_param_value,sqla_pg.new_session()) MakoTemplate.defaults.update(**dict( get_cookie = get_cookie, fen2yuan = utils.fen2yuan, fmt_second = utils.fmt_second, request = request, sys_param_value = _sys_param_value, system_name = _sys_param_value("1_system_name"), radaddr = _sys_param_value('3_radiusd_address'), adminport = _sys_param_value('4_radiusd_admin_port') )) # connect radiusd websocket admin port websock.connect( MakoTemplate.defaults['radaddr'], MakoTemplate.defaults['adminport'], ) mainapp.install(sqla_pg) ops_app.install(sqla_pg) bus_app.install(sqla_pg) mainapp.mount("/ops",ops_app) mainapp.mount("/bus",bus_app) #create dir try: os.makedirs(os.path.join(APP_DIR,'static/xls')) except:pass
def watermark(app, env): """Add watermark.""" if app.config.sphinxmark_debug is True: logging.basicConfig(level=logging.DEBUG) app.info('adding watermark...', nonl=True) if app.config.sphinxmark_enable is True: # append source directory to TEMPLATE_PATH so template is found srcdir = os.path.abspath(os.path.dirname(__file__)) TEMPLATE_PATH.append(srcdir) staticbase = '_static' buildpath = os.path.join(app.outdir, staticbase) try: os.makedirs(buildpath) except OSError: if not os.path.isdir(buildpath): raise if app.config.sphinxmark_image == 'default': imagefile = 'watermark-draft.png' imagepath = os.path.join(srcdir, imagefile) copy(imagepath, buildpath) logging.debug('Using default image: ' + imagefile) elif app.config.sphinxmark_image == 'text': imagefile = createimage(app, srcdir, buildpath) logging.debug('Image: ' + imagefile) else: imagefile = app.config.sphinxmark_image if app.config.html_static_path: staticpath = app.config.html_static_path[0] else: staticpath = '_static' logging.debug('static path: ' + staticpath) imagepath = os.path.join(staticpath, imagefile) logging.debug('Imagepath: ' + imagepath) if os.path.exists(imagepath) is False: logging.error( "Cannot find '%s'. Put watermark " + "images in the '_static' directory or " + "specify the location using 'html_static_path'.", imagefile) if app.config.sphinxmark_div == 'default': div = 'body' else: div = app.config.sphinxmark_div css = template('watermark', div=div, image=imagefile) logging.debug("Template: " + css) cssname = 'sphinxmark.css' cssfile = os.path.join(buildpath, cssname) with open(cssfile, 'w') as f: f.write(css) app.add_stylesheet(cssname) app.info(' done')
def shift_local(): import os from bottle import TEMPLATE_PATH, default_app ON_OPENSHIFT = False if os.environ.has_key('OPENSHIFT_REPO_DIR'): ON_OPENSHIFT = True if ON_OPENSHIFT: TEMPLATE_PATH.append( os.path.join(os.environ['OPENSHIFT_HOMEDIR'], 'runtime/repo/wsgi/views/')) application = default_app() else: import commands from bottle import run print "AdNail - Interfaces disponibles: " print commands.getoutput("/sbin/ifconfig | egrep -o '^[a-z].......'") intfz = raw_input('Introduce la interfaz a utilizar: ') comand = "/sbin/ifconfig " + intfz + " | egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | egrep -v '*(0|255)$'" iphost = commands.getoutput(comand) print "La IP del Servidor es: ", iphost run(host=iphost, port=8080, debug=True)
def init_application(dbconf=None,cusconf=None,secret=None): log.startLogging(sys.stdout) base.update_secret(secret) utils.update_secret(secret) log.msg("start init application...") TEMPLATE_PATH.append("./customer/views/") ''' install plugins''' engine,metadata = models.get_engine(dbconf) sqla_pg = sqla_plugin.Plugin(engine,metadata,keyword='db',create=False,commit=False,use_kwargs=False) session = sqla_pg.new_session() _sys_param_value = functools.partial(get_param_value,session) _get_member_by_name = functools.partial(get_member_by_name,session) _get_account_by_number = functools.partial(get_account_by_number,session) _get_online_status = functools.partial(get_online_status,session) MakoTemplate.defaults.update(**dict( get_cookie = get_cookie, fen2yuan = utils.fen2yuan, fmt_second = utils.fmt_second, request = request, sys_param_value = _sys_param_value, system_name = _sys_param_value("2_member_system_name"), get_member = _get_member_by_name, get_account = _get_account_by_number, is_online = _get_online_status )) websock.connect( _sys_param_value('3_radiusd_address'), _sys_param_value('4_radiusd_admin_port') ) mainapp.install(sqla_pg)
def init_application(dbconf=None,cusconf=None): log.startLogging(sys.stdout) TEMPLATE_PATH.append("./customer/views/") ''' install plugins''' engine,metadata = models.get_engine(dbconf) sqla_pg = sqla_plugin.Plugin(engine,metadata,keyword='db',create=False,commit=False,use_kwargs=False) session = sqla_pg.new_session() _sys_param_value = functools.partial(get_param_value,session) _get_member_by_name = functools.partial(get_member_by_name,session) _get_account_by_number = functools.partial(get_account_by_number,session) _get_online_status = functools.partial(get_online_status,session) MakoTemplate.defaults.update(**dict( get_cookie = get_cookie, fen2yuan = utils.fen2yuan, fmt_second = utils.fmt_second, request = request, sys_param_value = _sys_param_value, system_name = _sys_param_value("2_member_system_name"), get_member = _get_member_by_name, get_account = _get_account_by_number, is_online = _get_online_status )) websock.connect( _sys_param_value('3_radiusd_address'), _sys_param_value('4_radiusd_admin_port') ) mainapp.install(sqla_pg)
def init_application(dbconf=None, consconf=None): log.startLogging(sys.stdout) log.msg("start init application...") TEMPLATE_PATH.append("./admin/views/") ''' install plugins''' log.msg("init plugins..") engine, metadata = models.get_engine(dbconf) sqla_pg = sqla_plugin.Plugin(engine, metadata, keyword='db', create=False, commit=False, use_kwargs=False) session = sqla_pg.new_session() _sys_param_value = functools.partial(get_param_value, session) log.msg("init template context...") MakoTemplate.defaults.update( **dict(get_cookie=get_cookie, fen2yuan=utils.fen2yuan, fmt_second=utils.fmt_second, currdate=utils.get_currdate, request=request, sys_param_value=_sys_param_value, system_name=_sys_param_value("1_system_name"), radaddr=_sys_param_value('3_radiusd_address'), adminport=_sys_param_value('4_radiusd_admin_port'), permit=permit, all_menus=permit.build_menus( order_cats=[u"系统管理", u"营业管理", u"运维管理"]))) # connect radiusd websocket admin port log.msg("init websocket client...") wsparam = ( MakoTemplate.defaults['radaddr'], MakoTemplate.defaults['adminport'], ) reactor.callLater(5, websock.connect, *wsparam) log.msg("init tasks...") reactor.callLater(7, tasks.start_jobs, sqla_pg.new_session) log.msg("init operator rules...") for _super in session.query( models.SlcOperator.operator_name).filter_by(operator_type=0): permit.bind_super(_super[0]) log.msg("install plugins...") mainapp.install(sqla_pg) ops_app.install(sqla_pg) bus_app.install(sqla_pg) mainapp.mount("/ops", ops_app) mainapp.mount("/bus", bus_app) #create dir try: os.makedirs(os.path.join(APP_DIR, 'static/xls')) except: pass
def page(project, page='index'): # 设定模版目录 TEMPLATE_PATH.append('./projects/%s/pages/' % project) context = { 'url': request.url, 'req': request.params } return jinja2_template(page, **context)
def init_application(dbconf=None,consconf=None,secret=None): log.startLogging(sys.stdout) log.msg("start init application...") base.update_secret(secret) utils.update_secret(secret) TEMPLATE_PATH.append("./admin/views/") ''' install plugins''' log.msg("init plugins..") engine,metadata = models.get_engine(dbconf) sqla_pg = sqla_plugin.Plugin(engine,metadata,keyword='db',create=False,commit=False,use_kwargs=False) session = sqla_pg.new_session() _sys_param_value = functools.partial(get_param_value,session) _get_product_name = functools.partial(get_product_name,session) log.msg("init template context...") MakoTemplate.defaults.update(**dict( get_cookie = get_cookie, fen2yuan = utils.fen2yuan, fmt_second = utils.fmt_second, currdate = utils.get_currdate, request = request, sys_param_value = _sys_param_value, get_product_name = _get_product_name, system_name = _sys_param_value("1_system_name"), radaddr = _sys_param_value('3_radiusd_address'), adminport = _sys_param_value('4_radiusd_admin_port'), permit = permit, all_menus = permit.build_menus(order_cats=[u"系统管理",u"营业管理",u"运维管理"]) )) # connect radiusd websocket admin port log.msg("init websocket client...") wsparam = (MakoTemplate.defaults['radaddr'],MakoTemplate.defaults['adminport'],) reactor.callLater(3, websock.connect,*wsparam) log.msg("init tasks...") reactor.callLater(5, tasks.start_online_stat_job, sqla_pg.new_session) log.msg("init operator rules...") for _super in session.query(models.SlcOperator.operator_name).filter_by(operator_type=0): permit.bind_super(_super[0]) log.msg("install plugins...") mainapp.install(sqla_pg) ops_app.install(sqla_pg) bus_app.install(sqla_pg) card_app.install(sqla_pg) mainapp.mount("/ops",ops_app) mainapp.mount("/bus",bus_app) mainapp.mount("/card",card_app) #create dir try:os.makedirs(os.path.join(APP_DIR,'static/xls')) except:pass
def run(): """ start the xAAL stack & launch the HTTP stuff""" # add the default template directory to the bottle search path root = os.path.join(HOME, 'templates') TEMPLATE_PATH.append(root) xaal_core.setup() # debug disable template cache & enable error reporting debug(True) bottle_app = default_app() app = sio.setup(bottle_app) server = WSGIServer(("", 9090), app, handler_class=WebSocketHandler) server.serve_forever()
def setup_app(): root = os.path.dirname(os.path.abspath(__file__)) session_opts = { 'session.type': 'file', 'session.cookie_expires': 3600 * 10, 'session.data_dir': os.path.join(root, 'data/'), 'session.auto': True } app = Bottle() app = setup_routing(app) TEMPLATE_PATH.append(os.path.join(root, 'templates/')) TEMPLATE_PATH.remove('./views/') app = SessionMiddleware(app, session_opts) return app
def page(project, page): # 设定模版目录 TEMPLATE_PATH.append('./projects/%s/pages/' % project) TEMPLATE_PATH.append('./projects/%s/layouts/' % project) site = 'http://%s' % request.environ.get('HTTP_HOST') context = { 'project': project, 'page': page, 'site': site, 'url': request.url, 'req': request.params, 'base': '/%s/' % project, 'static': '%s/%s/%s/' % (site, ASSET_NAME, project) } return jinja2_template(page, **context)
def getimage(app): """Get image file.""" # append source directory to TEMPLATE_PATH so template is found srcdir = os.path.abspath(os.path.dirname(__file__)) TEMPLATE_PATH.append(srcdir) staticbase = '_static' buildpath = os.path.join(app.outdir, staticbase) try: os.makedirs(buildpath) except OSError: if not os.path.isdir(buildpath): raise if app.config.sphinxmark_image == 'default': imagefile = 'watermark-draft.png' imagepath = os.path.join(srcdir, imagefile) copy(imagepath, buildpath) LOG.debug('[sphinxmark] Using default image: ' + imagefile) elif app.config.sphinxmark_image == 'text': imagefile = createimage(app, srcdir, buildpath) LOG.debug('[sphinxmark] Image: ' + imagefile) else: imagefile = app.config.sphinxmark_image if app.config.html_static_path: staticpath = app.config.html_static_path[0] else: staticpath = '_static' LOG.debug('[sphinxmark] static path: ' + staticpath) imagepath = os.path.join(app.confdir, staticpath, imagefile) LOG.debug('[sphinxmark] Imagepath: ' + imagepath) try: copy(imagepath, buildpath) except Exception: message = ("Cannot find '%s'. Put watermark images in the " "'_static' directory or specify the location using " "'html_static_path'." % imagefile) LOG.warning(message) LOG.warning('Failed to add watermark.') return return(buildpath, imagefile)
def getimage(app): """Get image file.""" # append source directory to TEMPLATE_PATH so template is found srcdir = os.path.abspath(os.path.dirname(__file__)) TEMPLATE_PATH.append(srcdir) staticbase = '_static' buildpath = os.path.join(app.outdir, staticbase) try: os.makedirs(buildpath) except OSError: if not os.path.isdir(buildpath): raise if app.config.sphinxmark_image == 'default': imagefile = 'watermark-draft.png' imagepath = os.path.join(srcdir, imagefile) copy(imagepath, buildpath) app.debug('[sphinxmark] Using default image: ' + imagefile) elif app.config.sphinxmark_image == 'text': imagefile = createimage(app, srcdir, buildpath) app.debug('[sphinxmark] Image: ' + imagefile) else: imagefile = app.config.sphinxmark_image if app.config.html_static_path: staticpath = app.config.html_static_path[0] else: staticpath = '_static' app.debug('[sphinxmark] static path: ' + staticpath) imagepath = os.path.join(app.confdir, staticpath, imagefile) app.debug('[sphinxmark] Imagepath: ' + imagepath) try: copy(imagepath, buildpath) except: message = ("Cannot find '" + imagefile + "'. Put watermark " + "images in the '_static' directory or " + "specify the location using 'html_static_path'.") app.warn(message) app.warn('Failed to add watermark.') return return (buildpath, imagefile)
def __init__(self, args=None): # Init args self.args = args # Init stats # Will be updated within Bottle route self.stats = None # Init Bottle self._app = Bottle() # Enable CORS (issue #479) self._app.install(EnableCors()) # Define routes self._route() # Update the template path (glances/outputs/bottle) TEMPLATE_PATH.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'bottle')) # Path where the statics files are stored self.STATIC_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static')
def __init__(self, args=None): # Init args self.args = args # Init stats # Will be updated within Bottle route self.stats = None # Init Bottle self._app = Bottle() self._route() # Update the template path (glances/outputs/bottle) TEMPLATE_PATH.append( os.path.join(os.path.dirname(os.path.realpath(__file__)), 'bottle')) # Path where the statics files are stored self.STATIC_PATH = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'static') # Define the style (CSS) list (hash table) for stats self.__style_list = { 'DEFAULT': '', 'UNDERLINE': 'underline', 'BOLD': 'bold', 'SORT': 'sort', 'OK': 'ok', 'FILTER': 'filter', 'TITLE': 'title', 'CAREFUL': 'careful', 'WARNING': 'warning', 'CRITICAL': 'critical', 'OK_LOG': 'ok_log', 'CAREFUL_LOG': 'careful_log', 'WARNING_LOG': 'warning_log', 'CRITICAL_LOG': 'critical_log', 'NICE': 'nice', 'STATUS': 'status', 'PROCESS': '' }
def runWebServer(host, port, quiet): """ Install the logger and run the webserver """ # add a logger wrapper for bottle (in order to log its activity) # See http://stackoverflow.com/questions/31080214/python-bottle-always-logs-to-console-no-logging-to-file def log_to_logger(fn): """ Wrap a Bottle request so that a log line is emitted after it's handled.""" @wraps(fn) def _log_to_logger(*_args, **_kwargs): actual_response = fn(*_args, **_kwargs) weblogger.info('%s %s %s %s' % (request.remote_addr, request.method, request.url, response.status)) return actual_response return _log_to_logger # update the template paths so that in priority, # it first looks in <gameName>/server/templates/ and then in CGS/server/templates TEMPLATE_PATH.append('games/' + Game.getTheGameName() + '/server/templates/') TEMPLATE_PATH.reverse() # add the base url to all the templates #Jinja2Template.defaults['base_url'] = 'http://%s:%s/' % (host, port) Jinja2Template.defaults['base_url'] = '/' # add the game name to all the templates (for page title) Jinja2Template.defaults['GameName'] = Game.getTheGameName() # Start the web server install(log_to_logger) weblogger.message('Run the web server on port %d...', port) default_app( ).catchall = True # all the exceptions/errors are catched, and re-routed to error500 run(host=host, port=port, quiet=quiet, server='gevent', handler_class=WebSocketHandler)
def __init__(self, args=None): # Init args self.args = args # Init stats # Will be updated within Bottle route self.stats = None # Init Bottle self._app = Bottle() self._route() # Update the template path (glances/outputs/bottle) TEMPLATE_PATH.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'bottle')) # Path where the statics files are stored self.STATIC_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static') # Define the style (CSS) list (hash table) for stats self.__style_list = { 'DEFAULT': '', 'UNDERLINE': 'underline', 'BOLD': 'bold', 'SORT': 'sort', 'OK': 'ok', 'FILTER': 'filter', 'TITLE': 'title', 'CAREFUL': 'careful', 'WARNING': 'warning', 'CRITICAL': 'critical', 'OK_LOG': 'ok_log', 'CAREFUL_LOG': 'careful_log', 'WARNING_LOG': 'warning_log', 'CRITICAL_LOG': 'critical_log', 'NICE': 'nice', 'STATUS': 'status', 'PROCESS': '' }
def __init__(self, args=None): # Init args self.args = args # Init stats # Will be updated within Bottle route self.stats = None # Init Bottle self._app = Bottle() # Enable CORS (issue #479) self._app.install(EnableCors()) # Define routes self._route() # Update the template path (glances/outputs/bottle) TEMPLATE_PATH.append( os.path.join(os.path.dirname(os.path.realpath(__file__)), 'bottle')) # Path where the statics files are stored self.STATIC_PATH = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'static')
def shift_local(): import os from bottle import TEMPLATE_PATH, default_app ON_OPENSHIFT = False if os.environ.has_key('OPENSHIFT_REPO_DIR'): ON_OPENSHIFT = True if ON_OPENSHIFT: TEMPLATE_PATH.append(os.path.join(os.environ['OPENSHIFT_HOMEDIR'], 'runtime/repo/wsgi/views/')) application=default_app() else: import commands from bottle import run print "AdNail - Interfaces disponibles: " print commands.getoutput("/sbin/ifconfig | egrep -o '^[a-z].......'") intfz = raw_input('Introduce la interfaz a utilizar: ') comand = "/sbin/ifconfig "+intfz+" | egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | egrep -v '*(0|255)$'" iphost = commands.getoutput(comand) print "La IP del Servidor es: ", iphost run(host=iphost, port=8080, debug=True)
app = SessionMiddleware(btl.app(), session_opts) Auth.config(get_role_from_db=ut.get_role) # decorators for access controll req_admin = Auth(appUrl, role='admin', message='Only admin users can access this page.') req_login = Auth(appUrl) # index.pyが設置されているディレクトリの絶対パスを取得 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_DIR = os.path.join(BASE_DIR, 'static') # テンプレートファイルを設置するディレクトリのパスを指定 TEMPLATE_PATH.append(BASE_DIR + "/views") @error(404) def error404(error): return 'Nothing here, sorry' @btl.route('/static/css/<filename:path>') def static_css(filename): return static_file(filename, root=STATIC_DIR + "/css") @btl.get(appUrl + "/login") @btl.view(template('login', appUrl=appUrl)) def login_form():
import waldo.sequences.retrieve import waldo.nog.retrieve from waldo.translations.services import translate from waldo.translations.models import namespace_fullname from waldo.go import id_to_term import waldo.goslim import waldo.backend import json from os import path app = Bottle() route = app.route SimpleTemplate.defaults["get_url"] = app.get_url basedir = path.abspath(path.dirname(__file__)) TEMPLATE_PATH.append(path.join(basedir, 'views')) session = waldo.backend.create_session() PREDICTIONS_ENABLED = False route('/', name='home', callback=lambda: template('index')) route('/help', name='help', callback=lambda:template('static/help')) route('/about', name='about', callback=lambda:template('static/about')) route('/contact-us', name='contact-us', callback=lambda:template('static/contact-us')) route('/media/<filename:path>', callback=lambda **f: static_file(f['filename'], root=path.join(basedir,'media'))) @route('/translate', name='translate', method=('GET','POST')) def translate_identifiers():
def load_plugins(self, app, plugins_dir): # pylint: disable=too-many-locals, too-many-nested-blocks, undefined-loop-variable """ Load plugins from the provided directory If the plugin has - 'pages', declare routes for the pages - 'widgets', declare widgets in the main widgets list Register the plugin 'views' directory in the Bottle views If the plugin has a 'load_config' function, call it """ logger.info("load plugins from: %s", plugins_dir) # Get list of sub directories plugin_names = [ fname for fname in os.listdir(plugins_dir) if os.path.isdir(os.path.join(plugins_dir, fname)) ] # Try to import all found plugins i = 0 for plugin_name in plugin_names: logger.info("trying to load plugin '%s' ...", plugin_name) try: # Import the plugin in the package namespace plugin = import_module( '.%s.%s.%s' % (plugins_dir.rsplit('/')[-1], plugin_name, plugin_name), __package__) # Plugin defined routes ... if hasattr(plugin, 'pages'): for (f, entry) in plugin.pages.items(): logger.debug("page entry: %s", entry) # IMPORTANT: apply the view before the route! page_view = entry.get('view', None) if page_view: f = view(page_view)(f) page_route = entry.get('route', None) if not page_route: page_route = entry.get('routes', None) page_name = entry.get('name', None) # Maybe there is no route to link, so pass if not page_route: continue methods = entry.get('method', 'GET') # Routes are an array of tuples [(route, name), ...] route_url = '' if not isinstance(page_route, list): page_route = [(page_route, page_name)] for route_url, name in page_route: f = app.route( route_url, callback=f, method=methods, name=name, search_engine=entry.get( 'search_engine', False), search_prefix=entry.get('search_prefix', ''), search_filters=entry.get('search_filters', {})) # Plugin is dedicated to a backend endpoint... if hasattr(plugin, 'backend_endpoint'): if route_url == ('/%ss_list' % plugin.backend_endpoint): self.lists['%ss_list' % plugin.backend_endpoint] = { 'id': plugin.backend_endpoint, 'base_uri': route_url, 'function': f } logger.info("Found list '%s' for %s", route_url, plugin.backend_endpoint) # It's a valid widget entry if it got all data, and at least one route if 'widgets' in entry: for widget in entry.get('widgets'): if 'id' not in widget or 'for' not in widget: continue if 'name' not in widget or 'description' not in widget: continue if 'template' not in widget or not page_route: continue for place in widget['for']: if place not in self.widgets: self.widgets[place] = [] self.widgets[place].append({ 'id': widget['id'], 'name': widget['name'], 'description': widget['description'], 'template': widget['template'], 'icon': widget.get('icon', 'leaf'), 'read_only': widget.get('read_only', False), 'options': widget.get('options', None), 'picture': os.path.join( os.path.join( '/static/plugins/', plugin_name), widget.get('picture', '')), 'base_uri': route_url, 'function': f }) logger.info("Found widget '%s' for %s", widget['id'], place) # It's a valid widget entry if it got all data, and at least one route if 'tables' in entry: for table in entry.get('tables'): if 'id' not in table or 'for' not in table: continue if 'name' not in table or 'description' not in table: continue if 'template' not in table or not page_route: continue for place in table['for']: if place not in self.tables: self.tables[place] = [] self.tables[place].append({ 'id': table['id'], 'name': table['name'], 'description': table['description'], 'template': table['template'], 'icon': table.get('icon', 'leaf'), 'base_uri': page_route, 'function': f, 'actions': table.get('actions', {}) }) logger.info("Found table '%s' for %s", table['id'], place) # Add the views sub-directory of the plugin in the Bottle templates path dir_views = os.path.join( os.path.join(plugins_dir, plugin_name), 'views') if os.path.isdir(dir_views): TEMPLATE_PATH.append( os.path.join(os.path.join(plugins_dir, plugin_name), 'views')) logger.debug( "register views directory '%s'", os.path.join(os.path.join(plugins_dir, plugin_name), 'views')) # Self register in the plugin so the pages can get my data plugin.webui = self # Load/set plugin configuration f = getattr(plugin, 'load_config', None) if f and callable(f): logger.info( "plugin '%s' needs to load its configuration. Configuring...", plugin_name) cfg_files = [ '/usr/local/etc/%s/plugin_%s.cfg' % (self.app_config['name'].lower(), plugin_name), '/etc/%s/plugin_%s.cfg' % (self.app_config['name'].lower(), plugin_name), '~/%s/plugin_%s.cfg' % (self.app_config['name'].lower(), plugin_name), os.path.join(os.path.join(plugins_dir, plugin_name), 'settings.cfg') ] config = f(app, cfg_files) if config: logger.info("plugin '%s' configured.", plugin_name) else: # pragma: no cover - if any ... logger.warning("plugin '%s' configuration failed.", plugin_name) i += 1 self.plugins.append({'name': plugin_name, 'module': plugin}) logger.info("registered plugin '%s'", plugin_name) except Exception as e: # pragma: no cover - simple security ... logger.error("loading plugin %s, exception: %s", plugin_name, str(e)) logger.error("traceback: %s", traceback.format_exc()) logger.info("loaded %d plugins from: %s", i, plugins_dir) # exit() return i
from logging import basicConfig, getLogger, DEBUG from os import path, environ as env from pprint import pformat hostname: str = env.get("HOSTNAME", "localhost") port_number: int = int(env.get("PORT", 18000)) basicConfig(format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y/%m/%d %H:%M:%S', level=DEBUG) logger = getLogger(__name__) logger.debug("hostname={0}, port_number={1}".format(hostname, port_number)) #logger.debug(pformat(env)); TEMPLATE_PATH.append("/views") BASE_DIR = path.dirname(path.abspath(__file__)) webpack_dev_server = env.get("WEBPACK_DEV_SERVER", "0") front_end_url = "http://*****:*****@root_app.route("/") def index(): return template('index', frontEndUrl=front_end_url) @root_app.route('/js/<filename>') def js_dir(filename):
from __future__ import absolute_import, unicode_literals import os from bottle import TEMPLATE_PATH from .users import UsersModule TEMPLATE_PATH.append(os.path.join(os.path.dirname(__file__), 'templates')) # necessary to set a 'module' var to detect this specific module # on irc.client.py (see def load_module) module = UsersModule() from . import views
import os, json, datetime, random, hmac, base64, dbm, uuid from bottle import Bottle, request, HTTPResponse, jinja2_template as template, TEMPLATE_PATH, abort from urllib.parse import parse_qs, urlencode import settings BASEDIR = os.path.dirname(__file__) TEMPLATE_PATH.append(BASEDIR) AX_DATA = { 'http://axschema.org/contact/email': '{email}', 'http://axschema.org/namePerson': '{firstName} {lastName}', 'http://axschema.org/namePerson/first': '{firstName}', 'http://axschema.org/namePerson/last': '{lastName}' } AX_DESCRIPTION = { 'http://axschema.org/contact/email': 'E-mail', 'http://axschema.org/namePerson': 'Full name', 'http://axschema.org/namePerson/first': 'First name', 'http://axschema.org/namePerson/last': 'Last name', 'http://axschema.org/namePerson/prefix': 'Name prefix', 'http://axschema.org/namePerson/middle': 'Middle name', 'http://axschema.org/namePerson/suffix': 'Name suffix', 'http://axschema.org/namePerson/friendly': 'Username', 'http://axschema.org/company/name': 'Company name', 'http://axschema.org/company/title': 'Job title', } SREG_DATA = { 'email': '{email}', 'fullname': '{firstName} {lastName}', 'nickname': '{nickname}', 'dob': '2001-01-01', 'gender': 'M',
return static_file(path, root="./videos", mimetype="video/webm") @route("/favicon.png") def callback(): repo_dir = os.environ.get("OPENSHIFT_REPO_DIR") if (repo_dir): return static_file("favicon.png", root=os.path.join(repo_dir, "static")) else: return static_file("favicon.png", root="./static") @route("/robots.txt") def callback(): repo_dir = os.environ.get("OPENSHIFT_REPO_DIR") if (repo_dir): return static_file("robots.txt", root=os.path.join(repo_dir, "static")) else: return static_file("robots.txt", root="./static") # # Below for testing only # if __name__ == '__main__': from bottle import run, TEMPLATE_PATH TEMPLATE_PATH.append("./templates/") run(host="localhost", port=8051, debug=True) else: from bottle import TEMPLATE_PATH TEMPLATE_PATH.append(os.path.join(os.environ.get("OPENSHIFT_REPO_DIR"), "templates/")) application = default_app()
from pathlib import Path from bottle import route, TEMPLATE_PATH, view, abort from .utils import normalize from .. import settings from ..github_storage.assets import get_assets TEMPLATE_PATH.append(Path(__file__) / ".." / "views") @route("/") @view("index.tpl") def index(): return {'packages': list(map(normalize, settings.PACKAGES))} @route("/<package_name>/") @view("package.tpl") def package(package_name): try: repo_name = settings.PACKAGES[package_name] except KeyError: abort(404) assets = dict(get_assets(repo_name)) return {"assets": assets, 'package_name': package_name} def package_redirect(): # todo
#!/usr/bin/python from bottle import Bottle, TEMPLATE_PATH app = Bottle() TEMPLATE_PATH.append("./project/views/") TEMPLATE_PATH.remove("./views/") from project.controllers import *
from bottle import route, default_app, run, jinja2_template as template import jinja2 @route('/name/<name>') def nameindex(name='Stranger'): return '<strong>Hello, %s!</strong>' % name @route('/') def index(): return '<strong>Hello World!</strong>' @route('/detect') def detect(): return template('detect.tmpl') # This must be added in order to do correct path lookups for the views import os from bottle import TEMPLATE_PATH # Don't try to run this while we're testing locally. if __name__ != '__main__': TEMPLATE_PATH.append(os.path.join(os.environ['OPENSHIFT_HOMEDIR'], 'app-root/runtime/repo/wsgi/views/')) application=default_app() # For local debugging purposes. # After starting server, it will automatically reload when files are changed. if __name__ == '__main__': run(host='localhost', port=8080, reloader=True)
default_app, ) from config import Config from jinjaSetup import jinjaSetup from cork import Cork from beaker.middleware import SessionMiddleware ### CONFIG ### global config config = Config() # get logger logger = logging.getLogger(__name__) # bottle setup TEMPLATE_PATH.append(config["viewDir"]) logger.debug("added view dir") # add view extension (jinja 2 files) BaseTemplate.extensions.append("jinja") logger.debug("added jinja file extention") # adde custom jinja functions/filters jinjaSetup() # cork setup aaa = Cork(config["corkConfigDir"]) ### CONTROLLERS ###
# -*- coding: utf-8 -*- from bottle import route, run, request, auth_basic import hashlib import base64 from bottle import TEMPLATE_PATH, jinja2_template as template import scraping import view import os from bottle import static_file #このスクリプトがあるフォルダの絶対パス ROOT_PATH = os.path.dirname(os.path.abspath(__file__)) #templateパスの追加 TEMPLATE_PATH.append(ROOT_PATH + "../views") @route('/js/<filename>') def js_static(filename): return static_file(filename, root='./static/js') @route('/img/<filename>') def img_static(filename): return static_file(filename, root='./static/img') @route('/fonts/<filename>') def fonts_static(filename): return static_file(filename, root='./static/fonts')
session['edition_mode'] = (required_state == 'on') BaseTemplate.defaults['edition_mode'] = session['edition_mode'] logger.debug("edition_mode, session: %s", session['edition_mode']) if session['edition_mode']: user_message = _('Edition mode enabled') else: user_message = _('Edition mode disabled') response.status = 200 response.content_type = 'application/json' return json.dumps({'edition_mode': session['edition_mode'], 'message': user_message}) # Bottle templates path TEMPLATE_PATH.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'views')) # Make Bottle raise the inner exceptions when WebUI is in test mode # This makes it easier to debug if os.environ.get('ALIGNAK_WEBUI_TEST', False): app.catchall = False # ----- # Extend default WSGI application with a session middleware # ----- session_type = app.config.get('session.type', 'file') if os.environ.get('ALIGNAK_WEBUI_SESSION_TYPE'): session_type = os.environ.get('ALIGNAK_WEBUI_SESSION_TYPE') print("Session type from environment: %s" % session_type) session_data = app.config.get('session.session_data',
# Static routes: css, js, images, ... @get('/<filename:re:.*\.js>') def javascripts(filename): return static_file(filename, root=os.environ['OPENSHIFT_REPO_DIR']+'/wsgi/static/js') @get('/<filename:re:.*\.css>') def stylesheets(filename): return static_file(filename, root=os.environ['OPENSHIFT_REPO_DIR']+'/wsgi/static/css') @get('/<filename:re:.*\.(jpg|png|gif|ico)>') def images(filename): return static_file(filename, root=os.environ['OPENSHIFT_REPO_DIR']+'/wsgi/static/img') @get('/<filename:re:.*\.(eot|ttf|woff|svg)>') def fonts(filename): return static_file(filename, root=os.environ['OPENSHIFT_REPO_DIR']+'/wsgi/static/fonts') @get('/<filename:re:.*\.(doc|pdf)>') def fonts(filename): return static_file(filename, root=os.environ['OPENSHIFT_REPO_DIR']+'/wsgi/static/resources') # This must be added in order to do correct path lookups for the views import os from bottle import TEMPLATE_PATH TEMPLATE_PATH.append(os.path.join(os.environ['OPENSHIFT_REPO_DIR'], 'wsgi/views/')) application=default_app()
template, ) from access_modules import ( chromium, monitor, soccer_table, pic_of_the_day, camera, solar, cfg, pushover, ) current_dir = Path(__file__).resolve().parent # bottle initialization TEMPLATE_PATH.append(Path(current_dir, 'web/views')) # decorator to control monitor def monitor_handling(func): def wrapper(*args, **kwargs): status = monitor.status() if status is monitor.Status.OFF: monitor.switch_on() else: monitor.reset_timer() return func(*args, **kwargs) return wrapper
import bottle from bottle import TEMPLATE_PATH, redirect, request, route, run, jinja2_view, jinja2_template as template TEMPLATE_PATH.append('./templates') @route('/images/<filepath:path>') def server_static(filepath): return bottle.static_file(filepath, root='images') @bottle.route('/styles/<filepath:path>') def server_static(filepath): return bottle.static_file(filepath, root='styles') @bottle.route('/scripts/<filepath:path>') def server_static(filepath): return bottle.static_file(filepath, root='scripts') @route('/') @jinja2_view('index.html') def index(): return {'title': 'TheRedSunflowers'} @route('/courses_intro') @jinja2_view('courses_intro.html') def courses_intro(): return {'title': 'TheRedSunflowers'}
def start(host, port): log.debug("starting on {h}:{p}".format(h=host, p=port)) TEMPLATE_PATH.append( os.path.join(os.path.dirname(os.path.abspath(__file__)), "views")) run(host=host, port=port, debug=False, reloader=False)
console.setLevel(lvl_config_logger) formatter = logging.Formatter(LOGFORMAT_STDOUT[lvl_config_logger]) console.setFormatter(formatter) rootlogger.addHandler(console) logger = logging.getLogger('sbnredirect.app') # global GITHUB = 'http://github.com/CristianCantoro/SBNtoolkit' WIKIPEDIA = 'http://{lang}.wikipedia.org/wiki/{page}' WIKIDATA = 'http://www.wikidata.org/wiki/{item}' TEMPLATE_PATH.append(os.path.join('app', 'views')) SBNtoolkit = Bottle() @SBNtoolkit.get('/') def get_index(): return static_file('index.html', root='app/static/') @SBNtoolkit.post('/') def post_index(): code = request.forms.get('code') link_info = retrieve_link('it', 'sbn', code) or \ retrieve_link('data', 'sbn', code)
# -*- coding: utf-8 -*- from bottle import route, default_app, request, response, template, TEMPLATE_PATH import os, sqlite3 TEMPLATE_PATH.append(os.path.join(os.environ['OPENSHIFT_GEAR_DIR'], 'runtime/repo/wsgi/views/')) c = sqlite3.connect(os.path.join(os.getenv('OPENSHIFT_DATA_DIR'), 'tnd.db')) @route('/info') def info(): station_name = request.query.sn or None if station_name: tnd = c.execute('SELECT t.time, d.division FROM tnd AS t INNER JOIN division AS d ON t.division = d.id WHERE t.station=?', (station_name,)).fetchone() if tnd: return dict(zip(('t', 'd'), tnd)) else: return {} @route('/manifest.webapp') def manifest(): response.set_header('Content-Type', 'application/x-web-app-manifest+json') return template('manifest') @route('/') def index(): return template('index') application=default_app()
from __future__ import absolute_import from bottle import error, post, request, response, route, TEMPLATE_PATH, view from application import BASE_DIR from application.lib.logging import Logger from application.service import RSVPService TEMPLATE_PATH.append(BASE_DIR + '/views') @route('/') @view('index') def index(): return {} @post('/lookup') def lookup(): """Lookup user name to ensure they are on the guest list.""" first_name = request.forms.get('first_name') last_name = request.forms.get('last_name') if not first_name or not last_name: Logger.warn('Invalid parameters') response.status = 400 return {'message': 'invalid parameters'} # lookup name in db, return either error or signup uuid guest_uuid = RSVPService.search_by_name(request.forms.get('first_name'), request.forms.get('last_name')) # guest not found if not guest_uuid:
def bundle_page_url(page): host = CONFIG['hostname'] path = 'bundles' if page > 0: url = 'http://{0}/{1}/{2}'.format(host, path, page) else: url = 'http://{0}/{1}'.format(host, path) return url def otc_url(name): url = 'http://bitcoin-otc.com/viewratingdetail.php?nick={0}' return url.format(quote_plus(name)) app = Bottle() TEMPLATE_PATH.append('/home/deedbot/app/deedbundler/deedbundler_web/templates/') BaseTemplate.defaults['date'] = timestamp BaseTemplate.defaults['deed_url'] = deed_url BaseTemplate.defaults['bundle_url'] = bundle_url BaseTemplate.defaults['bundle_page_url'] = bundle_page_url BaseTemplate.defaults['otc_url'] = otc_url @app.get('/') def index(): db = get_db() cursor = db.cursor() pend_sel = 'SELECT b58_hash, otc_name, created_at, title FROM deeds WHERE bundled_at = 0 ORDER BY created_at DESC' cursor.execute(pend_sel) pending = cursor.fetchall()
# coding: UTF-8 import fcntl import time from bottle import get from bottle import redirect from bottle import request from bottle import route from bottle import run from bottle import static_file from bottle import template from bottle import TEMPLATE_PATH mainURL = 'http://www.j-wave.co.jp/iwf2017/specialtalklive/' TEMPLATE_PATH.append("./page") @route('/data/<filename>') def static_file_crossdomain(filename): response = static_file(filename, root="./data") response.set_header('Access-Control-allow-Origin', '*') return response # @get('/page/') # def page(): # return template('index',) @get('/') def red():
from bottle import Bottle, route, run, post, get, request, response, redirect, error, abort, static_file, TEMPLATE_PATH from bottle import jinja2_template as template, jinja2_view import filedict import json import time import os import pprint from functools import partial from datetime import datetime, date, time as dtime from random import choice import string import re import argparse TEMPLATE_PATH.append(os.path.join(os.path.split(os.path.realpath(__file__))[0],'views')) DEFAULT_DB_FILE = os.path.join(os.path.split(os.path.realpath(__file__))[0],"data/events.dict.sqlite") LATEST = dict() EVENTS = dict() NONAME = '_-_noname_-_' filter_dict = {} view = partial(jinja2_view, template_settings={'filters': filter_dict}) def filter(func): """Decorator to add the function to filter_dict""" filter_dict[func.__name__] = func return func @filter
from notmuch import Database, Query from bottle import Bottle, request, response, abort, redirect, view, TEMPLATE_PATH TEMPLATE_PATH.append('views') app = Bottle() db = Database() @app.route('/<identifier>/') def slash(identifier): redirect('/' + identifier) @app.get('/searches/:querystr') @view('flat') def search(querystr): query = Query(db, querystr).search_threads() threads = [('/threads/' + t.get_thread_id(), t.get_subject()) \ for t in query] return {'heading': 'Results for "%s"' % querystr, 'list': threads} def _get_thread(thread_id): querystr = 'thread:' + thread_id thread = next(iter(Query(db, querystr).search_threads())) return thread.get_subject() @app.get('/threads/:thread_id') @view('flat') def thread(thread_id):
import logging import json from bottle import route, default_app, run, response, abort, post, request api_version = "5" #API version, please increase by one every time you push number_storage = {} #storage array for hashes @route('/') def index(): return "HSSPKA API Version: " + api_version @route('/numbers', method='GET') def get_numbers(): number_storage['6274865966'] = 'PUBLICKEY' return json.dumps(number_storage.keys()) # This must be added in order to do correct path lookups for the views import os from bottle import TEMPLATE_PATH TEMPLATE_PATH.append( os.path.join(os.environ['OPENSHIFT_HOMEDIR'], 'runtime/repo/wsgi/views/')) application = default_app()
# -*- coding:utf-8 -*- # じゃんけんプログラムの改良 import os import random import bottle import jinja2 from bottle import get, post, request, route, run from bottle import TEMPLATE_PATH, jinja2_template as template # じゃんけんのためのクラスと関数 from functions2 import Hand, show_hands, referee # test.pyが設置されているディレクトリの絶対パスを取得。 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # テンプレートファイルを設置するディレクトリのパスを指定 TEMPLATE_PATH.append(BASE_DIR + "/template") @get('/') def h(): return ''' <form action="/rsp" method="post"> 名前を入力してください <input name="name" type="text" /> どの手をだしますか? グー:0、チョキ:1、パー:2 <input name="hand" type="text" /> <input value="決定" type="submit" /> </form> ''' @post('/rsp') def r():
from bottle import TEMPLATE_PATH, route, get, post, jinja2_template as template from models import * from bottle import static_file from config import config from datetime import datetime import random import sqlite3 as lite, xml.etree.ElementTree as et, os import xml.dom.minidom as minidom TEMPLATE_PATH.append("./app/templates") class TreeNode(object): def __init__(self, label=None, id=None, children=[]): self.label = label self.id = id self.children = children def __eq__(self, other): if not isinstance(other, TreeNode): return False if self.label != other.label: return False return True def __hash__(self): return self.label def __contains__(self, key): return key == self.label def append(self, node):
import json, os from bottle import default_app, route, template, TEMPLATE_PATH, static_file, run if __name__ == "__main__": TEMPLATE_PATH.append("mysite/") mysite = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @route('/') def index(): accountdb = f'{mysite}/accountdb.json' accounts = {} if os.path.exists(accountdb): with open(accountdb) as json_file: accounts = json.load(json_file) return template(f'index.tpl', {"accounts": accounts}) @route('/data/<filename>') def server_static(filename): return static_file(filename, root=f'{mysite}/data') @route('/css/<filename>') def server_static(filename): return static_file(filename, root=f'{mysite}/css') @route('/logs/<filename>.log') def server_static(filename): return static_file('{}.log'.format(filename),
#!/usr/bin/env python3 import os from unidecode import unidecode from lxml.html.clean import clean_html from notmuch import Database, Query from bottle import Bottle, request, response, \ abort, redirect, \ view, TEMPLATE_PATH, \ static_file from .queries import hierarchy, subhierarchy EJNUG_DIR = os.path.split(__file__)[0] TEMPLATE_PATH.append(os.path.join(EJNUG_DIR, 'views')) app = Bottle() @app.route('/') @view('home') def home(): return {} @app.route('/style.css') def css(): return static_file('style.css', root = EJNUG_DIR) @app.get('/!/<querystr:path>/') @view('thread') def search(querystr): db = Database() query = Query(db, querystr)
import os import secrets from bottle import Bottle, view, TEMPLATE_PATH, static_file, \ request, redirect, response, HTTPError from .db import SQLitePlugin from .api import api, check_api_auth application = app = Bottle() # TODO: Could be replaced with importlib.resources TEMPLATE_PATH.append(os.path.join(os.path.dirname(__file__), "views")) STATIC_PATH = os.path.join(os.path.dirname(__file__), "static") SQLITE_PATH = os.path.join(os.path.dirname(__file__), "..", "kdoorweb.sqlite") COOKIE_KEY = b"1234"#secrets.token_bytes(32) def current_user(db): user_id = request.get_cookie("uid", secret=COOKIE_KEY) if not user_id: return return db.get_user(user_id) def login_user(uid): response.set_cookie("uid", uid, secret=COOKIE_KEY) def logout_user():
@get('/history') def history(): gemaversion = request.params.get('gem') url_historial = "http://rubygems.org/api/v1/versions/" rhistorial = requests.get(url_historial + gemaversion + ".json") dochistorial = json.loads(rhistorial.text) return template('history.tpl', dochistorial=dochistorial, gemaversion=gemaversion) @error(404) def error404(error): return template('notfound.tpl') @error(500) def error500(error): return template('error') # This must be added in order to do correct path lookups for the views import os from bottle import TEMPLATE_PATH TEMPLATE_PATH.append( os.path.join(os.environ['OPENSHIFT_REPO_DIR'], 'wsgi/views/')) application = default_app()
import os, sys from bottle import route, run from bottle import request, post from bottle import template, TEMPLATE_PATH, static_file dir_path = os.path.join(os.path.dirname(__file__), '..') sys.path.insert(0, os.path.abspath(dir_path)) # views location views_path = dir_path + '\\app\\views' TEMPLATE_PATH.append(views_path) from app.src.models.request_model import RequestModel from app.src.controllers.main_controller import MainController @route('/') def home(): return template(views_path + '/index.html') @route('/result', method='POST') def result(): requestModel = RequestModel(request.forms) mainController = MainController(requestModel) response = mainController.calc_result() return template(views_path + '/result.html', response=response) @route('/<filename:path>') def static(filename):
__version__ = "0.1" __author__ = ["Danny O'Brien <http://www.spesh.com/danny/> ", "Liz Henry <http://bookmaniac.org/> "] __copyright__ = "Noisebridge" __contributors__ = None __license__ = "GPL v3" from bottle import Bottle, run, request, template, TEMPLATE_PATH from bottle import debug from bottle import HTTPError from bottle import redirect import mimeparse DEBUG = True api_app = Bottle() TEMPLATE_PATH.append(".") import random from datetime import datetime import fcntl import socket import time import re import string def chat_with_gate(message): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) port = 30012 try: s.connect(('minotaur.noise', port))
# -*- coding: utf-8 -*- __version__ = '0.1' from bottle import Bottle, TEMPLATE_PATH app = Bottle() TEMPLATE_PATH.append("./chanelist/views/") from chanelist.controllers import *
from bottle import TEMPLATE_PATH, Bottle, debug, redirect, request from bottle import jinja2_template as template from bottle import run, static_file # ------------------------------------------------- # Webサーバ設定 # ------------------------------------------------- app = Bottle() TEMPLATE_PATH.append("cmd実行してるパスから見た相対パスtemplate") @app.route('/', method=['GET']) def index(): return template('index.html', title='sample_page') run(app=app)
sys.path.append(pro_path) #定义assets路径,即静态资源路径,如css,js,及样式中用到的图片等 assets_path = '/'.join((pro_path, 'assets')) #定义图片路径 images_path = '/'.join((pro_path, 'images')) #定义提供文件下载的路径 download_path = '/'.join((pro_path, 'download')) #定义文件上传存放的路径 upload_path = '/'.join((pro_path, 'upload')) #定义模板路径 TEMPLATE_PATH.append('/'.join((pro_path, 'views'))) #定义日志目录 log_path = ('/'.join((pro_path, 'log'))) #定义日志输出格式 logging.basicConfig( level=logging.ERROR, format= '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filename="%s/error_log" % log_path, filemode='a') def writeDb(sql, db_data=()):
# -*- coding: utf-8 -*- # @author: Darren Vong from sys import argv from bottle import request, template, run, route, post, static_file, TEMPLATE_PATH,\ response import page_data_extractor TEMPLATE_PATH.append('../client') @route('/') def index(): return template("index") @route('/data') def get_data(): response.set_header("Access-Control-Allow-Origin", "*") page_title = request.query.get("page_title") print page_title return page_data_extractor.get_page_data(page_title) @route('/<path:path>') def get_resources(path): return static_file(path, root="../client") if __name__ == '__main__': run(host='0.0.0.0', debug=True, port=argv[1], reloader=True)
import os import pymongo import string from bottle import TEMPLATE_PATH, route, jinja2_template as template, request, response from models import * from bottle import static_file, request import urllib import urllib2 import sys import json import datetime TEMPLATE_PATH.append('./templates') sys.path.append('./backend/configs') sys.path.append('./backend') import apilib APP_CONFIG = {} APP_CONFIG["DBNAME"] = "gigzibit" APP_CONFIG["LOGTABLE"] = "log" APP_CONFIG["THUMBNAIL_COLOR"] = "#FEFEFE" APP_CONFIG["HEADING_COLOR"] = "#EBE0D6" APP_CONFIG["NAV_COLOR"] = "#FDFDFA" @route('/bootstrap/<dir1>/<dir2>/:filename') def serve_static(dir1, dir2, filename): return static_file(dir1 + '/' + dir2 + '/' + filename, root='./bootstrap/docs/') @route('/HTML-KickStart/<dir1>/:filename') def serve_static(dir1, filename): return static_file(dir1 + '/' + filename, root='./HTML-KickStart/')
from bottle import route, request, post, get, run, template, error, response, static_file, TEMPLATE_PATH, default_app, debug import os,sys,fqlquery debug(mode=True) mydir=os.path.dirname(os.path.realpath(__file__)) TEMPLATE_PATH.append(os.path.join(mydir,"template")) @error(404) def kesasar(err): return "Lo kesasar bro, apa yang lo cari tidak ditemukan" @error(500) def rusak(err): return "Kayaknya script lo error deh bro, cek output console" # static file @route('/lib/<filename:path>') def getfile(filename): return static_file(filename,os.path.join(mydir,"lib")) @get('/') def index(): return template("main.html",data=[],katas="Tulis nama") @post('/cari.py') def cari(): kata=request.forms.get("kata") fql = fqlquery.FQL("ISI_TOKEN_DISINI") dat = fql.query("SELECT name,uid FROM user WHERE uid IN (SELECT uid FROM group_member WHERE gid = '376405625706616' LIMIT 0,99999) AND strpos(lower(name),lower('%s'))>0"%kata) ##esponse.set_header('content-type','application/json') return template("main.html",data=dat,katas=kata) application=default_app()