class Params(pp.Params): daemon = pp.Param(None, dtype=str, doc=f"first positional should be daemon", positional=True) command = pp.Param(None, dtype=str, doc=f"one of - start, stop", positional=True) config = pp.Param("/etc/teleremd.config.yaml", dtype=str, doc="teleremd daemon config")
class Params(TeleRemBot.Params): command = pp.Param(None, dtype=str, doc=f"command - one of: {COMMANDS}", positional=True) config = pp.Param("telerem.config.yaml", dtype=str, doc="config yaml file location") systemd = pp.Param(False, dtype=bool, doc=f"installs a systemd service") initd = pp.Param(False, dtype=bool, doc=f"installs an init.d daemon script")
def readparams(): """Read simulation parameters from 'in' file.""" pdict = {} # dictionary containing params fname = os.getcwd() + '/in' f = open(fname, 'r') flines = f.readlines() rerror = False for line in flines: # skip comments (rudimentary method) if '#' in line: continue line = line.split() if line: # note that this interface should handle conversion from # string to e.g. int correctly p = params.Param(line[0], line[1]) if p.value is None: # something went wrong, we should have had an error # msg on stdout rerror = True else: pdict[p.name] = p.value if rerror: return {} return pdict
class CSSLink(Link): ''' A CSS style sheet. ''' media = pm.Param('Media tag', default='all') location = 'head' template = 'tw2.core.templates.csslink'
class Params(pp.Params): bot_name = pp.Param( "TeleRemBash", dtype=str, doc="The Bot Name (used in the OTP provisioning uri only)") api_token = pp.Param(None, dtype=str, doc="Telegram Bot API Token") auth_secret = pp.Param(None, dtype=str, doc="OPT Authenticator Secret (RFC 6238)") scripts_root = pp.Param("scripts", dtype=str, doc="scripts location") scripts_timeout = pp.Param(30, dtype=int, doc="execution timeout in seconds") username = pp.Param(None, dtype=str, doc="Username of the authorized user") user_id = pp.Param(None, dtype=int, doc="User IDs of the authorized user") @staticmethod def resolve_path(path): return path if path.startswith('/') else os.path.join( os.getcwd(), path) def get_scripts_root(self): return self.resolve_path(str(self.scripts_root))
class Params(TeleRemBot.Params): service_name = pp.Param( "teleremd", dtype=str, doc=f"(install only) name of the service/daemon") service_user = pp.Param( "teleremd", dtype=str, doc=f"(install only) user for the service/daemon") pid_file = pp.Param(None, dtype=str, doc=f"pidfile for the daemon") def get_home_dir(self): import pwd home_dir = pwd.getpwnam(self.service_user).pw_dir return home_dir def get_pid_file(self): pid_file = f"/run/{self.service_name}/{self.service_name}.pid" if self.pid_file is None else self.pid_file return pid_file
class _JSFuncCall(JSSource): """ Internal use inline JavaScript function call. Please use tw2.core.js_function(...) externally. """ src = None function = pm.Param('Function name') args = pm.Param('Function arguments', default=None) location = 'bodybottom' # TBD: afterwidget? def __str__(self): if not self.src: self.prepare() return self.src def prepare(self): if not self.src: args = '' if isinstance(self.args, dict): args = encoder.encode(self.args) elif self.args: args = ', '.join(encoder.encode(a) for a in self.args) self.src = '%s(%s)' % (self.function, args) super(_JSFuncCall, self).prepare() def __hash__(self): if self.args: if isinstance(self.args, dict): sargs = encoder.encode(self.args) else: sargs = ', '.join(encoder.encode(a) for a in self.args) else: sargs = None return hash((hasattr(self, 'src') and self.src or '') + (sargs or '')) def __eq__(self, other): return (getattr(self, 'src', None) == getattr(other, 'src', None) and getattr(self, 'args', None) == getattr( other, 'args', None))
class CSSSource(Resource): """ Inline Cascading Style-Sheet code. """ src = pm.Param('CSS code', default=None) location = 'head' template = 'tw2.core.templates.csssource' def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.src) def prepare(self): super(CSSSource, self).prepare() if not self.src: raise ValueError("%r must be provided a 'src' attr" % self) self.src = Markup(self.src)
class JSSource(Resource): """ Inline JavaScript source code. """ src = pm.Param('Source code', default=None) location = 'bodybottom' template = 'tw2.core.templates.jssource' def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.src) def prepare(self): super(JSSource, self).prepare() if not self.src: raise ValueError("%r must be provided a 'src' attr" % self) self.src = Markup(self.src)
class Resource(ResourceBundle): location = pm.Param( 'Location on the page where the resource should be placed.' \ 'This can be one of: head, headbottom, bodytop or bodybottom. '\ 'None means the resource will not be injected, which is still '\ 'useful, e.g. static images.', default=None) id = None def prepare(self): super(Resource, self).prepare() rl = core.request_local() rl_resources = rl.setdefault('resources', []) rl_location = rl['middleware'].config.inject_resources_location if self not in rl_resources: if self.location is '__use_middleware': self.location = rl_location rl_resources.append(self)
class Link(Resource): ''' A link to a file. ''' id = None link = pm.Param( 'Direct web link to file. If this is not specified, it is ' + 'automatically generated, based on :attr:`modname` and ' + ':attr:`filename`.', ) modname = pm.Param( 'Name of Python module that contains the file.', default=None, ) filename = pm.Param( 'Path to file, relative to module base.', default=None, ) no_inject = pm.Param( "Don't inject this link. (Default: False)", default=False, ) whole_dir = pm.Param( "Make the whole directory available. (Default: False)", default=False, ) @classmethod def guess_modname(cls): """ Try to guess my modname. If I wasn't supplied any modname, take a guess by stepping back up the frame stack until I find something not in tw2.core """ try: frame, i = inspect.stack()[0][0], 0 while frame.f_globals['__name__'].startswith('tw2.core'): frame, i = inspect.stack()[i][0], i + 1 return frame.f_globals['__name__'] except Exception: return None @classmethod def post_define(cls): if not cls.no_inject: if getattr(cls, 'filename', None) and \ type(cls.filename) != property: if not cls.modname: cls.modname = cls.guess_modname() md.register_resource(cls.modname or '__anon__', cls.filename, cls.whole_dir) def prepare(self): rl = core.request_local() if not self.no_inject: if not hasattr(self, 'link'): # TBD shouldn't we test for this in __new__ ? if not self.filename: raise pm.ParameterError( "Either 'link' or 'filename' must be specified") resources = rl['middleware'].resources self.link = resources.resource_path(self.modname or '__anon__', self.filename) super(Link, self).prepare() def __hash__(self): return hash( hasattr(self, 'link') and \ self.link or \ ((self.modname or '') + self.filename) ) def __eq__(self, other): return (isinstance(other, Link) and self.link == other.link and self.modname == other.modname and self.filename == other.filename) def __repr__(self): return "%s('%s')" % (self.__class__.__name__, getattr(self, 'link', '%s/%s' % (self.modname, self.filename)))