sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def set_manage_params( self, chunked_input=None, chunked_output=None, gzip=None, websockets=None, source_method=None, rtsp=None, proxy_protocol=None): """Allows enabling various automatic management mechanics. * http://uwsgi.readthedocs.io/en/latest/Changelog-1.9.html#http-router-keepalive-auto-chunking-auto-gzip-and-transparent-websockets :param bool chunked_input: Automatically detect chunked input requests and put the session in raw mode. :param bool chunked_output: Automatically transform output to chunked encoding during HTTP 1.1 keepalive (if needed). :param bool gzip: Automatically gzip content if uWSGI-Encoding header is set to gzip, but content size (Content-Length/Transfer-Encoding) and Content-Encoding are not specified. :param bool websockets: Automatically detect websockets connections and put the session in raw mode. :param bool source_method: Automatically put the session in raw mode for `SOURCE` HTTP method. * http://uwsgi.readthedocs.io/en/latest/Changelog-2.0.5.html#icecast2-protocol-helpers :param bool rtsp: Allow the HTTP router to detect RTSP and chunked requests automatically. :param bool proxy_protocol: Allows the HTTP router to manage PROXY1 protocol requests, such as those made by Haproxy or Amazon Elastic Load Balancer (ELB). """ self._set_aliased('chunked-input', chunked_input, cast=bool) self._set_aliased('auto-chunked', chunked_output, cast=bool) self._set_aliased('auto-gzip', gzip, cast=bool) self._set_aliased('websockets', websockets, cast=bool) self._set_aliased('manage-source', source_method, cast=bool) self._set_aliased('manage-rtsp', rtsp, cast=bool) self._set_aliased('enable-proxy-protocol', proxy_protocol, cast=bool) return self
Allows enabling various automatic management mechanics. * http://uwsgi.readthedocs.io/en/latest/Changelog-1.9.html#http-router-keepalive-auto-chunking-auto-gzip-and-transparent-websockets :param bool chunked_input: Automatically detect chunked input requests and put the session in raw mode. :param bool chunked_output: Automatically transform output to chunked encoding during HTTP 1.1 keepalive (if needed). :param bool gzip: Automatically gzip content if uWSGI-Encoding header is set to gzip, but content size (Content-Length/Transfer-Encoding) and Content-Encoding are not specified. :param bool websockets: Automatically detect websockets connections and put the session in raw mode. :param bool source_method: Automatically put the session in raw mode for `SOURCE` HTTP method. * http://uwsgi.readthedocs.io/en/latest/Changelog-2.0.5.html#icecast2-protocol-helpers :param bool rtsp: Allow the HTTP router to detect RTSP and chunked requests automatically. :param bool proxy_protocol: Allows the HTTP router to manage PROXY1 protocol requests, such as those made by Haproxy or Amazon Elastic Load Balancer (ELB).
entailment
def set_owner_params(self, uid=None, gid=None): """Drop http router privileges to specified user and group. :param str|unicode|int uid: Set uid to the specified username or uid. :param str|unicode|int gid: Set gid to the specified groupname or gid. """ self._set_aliased('uid', uid) self._set_aliased('gid', gid) return self
Drop http router privileges to specified user and group. :param str|unicode|int uid: Set uid to the specified username or uid. :param str|unicode|int gid: Set gid to the specified groupname or gid.
entailment
def set_connections_params(self, harakiri=None, timeout_socket=None, retry_delay=None, retry_max=None): """Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60. :param int retry_delay: Retry connections to dead static nodes after the specified amount of seconds. Default: 30. :param int retry_max: Maximum number of retries/fallbacks to other nodes. Default: 3. """ super(RouterSsl, self).set_connections_params(**filter_locals(locals(), ['retry_max'])) self._set_aliased('max-retries', retry_max) return self
Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60. :param int retry_delay: Retry connections to dead static nodes after the specified amount of seconds. Default: 30. :param int retry_max: Maximum number of retries/fallbacks to other nodes. Default: 3.
entailment
def set_basic_params( self, workers=None, zerg_server=None, fallback_node=None, concurrent_events=None, cheap_mode=None, stats_server=None, quiet=None, buffer_size=None, fallback_nokey=None, subscription_key=None, emperor_command_socket=None): """ :param int workers: Number of worker processes to spawn. :param str|unicode zerg_server: Attach the router to a zerg server. :param str|unicode fallback_node: Fallback to the specified node in case of error. :param int concurrent_events: Set the maximum number of concurrent events router can manage. Default: system dependent. :param bool cheap_mode: Enables cheap mode. When the router is in cheap mode, it will not respond to requests until a node is available. This means that when there are no nodes subscribed, only your local app (if any) will respond. When all of the nodes go down, the router will return in cheap mode. :param str|unicode stats_server: Router stats server address to run at. :param bool quiet: Do not report failed connections to instances. :param int buffer_size: Set internal buffer size in bytes. Default: page size. :param bool fallback_nokey: Move to fallback node even if a subscription key is not found. :param str|unicode subscription_key: Skip uwsgi parsing and directly set a key. :param str|unicode emperor_command_socket: Set the emperor command socket that will receive spawn commands. See `.empire.set_emperor_command_params()`. """ super(RouterFast, self).set_basic_params(**filter_locals(locals(), [ 'fallback_nokey', 'subscription_key', 'emperor_command_socket', ])) self._set_aliased('fallback-on-no-key', fallback_nokey, cast=bool) self._set_aliased('force-key', subscription_key) self._set_aliased('emperor-socket', emperor_command_socket) return self
:param int workers: Number of worker processes to spawn. :param str|unicode zerg_server: Attach the router to a zerg server. :param str|unicode fallback_node: Fallback to the specified node in case of error. :param int concurrent_events: Set the maximum number of concurrent events router can manage. Default: system dependent. :param bool cheap_mode: Enables cheap mode. When the router is in cheap mode, it will not respond to requests until a node is available. This means that when there are no nodes subscribed, only your local app (if any) will respond. When all of the nodes go down, the router will return in cheap mode. :param str|unicode stats_server: Router stats server address to run at. :param bool quiet: Do not report failed connections to instances. :param int buffer_size: Set internal buffer size in bytes. Default: page size. :param bool fallback_nokey: Move to fallback node even if a subscription key is not found. :param str|unicode subscription_key: Skip uwsgi parsing and directly set a key. :param str|unicode emperor_command_socket: Set the emperor command socket that will receive spawn commands. See `.empire.set_emperor_command_params()`.
entailment
def set_resubscription_params(self, addresses=None, bind_to=None): """You can specify a dgram address (udp or unix) on which all of the subscriptions request will be forwarded to (obviously changing the node address to the router one). The system could be useful to build 'federated' setup. * http://uwsgi.readthedocs.io/en/latest/Changelog-2.0.1.html#resubscriptions :param str|unicode|list[str|unicode] addresses: Forward subscriptions to the specified subscription server. :param str|unicode|list[str|unicode] bind_to: Bind to the specified address when re-subscribing. """ self._set_aliased('resubscribe', addresses, multi=True) self._set_aliased('resubscribe-bind', bind_to) return self
You can specify a dgram address (udp or unix) on which all of the subscriptions request will be forwarded to (obviously changing the node address to the router one). The system could be useful to build 'federated' setup. * http://uwsgi.readthedocs.io/en/latest/Changelog-2.0.1.html#resubscriptions :param str|unicode|list[str|unicode] addresses: Forward subscriptions to the specified subscription server. :param str|unicode|list[str|unicode] bind_to: Bind to the specified address when re-subscribing.
entailment
def set_connections_params(self, harakiri=None, timeout_socket=None, retry_delay=None, retry_max=None, defer=None): """Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60. :param int retry_delay: Retry connections to dead static nodes after the specified amount of seconds. Default: 30. :param int retry_max: Maximum number of retries/fallbacks to other nodes. Default: 3 :param int defer: Defer connection delay, seconds. Default: 5. """ super(RouterFast, self).set_connections_params(**filter_locals(locals(), ['retry_max', 'defer'])) self._set_aliased('max-retries', retry_max) self._set_aliased('defer-connect-timeout', defer) return self
Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60. :param int retry_delay: Retry connections to dead static nodes after the specified amount of seconds. Default: 30. :param int retry_max: Maximum number of retries/fallbacks to other nodes. Default: 3 :param int defer: Defer connection delay, seconds. Default: 5.
entailment
def set_postbuffering_params(self, size=None, store_dir=None): """Sets buffering params. Web-proxies like nginx are "buffered", so they wait til the whole request (and its body) has been read, and then it sends it to the backends. :param int size: The size (in bytes) of the request body after which the body will be stored to disk (as a temporary file) instead of memory. :param str|unicode store_dir: Put buffered files to the specified directory. Default: TMPDIR, /tmp/ """ self._set_aliased('post-buffering', size) self._set_aliased('post-buffering-dir', store_dir) return self
Sets buffering params. Web-proxies like nginx are "buffered", so they wait til the whole request (and its body) has been read, and then it sends it to the backends. :param int size: The size (in bytes) of the request body after which the body will be stored to disk (as a temporary file) instead of memory. :param str|unicode store_dir: Put buffered files to the specified directory. Default: TMPDIR, /tmp/
entailment
def set_connections_params( self, harakiri=None, timeout_socket=None, retry_delay=None, retry_max=None, use_xclient=None): """Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60. :param int retry_delay: Retry connections to dead static nodes after the specified amount of seconds. Default: 30. :param int retry_max: Maximum number of retries/fallbacks to other nodes. Default: 3. :param bool use_xclient: Use the xclient protocol to pass the client address. """ super(RouterRaw, self).set_connections_params(**filter_locals(locals(), ['retry_max', 'use_xclient'])) self._set_aliased('max-retries', retry_max) self._set_aliased('xclient', use_xclient) return self
Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60. :param int retry_delay: Retry connections to dead static nodes after the specified amount of seconds. Default: 30. :param int retry_max: Maximum number of retries/fallbacks to other nodes. Default: 3. :param bool use_xclient: Use the xclient protocol to pass the client address.
entailment
def set_connections_params(self, harakiri=None, timeout_socket=None): """Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60. """ self._set_aliased('harakiri', harakiri) self._set_aliased('timeout', timeout_socket) return self
Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60.
entailment
def set_window_params(self, cols=None, rows=None): """Sets pty window params. :param int cols: :param int rows: """ self._set_aliased('cols', cols) self._set_aliased('rows', rows) return self
Sets pty window params. :param int cols: :param int rows:
entailment
def set_basic_params(self, use_credentials=None, stats_server=None): """ :param str|unicode use_credentials: Enable check of SCM_CREDENTIALS for tuntap client/server. :param str|unicode stats_server: Router stats server address to run at. """ self._set_aliased('use-credentials', use_credentials) self._set_aliased('router-stats', stats_server) return self
:param str|unicode use_credentials: Enable check of SCM_CREDENTIALS for tuntap client/server. :param str|unicode stats_server: Router stats server address to run at.
entailment
def register_route(self, src, dst, gateway): """Adds a routing rule to the tuntap router. :param str|unicode src: Source/mask. :param str|unicode dst: Destination/mask. :param str|unicode gateway: Gateway address. """ self._set_aliased('router-route', ' '.join((src, dst, gateway)), multi=True) return self
Adds a routing rule to the tuntap router. :param str|unicode src: Source/mask. :param str|unicode dst: Destination/mask. :param str|unicode gateway: Gateway address.
entailment
def device_add_rule(self, direction, action, src, dst, target=None): """Adds a tuntap device rule. To be used in a vassal. :param str|unicode direction: Direction: * in * out. :param str|unicode action: Action: * allow * deny * route * gateway. :param str|unicode src: Source/mask. :param str|unicode dst: Destination/mask. :param str|unicode target: Depends on action. * Route / Gateway: Accept addr:port """ value = [direction, src, dst, action] if target: value.append(target) self._set_aliased('device-rule', ' '.join(value), multi=True) return self
Adds a tuntap device rule. To be used in a vassal. :param str|unicode direction: Direction: * in * out. :param str|unicode action: Action: * allow * deny * route * gateway. :param str|unicode src: Source/mask. :param str|unicode dst: Destination/mask. :param str|unicode target: Depends on action. * Route / Gateway: Accept addr:port
entailment
def add_firewall_rule(self, direction, action, src=None, dst=None): """Adds a firewall rule to the router. The TunTap router includes a very simple firewall for governing vassal's traffic. The first matching rule stops the chain, if no rule applies, the policy is "allow". :param str|unicode direction: Direction: * in * out :param str|unicode action: Action: * allow * deny :param str|unicode src: Source/mask. :param str|unicode dst: Destination/mask """ value = [action] if src: value.extend((src, dst)) self._set_aliased('router-firewall-%s' % direction.lower(), ' '.join(value), multi=True) return self
Adds a firewall rule to the router. The TunTap router includes a very simple firewall for governing vassal's traffic. The first matching rule stops the chain, if no rule applies, the policy is "allow". :param str|unicode direction: Direction: * in * out :param str|unicode action: Action: * allow * deny :param str|unicode src: Source/mask. :param str|unicode dst: Destination/mask
entailment
def configure_uwsgi(configurator_func): """Allows configuring uWSGI using Configuration objects returned by the given configuration function. .. code-block: python # In configuration module, e.g `uwsgicfg.py` from uwsgiconf.config import configure_uwsgi configure_uwsgi(get_configurations) :param callable configurator_func: Function which return a list on configurations. :rtype: list|None :returns: A list with detected configurations or ``None`` if called from within uWSGI (e.g. when trying to load WSGI application). :raises ConfigurationError: """ from .settings import ENV_CONF_READY, ENV_CONF_ALIAS, CONFIGS_MODULE_ATTR if os.environ.get(ENV_CONF_READY): # This call is from uWSGI trying to load an application. # We prevent unnecessary configuration # for setups where application is located in the same # file as configuration. del os.environ[ENV_CONF_READY] # Drop it support consecutive reconfiguration. return None configurations = configurator_func() registry = OrderedDict() if not isinstance(configurations, (list, tuple)): configurations = [configurations] for conf_candidate in configurations: if not isinstance(conf_candidate, (Section, Configuration)): continue if isinstance(conf_candidate, Section): conf_candidate = conf_candidate.as_configuration() alias = conf_candidate.alias if alias in registry: raise ConfigurationError( "Configuration alias '%s' clashes with another configuration. " "Please change the alias." % alias) registry[alias] = conf_candidate if not registry: raise ConfigurationError( "Callable passed into 'configure_uwsgi' must return 'Section' or 'Configuration' objects.") # Try to get configuration alias from env with fall back # to --conf argument (as passed by UwsgiRunner.spawn()). target_alias = os.environ.get(ENV_CONF_ALIAS) if not target_alias: last = sys.argv[-2:] if len(last) == 2 and last[0] == '--conf': target_alias = last[1] conf_list = list(registry.values()) if target_alias: # This call is [presumably] from uWSGI configuration read procedure. config = registry.get(target_alias) if config: section = config.sections[0] # type: Section # Set ready marker which is checked above. os.environ[ENV_CONF_READY] = '1' # Placeholder for runtime introspection. section.set_placeholder('config-alias', target_alias) # Print out config.print_ini() else: # This call is from module containing uWSGI configurations. import inspect # Set module attribute automatically. config_module = inspect.currentframe().f_back config_module.f_locals[CONFIGS_MODULE_ATTR] = conf_list return conf_list
Allows configuring uWSGI using Configuration objects returned by the given configuration function. .. code-block: python # In configuration module, e.g `uwsgicfg.py` from uwsgiconf.config import configure_uwsgi configure_uwsgi(get_configurations) :param callable configurator_func: Function which return a list on configurations. :rtype: list|None :returns: A list with detected configurations or ``None`` if called from within uWSGI (e.g. when trying to load WSGI application). :raises ConfigurationError:
entailment
def replace_placeholders(self, value): """Replaces placeholders that can be used e.g. in filepaths. Supported placeholders: * {project_runtime_dir} * {project_name} * {runtime_dir} :param str|unicode|list[str|unicode]|None value: :rtype: None|str|unicode|list[str|unicode] """ if not value: return value is_list = isinstance(value, list) values = [] for value in listify(value): runtime_dir = self.get_runtime_dir() project_name = self.project_name value = value.replace('{runtime_dir}', runtime_dir) value = value.replace('{project_name}', project_name) value = value.replace('{project_runtime_dir}', os.path.join(runtime_dir, project_name)) values.append(value) value = values if is_list else values.pop() return value
Replaces placeholders that can be used e.g. in filepaths. Supported placeholders: * {project_runtime_dir} * {project_name} * {runtime_dir} :param str|unicode|list[str|unicode]|None value: :rtype: None|str|unicode|list[str|unicode]
entailment
def get_runtime_dir(self, default=True): """Directory to store runtime files. See ``.replace_placeholders()`` .. note:: This can be used to store PID files, sockets, master FIFO, etc. :param bool default: Whether to return [system] default if not set. :rtype: str|unicode """ dir_ = self._runtime_dir if not dir_ and default: uid = self.main_process.get_owner()[0] dir_ = '/run/user/%s/' % uid if uid else '/run/' return dir_
Directory to store runtime files. See ``.replace_placeholders()`` .. note:: This can be used to store PID files, sockets, master FIFO, etc. :param bool default: Whether to return [system] default if not set. :rtype: str|unicode
entailment
def print_stamp(self): """Prints out a stamp containing useful information, such as what and when has generated this configuration. """ from . import VERSION print_out = partial(self.print_out, format_options='red') print_out('This configuration was automatically generated using') print_out('uwsgiconf v%s on %s' % ('.'.join(map(str, VERSION)), datetime.now().isoformat(' '))) return self
Prints out a stamp containing useful information, such as what and when has generated this configuration.
entailment
def print_out(self, value, indent=None, format_options=None, asap=False): """Prints out the given value. :param value: :param str|unicode indent: :param dict|str|unicode format_options: text color :param bool asap: Print as soon as possible. """ if indent is None: indent = '> ' text = indent + str(value) if format_options is None: format_options = 'gray' if self._style_prints and format_options: if not isinstance(format_options, dict): format_options = {'color_fg': format_options} text = format_print_text(text, **format_options) command = 'iprint' if asap else 'print' self._set(command, text, multi=True) return self
Prints out the given value. :param value: :param str|unicode indent: :param dict|str|unicode format_options: text color :param bool asap: Print as soon as possible.
entailment
def print_variables(self): """Prints out magic variables available in config files alongside with their values and descriptions. May be useful for debugging. http://uwsgi-docs.readthedocs.io/en/latest/Configuration.html#magic-variables """ print_out = partial(self.print_out, format_options='green') print_out('===== variables =====') for var, hint in self.vars.get_descriptions().items(): print_out(' %' + var + ' = ' + var + ' = ' + hint.replace('%', '%%')) print_out('=====================') return self
Prints out magic variables available in config files alongside with their values and descriptions. May be useful for debugging. http://uwsgi-docs.readthedocs.io/en/latest/Configuration.html#magic-variables
entailment
def set_plugins_params(self, plugins=None, search_dirs=None, autoload=None, required=False): """Sets plugin-related parameters. :param list|str|unicode|OptionsGroup|list[OptionsGroup] plugins: uWSGI plugins to load :param list|str|unicode search_dirs: Directories to search for uWSGI plugins. :param bool autoload: Try to automatically load plugins when unknown options are found. :param bool required: Load uWSGI plugins and exit on error. """ plugins = plugins or [] command = 'need-plugin' if required else 'plugin' for plugin in listify(plugins): if plugin not in self._plugins: self._set(command, plugin, multi=True) self._plugins.append(plugin) self._set('plugins-dir', search_dirs, multi=True, priority=0) self._set('autoload', autoload, cast=bool) return self
Sets plugin-related parameters. :param list|str|unicode|OptionsGroup|list[OptionsGroup] plugins: uWSGI plugins to load :param list|str|unicode search_dirs: Directories to search for uWSGI plugins. :param bool autoload: Try to automatically load plugins when unknown options are found. :param bool required: Load uWSGI plugins and exit on error.
entailment
def set_fallback(self, target): """Sets a fallback configuration for section. Re-exec uWSGI with the specified config when exit code is 1. :param str|unicode|Section target: File path or Section to include. """ if isinstance(target, Section): target = ':' + target.name self._set('fallback-config', target) return self
Sets a fallback configuration for section. Re-exec uWSGI with the specified config when exit code is 1. :param str|unicode|Section target: File path or Section to include.
entailment
def set_placeholder(self, key, value): """Placeholders are custom magic variables defined during configuration time. .. note:: These are accessible, like any uWSGI option, in your application code via ``.runtime.environ.uwsgi_env.config``. :param str|unicode key: :param str|unicode value: """ self._set('set-placeholder', '%s=%s' % (key, value), multi=True) return self
Placeholders are custom magic variables defined during configuration time. .. note:: These are accessible, like any uWSGI option, in your application code via ``.runtime.environ.uwsgi_env.config``. :param str|unicode key: :param str|unicode value:
entailment
def env(self, key, value=None, unset=False, asap=False): """Processes (sets/unsets) environment variable. If is not given in `set` mode value will be taken from current env. :param str|unicode key: :param value: :param bool unset: Whether to unset this variable. :param bool asap: If True env variable will be set as soon as possible. """ if unset: self._set('unenv', key, multi=True) else: if value is None: value = os.environ.get(key) self._set('%senv' % ('i' if asap else ''), '%s=%s' % (key, value), multi=True) return self
Processes (sets/unsets) environment variable. If is not given in `set` mode value will be taken from current env. :param str|unicode key: :param value: :param bool unset: Whether to unset this variable. :param bool asap: If True env variable will be set as soon as possible.
entailment
def include(self, target): """Includes target contents into config. :param str|unicode|Section|list target: File path or Section to include. """ for target_ in listify(target): if isinstance(target_, Section): target_ = ':' + target_.name self._set('ini', target_, multi=True) return self
Includes target contents into config. :param str|unicode|Section|list target: File path or Section to include.
entailment
def derive_from(cls, section, name=None): """Creates a new section based on the given. :param Section section: Section to derive from, :param str|unicode name: New section name. :rtype: Section """ new_section = deepcopy(section) if name: new_section.name = name return new_section
Creates a new section based on the given. :param Section section: Section to derive from, :param str|unicode name: New section name. :rtype: Section
entailment
def _validate_sections(cls, sections): """Validates sections types and uniqueness.""" names = [] for section in sections: if not hasattr(section, 'name'): raise ConfigurationError('`sections` attribute requires a list of Section') name = section.name if name in names: raise ConfigurationError('`%s` section name must be unique' % name) names.append(name)
Validates sections types and uniqueness.
entailment
def format(self, do_print=False, stamp=True): """Applies formatting to configuration. *Currently formats to .ini* :param bool do_print: Whether to print out formatted config. :param bool stamp: Whether to add stamp data to the first configuration section. :rtype: str|unicode """ if stamp and self.sections: self.sections[0].print_stamp() formatted = IniFormatter(self.sections).format() if do_print: print(formatted) return formatted
Applies formatting to configuration. *Currently formats to .ini* :param bool do_print: Whether to print out formatted config. :param bool stamp: Whether to add stamp data to the first configuration section. :rtype: str|unicode
entailment
def tofile(self, filepath=None): """Saves configuration into a file and returns its path. Convenience method. :param str|unicode filepath: Filepath to save configuration into. If not provided a temporary file will be automatically generated. :rtype: str|unicode """ if filepath is None: with NamedTemporaryFile(prefix='%s_' % self.alias, suffix='.ini', delete=False) as f: filepath = f.name else: filepath = os.path.abspath(filepath) if os.path.isdir(filepath): filepath = os.path.join(filepath, '%s.ini' % self.alias) with open(filepath, 'w') as target_file: target_file.write(self.format()) target_file.flush() return filepath
Saves configuration into a file and returns its path. Convenience method. :param str|unicode filepath: Filepath to save configuration into. If not provided a temporary file will be automatically generated. :rtype: str|unicode
entailment
def _set_name(self, version=AUTO): """Returns plugin name.""" name = 'python' if version: if version is AUTO: version = sys.version_info[0] if version == 2: version = '' name = '%s%s' % (name, version) self.name = name
Returns plugin name.
entailment
def set_app_args(self, *args): """Sets ``sys.argv`` for python apps. Examples: * pyargv="one two three" will set ``sys.argv`` to ``('one', 'two', 'three')``. :param args: """ if args: self._set('pyargv', ' '.join(args)) return self._section
Sets ``sys.argv`` for python apps. Examples: * pyargv="one two three" will set ``sys.argv`` to ``('one', 'two', 'three')``. :param args:
entailment
def set_wsgi_params(self, module=None, callable_name=None, env_strategy=None): """Set wsgi related parameters. :param str|unicode module: * load .wsgi file as the Python application * load a WSGI module as the application. .. note:: The module (sans ``.py``) must be importable, ie. be in ``PYTHONPATH``. Examples: * mypackage.my_wsgi_module -- read from `application` attr of mypackage/my_wsgi_module.py * mypackage.my_wsgi_module:my_app -- read from `my_app` attr of mypackage/my_wsgi_module.py :param str|unicode callable_name: Set WSGI callable name. Default: application. :param str|unicode env_strategy: Strategy for allocating/deallocating the WSGI env, can be: * ``cheat`` - preallocates the env dictionary on uWSGI startup and clears it after each request. Default behaviour for uWSGI <= 2.0.x * ``holy`` - creates and destroys the environ dictionary at each request. Default behaviour for uWSGI >= 2.1 """ module = module or '' if '/' in module: self._set('wsgi-file', module, condition=module) else: self._set('wsgi', module, condition=module) self._set('callable', callable_name) self._set('wsgi-env-behaviour', env_strategy) return self._section
Set wsgi related parameters. :param str|unicode module: * load .wsgi file as the Python application * load a WSGI module as the application. .. note:: The module (sans ``.py``) must be importable, ie. be in ``PYTHONPATH``. Examples: * mypackage.my_wsgi_module -- read from `application` attr of mypackage/my_wsgi_module.py * mypackage.my_wsgi_module:my_app -- read from `my_app` attr of mypackage/my_wsgi_module.py :param str|unicode callable_name: Set WSGI callable name. Default: application. :param str|unicode env_strategy: Strategy for allocating/deallocating the WSGI env, can be: * ``cheat`` - preallocates the env dictionary on uWSGI startup and clears it after each request. Default behaviour for uWSGI <= 2.0.x * ``holy`` - creates and destroys the environ dictionary at each request. Default behaviour for uWSGI >= 2.1
entailment
def set_autoreload_params(self, scan_interval=None, ignore_modules=None): """Sets autoreload related parameters. :param int scan_interval: Seconds. Monitor Python modules' modification times to trigger reload. .. warning:: Use only in development. :param list|st|unicode ignore_modules: Ignore the specified module during auto-reload scan. """ self._set('py-auto-reload', scan_interval) self._set('py-auto-reload-ignore', ignore_modules, multi=True) return self._section
Sets autoreload related parameters. :param int scan_interval: Seconds. Monitor Python modules' modification times to trigger reload. .. warning:: Use only in development. :param list|st|unicode ignore_modules: Ignore the specified module during auto-reload scan.
entailment
def register_module_alias(self, alias, module_path, after_init=False): """Adds an alias for a module. http://uwsgi-docs.readthedocs.io/en/latest/PythonModuleAlias.html :param str|unicode alias: :param str|unicode module_path: :param bool after_init: add a python module alias after uwsgi module initialization """ command = 'post-pymodule-alias' if after_init else 'pymodule-alias' self._set(command, '%s=%s' % (alias, module_path), multi=True) return self._section
Adds an alias for a module. http://uwsgi-docs.readthedocs.io/en/latest/PythonModuleAlias.html :param str|unicode alias: :param str|unicode module_path: :param bool after_init: add a python module alias after uwsgi module initialization
entailment
def import_module(self, modules, shared=False, into_spooler=False): """Imports a python module. :param list|str|unicode modules: :param bool shared: Import a python module in all of the processes. This is done after fork but before request processing. :param bool into_spooler: Import a python module in the spooler. http://uwsgi-docs.readthedocs.io/en/latest/Spooler.html """ if all((shared, into_spooler)): raise ConfigurationError('Unable to set both `shared` and `into_spooler` flags') if into_spooler: command = 'spooler-python-import' else: command = 'shared-python-import' if shared else 'python-import' self._set(command, modules, multi=True) return self._section
Imports a python module. :param list|str|unicode modules: :param bool shared: Import a python module in all of the processes. This is done after fork but before request processing. :param bool into_spooler: Import a python module in the spooler. http://uwsgi-docs.readthedocs.io/en/latest/Spooler.html
entailment
def set_server_params( self, client_notify_address=None, mountpoints_depth=None, require_vassal=None, tolerance=None, tolerance_inactive=None, key_dot_split=None): """Sets subscription server related params. :param str|unicode client_notify_address: Set the notification socket for subscriptions. When you subscribe to a server, you can ask it to "acknowledge" the acceptance of your request. pointing address (Unix socket or UDP), on which your instance will bind and the subscription server will send acknowledgements to. :param int mountpoints_depth: Enable support of mountpoints of certain depth for subscription system. * http://uwsgi-docs.readthedocs.io/en/latest/SubscriptionServer.html#mountpoints-uwsgi-2-1 :param bool require_vassal: Require a vassal field (see ``subscribe``) from each subscription. :param int tolerance: Subscription reclaim tolerance (seconds). :param int tolerance_inactive: Subscription inactivity tolerance (seconds). :param bool key_dot_split: Try to fallback to the next part in (dot based) subscription key. Used, for example, in SNI. """ # todo notify-socket (fallback) relation self._set('subscription-notify-socket', client_notify_address) self._set('subscription-mountpoint', mountpoints_depth) self._set('subscription-vassal-required', require_vassal, cast=bool) self._set('subscription-tolerance', tolerance) self._set('subscription-tolerance-inactive', tolerance_inactive) self._set('subscription-dotsplit', key_dot_split, cast=bool) return self._section
Sets subscription server related params. :param str|unicode client_notify_address: Set the notification socket for subscriptions. When you subscribe to a server, you can ask it to "acknowledge" the acceptance of your request. pointing address (Unix socket or UDP), on which your instance will bind and the subscription server will send acknowledgements to. :param int mountpoints_depth: Enable support of mountpoints of certain depth for subscription system. * http://uwsgi-docs.readthedocs.io/en/latest/SubscriptionServer.html#mountpoints-uwsgi-2-1 :param bool require_vassal: Require a vassal field (see ``subscribe``) from each subscription. :param int tolerance: Subscription reclaim tolerance (seconds). :param int tolerance_inactive: Subscription inactivity tolerance (seconds). :param bool key_dot_split: Try to fallback to the next part in (dot based) subscription key. Used, for example, in SNI.
entailment
def set_server_verification_params( self, digest_algo=None, dir_cert=None, tolerance=None, no_check_uid=None, dir_credentials=None, pass_unix_credentials=None): """Sets peer verification params for subscription server. These are for secured subscriptions. :param str|unicode digest_algo: Digest algorithm. Example: SHA1 .. note:: Also requires ``dir_cert`` to be set. :param str|unicode dir_cert: Certificate directory. .. note:: Also requires ``digest_algo`` to be set. :param int tolerance: Maximum tolerance (in seconds) of clock skew for secured subscription system. Default: 24h. :param str|unicode|int|list[str|unicode|int] no_check_uid: Skip signature check for the specified uids when using unix sockets credentials. :param str|unicode|list[str|unicode] dir_credentials: Directories to search for subscriptions key credentials. :param bool pass_unix_credentials: Enable management of SCM_CREDENTIALS in subscriptions UNIX sockets. """ if digest_algo and dir_cert: self._set('subscriptions-sign-check', '%s:%s' % (digest_algo, dir_cert)) self._set('subscriptions-sign-check-tolerance', tolerance) self._set('subscriptions-sign-skip-uid', no_check_uid, multi=True) self._set('subscriptions-credentials-check', dir_credentials, multi=True) self._set('subscriptions-use-credentials', pass_unix_credentials, cast=bool) return self._section
Sets peer verification params for subscription server. These are for secured subscriptions. :param str|unicode digest_algo: Digest algorithm. Example: SHA1 .. note:: Also requires ``dir_cert`` to be set. :param str|unicode dir_cert: Certificate directory. .. note:: Also requires ``digest_algo`` to be set. :param int tolerance: Maximum tolerance (in seconds) of clock skew for secured subscription system. Default: 24h. :param str|unicode|int|list[str|unicode|int] no_check_uid: Skip signature check for the specified uids when using unix sockets credentials. :param str|unicode|list[str|unicode] dir_credentials: Directories to search for subscriptions key credentials. :param bool pass_unix_credentials: Enable management of SCM_CREDENTIALS in subscriptions UNIX sockets.
entailment
def set_client_params( self, start_unsubscribed=None, clear_on_exit=None, unsubscribe_on_reload=None, announce_interval=None): """Sets subscribers related params. :param bool start_unsubscribed: Configure subscriptions but do not send them. .. note:: Useful with master FIFO. :param bool clear_on_exit: Force clear instead of unsubscribe during shutdown. :param bool unsubscribe_on_reload: Force unsubscribe request even during graceful reload. :param int announce_interval: Send subscription announce at the specified interval. Default: 10 master cycles. """ self._set('start-unsubscribed', start_unsubscribed, cast=bool) self._set('subscription-clear-on-shutdown', clear_on_exit, cast=bool) self._set('unsubscribe-on-graceful-reload', unsubscribe_on_reload, cast=bool) self._set('subscribe-freq', announce_interval) return self._section
Sets subscribers related params. :param bool start_unsubscribed: Configure subscriptions but do not send them. .. note:: Useful with master FIFO. :param bool clear_on_exit: Force clear instead of unsubscribe during shutdown. :param bool unsubscribe_on_reload: Force unsubscribe request even during graceful reload. :param int announce_interval: Send subscription announce at the specified interval. Default: 10 master cycles.
entailment
def subscribe( self, server=None, key=None, address=None, address_vassal=None, balancing_weight=None, balancing_algo=None, modifier=None, signing=None, check_file=None, protocol=None, sni_cert=None, sni_key=None, sni_client_ca=None): """Registers a subscription intent. :param str|unicode server: Subscription server address (UDP or UNIX socket). Examples: * 127.0.0.1:7171 :param str|unicode key: Key to subscribe. Generally the domain name (+ optional '/< mountpoint>'). Examples: * mydomain.it/foo * mydomain.it/foo/bar (requires ``mountpoints_depth=2``) * mydomain.it * ubuntu64.local:9090 :param str|unicode|int address: Address to subscribe (the value for the key) or zero-based internal socket number (integer). :param str|unicode address: Vassal node address. :param int balancing_weight: Load balancing value. Default: 1. :param balancing_algo: Load balancing algorithm to use. See ``balancing_algorithms`` .. note:: Since 2.1 :param Modifier modifier: Routing modifier object. See ``.routing.modifiers`` :param list|tuple signing: Signing basics, expects two elements list/tuple: (signing_algorithm, key). Examples: * SHA1:idlessh001 :param str|unicode check_file: If this file exists the subscription packet is sent, otherwise it is skipped. :param str|unicode protocol: the protocol to use, by default it is ``uwsgi``. See ``.networking.socket_types``. .. note:: Since 2.1 :param str|unicode sni_cert: Certificate file to use for SNI proxy management. * http://uwsgi.readthedocs.io/en/latest/SNI.html#subscription-system-and-sni :param str|unicode sni_key: sni_key Key file to use for SNI proxy management. * http://uwsgi.readthedocs.io/en/latest/SNI.html#subscription-system-and-sni :param str|unicode sni_client_ca: Ca file to use for SNI proxy management. * http://uwsgi.readthedocs.io/en/latest/SNI.html#subscription-system-and-sni """ # todo params: inactive (inactive slot activation) if not any((server, key)): raise ConfigurationError('Subscription requires `server` or `key` to be set.') address_key = 'addr' if isinstance(address, int): address_key = 'socket' if balancing_algo: backup = getattr(balancing_algo, 'backup_level', None) if signing: signing = ':'.join(signing) if modifier: modifier1 = modifier if modifier.submod: modifier2 = modifier.submod rule = KeyValue( filter_locals(locals(), drop=['address_key', 'modifier']), aliases={ 'address': address_key, 'address_vassal': 'vassal', 'signing': 'sign', 'check_file': 'check', 'balancing_weight': 'weight', 'balancing_algo': 'algo', 'protocol': 'proto', 'sni_cert': 'sni_crt', 'sni_client_ca': 'sni_ca', }, ) self._set('subscribe2', rule) return self._section
Registers a subscription intent. :param str|unicode server: Subscription server address (UDP or UNIX socket). Examples: * 127.0.0.1:7171 :param str|unicode key: Key to subscribe. Generally the domain name (+ optional '/< mountpoint>'). Examples: * mydomain.it/foo * mydomain.it/foo/bar (requires ``mountpoints_depth=2``) * mydomain.it * ubuntu64.local:9090 :param str|unicode|int address: Address to subscribe (the value for the key) or zero-based internal socket number (integer). :param str|unicode address: Vassal node address. :param int balancing_weight: Load balancing value. Default: 1. :param balancing_algo: Load balancing algorithm to use. See ``balancing_algorithms`` .. note:: Since 2.1 :param Modifier modifier: Routing modifier object. See ``.routing.modifiers`` :param list|tuple signing: Signing basics, expects two elements list/tuple: (signing_algorithm, key). Examples: * SHA1:idlessh001 :param str|unicode check_file: If this file exists the subscription packet is sent, otherwise it is skipped. :param str|unicode protocol: the protocol to use, by default it is ``uwsgi``. See ``.networking.socket_types``. .. note:: Since 2.1 :param str|unicode sni_cert: Certificate file to use for SNI proxy management. * http://uwsgi.readthedocs.io/en/latest/SNI.html#subscription-system-and-sni :param str|unicode sni_key: sni_key Key file to use for SNI proxy management. * http://uwsgi.readthedocs.io/en/latest/SNI.html#subscription-system-and-sni :param str|unicode sni_client_ca: Ca file to use for SNI proxy management. * http://uwsgi.readthedocs.io/en/latest/SNI.html#subscription-system-and-sni
entailment
def find_project_dir(): """Runs up the stack to find the location of manage.py which will be considered a project base path. :rtype: str|unicode """ frame = inspect.currentframe() while True: frame = frame.f_back fname = frame.f_globals['__file__'] if os.path.basename(fname) == 'manage.py': break return os.path.dirname(fname)
Runs up the stack to find the location of manage.py which will be considered a project base path. :rtype: str|unicode
entailment
def run_uwsgi(config_section, compile_only=False): """Runs uWSGI using the given section configuration. :param Section config_section: :param bool compile_only: Do not run, only compile and output configuration file for run. """ config = config_section.as_configuration() if compile_only: config.print_ini() return config_path = config.tofile() os.execvp('uwsgi', ['uwsgi', '--ini=%s' % config_path])
Runs uWSGI using the given section configuration. :param Section config_section: :param bool compile_only: Do not run, only compile and output configuration file for run.
entailment
def spawn(cls, options=None, dir_base=None): """Alternative constructor. Creates a mutator and returns section object. :param dict options: :param str|unicode dir_base: :rtype: SectionMutator """ from uwsgiconf.utils import ConfModule options = options or { 'compile': True, } dir_base = os.path.abspath(dir_base or find_project_dir()) name_module = ConfModule.default_name name_project = get_project_name(dir_base) path_conf = os.path.join(dir_base, name_module) if os.path.exists(path_conf): # Read an existing config for further modification of first section. section = cls._get_section_existing(name_module, name_project) else: # Create section on-fly. section = cls._get_section_new(dir_base) mutator = cls( section=section, dir_base=dir_base, project_name=name_project, options=options) mutator.mutate() return mutator
Alternative constructor. Creates a mutator and returns section object. :param dict options: :param str|unicode dir_base: :rtype: SectionMutator
entailment
def _get_section_existing(self, name_module, name_project): """Loads config section from existing configuration file (aka uwsgicfg.py) :param str|unicode name_module: :param str|unicode name_project: :rtype: Section """ from importlib import import_module from uwsgiconf.settings import CONFIGS_MODULE_ATTR config = getattr( import_module(os.path.splitext(name_module)[0], package=name_project), CONFIGS_MODULE_ATTR)[0] return config.sections[0]
Loads config section from existing configuration file (aka uwsgicfg.py) :param str|unicode name_module: :param str|unicode name_project: :rtype: Section
entailment
def _get_section_new(cls, dir_base): """Creates a new section with default settings. :param str|unicode dir_base: :rtype: Section """ from uwsgiconf.presets.nice import PythonSection from django.conf import settings wsgi_app = settings.WSGI_APPLICATION path_wsgi, filename, _, = wsgi_app.split('.') path_wsgi = os.path.join(dir_base, path_wsgi, '%s.py' %filename) section = PythonSection( wsgi_module=path_wsgi, ).networking.register_socket( PythonSection.networking.sockets.http('127.0.0.1:8000') ).main_process.change_dir(dir_base) return section
Creates a new section with default settings. :param str|unicode dir_base: :rtype: Section
entailment
def contribute_static(self): """Contributes static and media file serving settings to an existing section.""" options = self.options if options['compile'] or not options['use_static_handler']: return from django.core.management import call_command settings = self.settings statics = self.section.statics statics.register_static_map(settings.STATIC_URL, settings.STATIC_ROOT) statics.register_static_map(settings.MEDIA_URL, settings.MEDIA_ROOT) call_command('collectstatic', clear=True, interactive=False)
Contributes static and media file serving settings to an existing section.
entailment
def contribute_error_pages(self): """Contributes generic static error massage pages to an existing section.""" static_dir = self.settings.STATIC_ROOT if not static_dir: # Source static directory is not configured. Use temporary. import tempfile static_dir = os.path.join(tempfile.gettempdir(), self.project_name) self.settings.STATIC_ROOT = static_dir self.section.routing.set_error_pages( common_prefix=os.path.join(static_dir, 'uwsgify'))
Contributes generic static error massage pages to an existing section.
entailment
def mutate(self): """Mutates current section.""" section = self.section project_name = self.project_name section.project_name = project_name self.contribute_runtime_dir() main = section.main_process main.set_naming_params(prefix='[%s] ' % project_name) main.set_pid_file( self.get_pid_filepath(), before_priv_drop=False, # For vacuum to cleanup properly. safe=True, ) section.master_process.set_basic_params( fifo_file=self.get_fifo_filepath(), ) # todo maybe autoreload in debug apps = section.applications apps.set_basic_params( manage_script_name=True, ) self.contribute_error_pages() self.contribute_static()
Mutates current section.
entailment
def register_file_monitor(filename, target=None): """Maps a specific file/directory modification event to a signal. :param str|unicode filename: File or a directory to watch for its modification. :param int|Signal|str|unicode target: Existing signal to raise or Signal Target to register signal implicitly. Available targets: * ``workers`` - run the signal handler on all the workers * ``workerN`` - run the signal handler only on worker N * ``worker``/``worker0`` - run the signal handler on the first available worker * ``active-workers`` - run the signal handlers on all the active [non-cheaped] workers * ``mules`` - run the signal handler on all of the mules * ``muleN`` - run the signal handler on mule N * ``mule``/``mule0`` - run the signal handler on the first available mule * ``spooler`` - run the signal on the first available spooler * ``farmN/farm_XXX`` - run the signal handler in the mule farm N or named XXX :raises ValueError: If unable to register monitor. """ return _automate_signal(target, func=lambda sig: uwsgi.add_file_monitor(int(sig), filename))
Maps a specific file/directory modification event to a signal. :param str|unicode filename: File or a directory to watch for its modification. :param int|Signal|str|unicode target: Existing signal to raise or Signal Target to register signal implicitly. Available targets: * ``workers`` - run the signal handler on all the workers * ``workerN`` - run the signal handler only on worker N * ``worker``/``worker0`` - run the signal handler on the first available worker * ``active-workers`` - run the signal handlers on all the active [non-cheaped] workers * ``mules`` - run the signal handler on all of the mules * ``muleN`` - run the signal handler on mule N * ``mule``/``mule0`` - run the signal handler on the first available mule * ``spooler`` - run the signal on the first available spooler * ``farmN/farm_XXX`` - run the signal handler in the mule farm N or named XXX :raises ValueError: If unable to register monitor.
entailment
def set(self, value, mode=None): """Sets metric value. :param int|long value: New value. :param str|unicode mode: Update mode. * None - Unconditional update. * max - Sets metric value if it is greater that the current one. * min - Sets metric value if it is less that the current one. :rtype: bool """ if mode == 'max': func = uwsgi.metric_set_max elif mode == 'min': func = uwsgi.metric_set_min else: func = uwsgi.metric_set return func(self.name, value)
Sets metric value. :param int|long value: New value. :param str|unicode mode: Update mode. * None - Unconditional update. * max - Sets metric value if it is greater that the current one. * min - Sets metric value if it is less that the current one. :rtype: bool
entailment
def get_message(cls, signals=True, farms=False, buffer_size=65536, timeout=-1): """Block until a mule message is received and return it. This can be called from multiple threads in the same programmed mule. :param bool signals: Whether to manage signals. :param bool farms: Whether to manage farms. :param int buffer_size: :param int timeout: Seconds. :rtype: str|unicode :raises ValueError: If not in a mule. """ return decode(uwsgi.mule_get_msg(signals, farms, buffer_size, timeout))
Block until a mule message is received and return it. This can be called from multiple threads in the same programmed mule. :param bool signals: Whether to manage signals. :param bool farms: Whether to manage farms. :param int buffer_size: :param int timeout: Seconds. :rtype: str|unicode :raises ValueError: If not in a mule.
entailment
def regenerate(session): """Regenerates header files for cmark under ./generated.""" if platform.system() == 'Windows': output_dir = '../generated/windows' else: output_dir = '../generated/unix' session.run(shutil.rmtree, 'build', ignore_errors=True) session.run(os.makedirs, 'build') session.chdir('build') session.run('cmake', '../third_party/cmark') session.run(shutil.copy, 'src/cmark-gfm_export.h', output_dir) session.run(shutil.copy, 'src/cmark-gfm_version.h', output_dir) session.run(shutil.copy, 'src/config.h', output_dir) session.run(shutil.copy, 'extensions/cmark-gfm-extensions_export.h', output_dir) session.chdir('..') session.run(shutil.rmtree, 'build')
Regenerates header files for cmark under ./generated.
entailment
def output_capturing(): """Temporarily captures/redirects stdout.""" out = sys.stdout sys.stdout = StringIO() try: yield finally: sys.stdout = out
Temporarily captures/redirects stdout.
entailment
def filter_locals(locals_dict, drop=None, include=None): """Filters a dictionary produced by locals(). :param dict locals_dict: :param list drop: Keys to drop from dict. :param list include: Keys to include into dict. :rtype: dict """ drop = drop or [] drop.extend([ 'self', '__class__', # py3 ]) include = include or locals_dict.keys() relevant_keys = [key for key in include if key not in drop] locals_dict = {k: v for k, v in locals_dict.items() if k in relevant_keys} return locals_dict
Filters a dictionary produced by locals(). :param dict locals_dict: :param list drop: Keys to drop from dict. :param list include: Keys to include into dict. :rtype: dict
entailment
def get_output(cmd, args): """Runs a command and returns its output (stdout + stderr). :param str|unicode cmd: :param str|unicode|list[str|unicode] args: :rtype: str|unicode """ from subprocess import Popen, STDOUT, PIPE command = [cmd] command.extend(listify(args)) process = Popen(command, stdout=PIPE, stderr=STDOUT) out, _ = process.communicate() return out.decode('utf-8')
Runs a command and returns its output (stdout + stderr). :param str|unicode cmd: :param str|unicode|list[str|unicode] args: :rtype: str|unicode
entailment
def parse_command_plugins_output(out): """Parses ``plugin-list`` command output from uWSGI and returns object containing lists of embedded plugin names. :param str|unicode out: :rtype EmbeddedPlugins: """ out = out.split('--- end of plugins list ---')[0] out = out.partition('plugins ***')[2] out = out.splitlines() current_slot = 0 plugins = EmbeddedPlugins([], []) for line in out: line = line.strip() if not line: continue if line.startswith('***'): current_slot += 1 continue if current_slot is not None: plugins[current_slot].append(line) plugins = plugins._replace(request=[plugin.partition(' ')[2] for plugin in plugins.request]) return plugins
Parses ``plugin-list`` command output from uWSGI and returns object containing lists of embedded plugin names. :param str|unicode out: :rtype EmbeddedPlugins:
entailment
def get_uwsgi_stub_attrs_diff(): """Returns attributes difference two elements tuple between real uwsgi module and its stub. Might be of use while describing in stub new uwsgi functions. :return: (uwsgi_only_attrs, stub_only_attrs) :rtype: tuple """ try: import uwsgi except ImportError: from uwsgiconf.exceptions import UwsgiconfException raise UwsgiconfException( '`uwsgi` module is unavailable. Calling `get_attrs_diff` in such environment makes no sense.') from . import uwsgi_stub def get_attrs(src): return set(attr for attr in dir(src) if not attr.startswith('_')) attrs_uwsgi = get_attrs(uwsgi) attrs_stub = get_attrs(uwsgi_stub) from_uwsgi = sorted(attrs_uwsgi.difference(attrs_stub)) from_stub = sorted(attrs_stub.difference(attrs_uwsgi)) return from_uwsgi, from_stub
Returns attributes difference two elements tuple between real uwsgi module and its stub. Might be of use while describing in stub new uwsgi functions. :return: (uwsgi_only_attrs, stub_only_attrs) :rtype: tuple
entailment
def spawn_uwsgi(self, only=None): """Spawns uWSGI process(es) which will use configuration(s) from the module. Returns list of tuples: (configuration_alias, uwsgi_process_id) If only one configuration found current process (uwsgiconf) is replaced with a new one (uWSGI), otherwise a number of new detached processes is spawned. :param str|unicode only: Configuration alias to run from the module. If not set uWSGI will be spawned for every configuration found in the module. :rtype: list """ spawned = [] configs = self.configurations if len(configs) == 1: alias = configs[0].alias UwsgiRunner().spawn(self.fpath, alias, replace=True) spawned.append((alias, os.getpid())) else: for config in configs: # type: Configuration alias = config.alias if only is None or alias == only: pid = UwsgiRunner().spawn(self.fpath, alias) spawned.append((alias, pid)) return spawned
Spawns uWSGI process(es) which will use configuration(s) from the module. Returns list of tuples: (configuration_alias, uwsgi_process_id) If only one configuration found current process (uwsgiconf) is replaced with a new one (uWSGI), otherwise a number of new detached processes is spawned. :param str|unicode only: Configuration alias to run from the module. If not set uWSGI will be spawned for every configuration found in the module. :rtype: list
entailment
def configurations(self): """Configurations from uwsgiconf module.""" if self._confs is not None: return self._confs with output_capturing(): module = self.load(self.fpath) confs = getattr(module, CONFIGS_MODULE_ATTR) confs = listify(confs) self._confs = confs return confs
Configurations from uwsgiconf module.
entailment
def load(cls, fpath): """Loads a module and returns its object. :param str|unicode fpath: :rtype: module """ module_name = os.path.splitext(os.path.basename(fpath))[0] sys.path.insert(0, os.path.dirname(fpath)) try: module = import_module(module_name) finally: sys.path = sys.path[1:] return module
Loads a module and returns its object. :param str|unicode fpath: :rtype: module
entailment
def cmd_log(self, reopen=False, rotate=False): """Allows managing of uWSGI log related stuff :param bool reopen: Reopen log file. Could be required after third party rotation. :param bool rotate: Trigger built-in log rotation. """ cmd = b'' if reopen: cmd += b'l' if rotate: cmd += b'L' return self.send_command(cmd)
Allows managing of uWSGI log related stuff :param bool reopen: Reopen log file. Could be required after third party rotation. :param bool rotate: Trigger built-in log rotation.
entailment
def cmd_reload(self, force=False, workers_only=False, workers_chain=False): """Reloads uWSGI master process, workers. :param bool force: Use forced (brutal) reload instead of a graceful one. :param bool workers_only: Reload only workers. :param bool workers_chain: Run chained workers reload (one after another, instead of destroying all of them in bulk). """ if workers_chain: return self.send_command(b'c') if workers_only: return self.send_command(b'R' if force else b'r') return self.send_command(b'R' if force else b'r')
Reloads uWSGI master process, workers. :param bool force: Use forced (brutal) reload instead of a graceful one. :param bool workers_only: Reload only workers. :param bool workers_chain: Run chained workers reload (one after another, instead of destroying all of them in bulk).
entailment
def send_command(self, cmd): """Sends a generic command into FIFO. :param bytes cmd: Command chars to send into FIFO. """ if not cmd: return with open(self.fifo, 'wb') as f: f.write(cmd)
Sends a generic command into FIFO. :param bytes cmd: Command chars to send into FIFO.
entailment
def get_env_path(cls): """Returns PATH environment variable updated to run uwsgiconf in (e.g. for virtualenv). :rtype: str|unicode """ return os.path.dirname(Finder.python()) + os.pathsep + os.environ['PATH']
Returns PATH environment variable updated to run uwsgiconf in (e.g. for virtualenv). :rtype: str|unicode
entailment
def prepare_env(cls): """Prepares current environment and returns Python binary name. This adds some virtualenv friendliness so that we try use uwsgi from it. :rtype: str|unicode """ os.environ['PATH'] = cls.get_env_path() return os.path.basename(Finder.python())
Prepares current environment and returns Python binary name. This adds some virtualenv friendliness so that we try use uwsgi from it. :rtype: str|unicode
entailment
def spawn(self, filepath, configuration_alias, replace=False): """Spawns uWSGI using the given configuration module. :param str|unicode filepath: :param str|unicode configuration_alias: :param bool replace: Whether a new process should replace current one. """ # Pass --conf as an argument to have a chance to use # touch reloading form .py configuration file change. args = ['uwsgi', '--ini', 'exec://%s %s --conf %s' % (self.binary_python, filepath, configuration_alias)] if replace: return os.execvp('uwsgi', args) return os.spawnvp(os.P_NOWAIT, 'uwsgi', args)
Spawns uWSGI using the given configuration module. :param str|unicode filepath: :param str|unicode configuration_alias: :param bool replace: Whether a new process should replace current one.
entailment
def get(self, key, default=None, as_int=False, setter=None): """Gets a value from the cache. :param str|unicode key: The cache key to get value for. :param default: Value to return if none found in cache. :param bool as_int: Return 64bit number instead of str. :param callable setter: Setter callable to automatically set cache value if not already cached. Required to accept a key and return a value that will be cached. :rtype: str|unicode|int """ if as_int: val = uwsgi.cache_num(key, self.name) else: val = decode(uwsgi.cache_get(key, self.name)) if val is None: if setter is None: return default val = setter(key) if val is None: return default self.set(key, val) return val
Gets a value from the cache. :param str|unicode key: The cache key to get value for. :param default: Value to return if none found in cache. :param bool as_int: Return 64bit number instead of str. :param callable setter: Setter callable to automatically set cache value if not already cached. Required to accept a key and return a value that will be cached. :rtype: str|unicode|int
entailment
def set(self, key, value): """Sets the specified key value. :param str|unicode key: :param int|str|unicode value: :rtype: bool """ return uwsgi.cache_set(key, value, self.timeout, self.name)
Sets the specified key value. :param str|unicode key: :param int|str|unicode value: :rtype: bool
entailment
def incr(self, key, delta=1): """Increments the specified key value by the specified value. :param str|unicode key: :param int delta: :rtype: bool """ return uwsgi.cache_inc(key, delta, self.timeout, self.name)
Increments the specified key value by the specified value. :param str|unicode key: :param int delta: :rtype: bool
entailment
def decr(self, key, delta=1): """Decrements the specified key value by the specified value. :param str|unicode key: :param int delta: :rtype: bool """ return uwsgi.cache_dec(key, delta, self.timeout, self.name)
Decrements the specified key value by the specified value. :param str|unicode key: :param int delta: :rtype: bool
entailment
def mul(self, key, value=2): """Multiplies the specified key value by the specified value. :param str|unicode key: :param int value: :rtype: bool """ return uwsgi.cache_mul(key, value, self.timeout, self.name)
Multiplies the specified key value by the specified value. :param str|unicode key: :param int value: :rtype: bool
entailment
def div(self, key, value=2): """Divides the specified key value by the specified value. :param str|unicode key: :param int value: :rtype: bool """ return uwsgi.cache_mul(key, value, self.timeout, self.name)
Divides the specified key value by the specified value. :param str|unicode key: :param int value: :rtype: bool
entailment
def recv(request_context=None, non_blocking=False): """Receives data from websocket. :param request_context: :param bool non_blocking: :rtype: bytes|str :raises IOError: If unable to receive a message. """ if non_blocking: result = uwsgi.websocket_recv_nb(request_context) else: result = uwsgi.websocket_recv(request_context) return result
Receives data from websocket. :param request_context: :param bool non_blocking: :rtype: bytes|str :raises IOError: If unable to receive a message.
entailment
def send(message, request_context=None, binary=False): """Sends a message to websocket. :param str message: data to send :param request_context: :raises IOError: If unable to send a message. """ if binary: return uwsgi.websocket_send_binary(message, request_context) return uwsgi.websocket_send(message, request_context)
Sends a message to websocket. :param str message: data to send :param request_context: :raises IOError: If unable to send a message.
entailment
def markdown_to_html(text, options=0): """Render the given text to Markdown. This is a direct interface to ``cmark_markdown_to_html``. Args: text (str): The text to render to Markdown. options (int): The cmark options. Returns: str: The rendered markdown. """ encoded_text = text.encode('utf-8') raw_result = _cmark.lib.cmark_markdown_to_html( encoded_text, len(encoded_text), options) return _cmark.ffi.string(raw_result).decode('utf-8')
Render the given text to Markdown. This is a direct interface to ``cmark_markdown_to_html``. Args: text (str): The text to render to Markdown. options (int): The cmark options. Returns: str: The rendered markdown.
entailment
def markdown_to_html_with_extensions(text, options=0, extensions=None): """Render the given text to Markdown, using extensions. This is a high-level wrapper over the various functions needed to enable extensions, attach them to a parser, and render html. Args: text (str): The text to render to Markdown. options (int): The cmark options. extensions (Sequence[str]): The list of extension names to use. Returns: str: The rendered markdown. """ if extensions is None: extensions = [] core_extensions_ensure_registered() cmark_extensions = [] for extension_name in extensions: extension = find_syntax_extension(extension_name) if extension is None: raise ValueError('Unknown extension {}'.format(extension_name)) cmark_extensions.append(extension) parser = parser_new(options=options) try: for extension in cmark_extensions: parser_attach_syntax_extension(parser, extension) parser_feed(parser, text) root = parser_finish(parser) if _cmark.lib.cmark_node_get_type(root) == _cmark.lib.CMARK_NODE_NONE: raise ValueError('Error parsing markdown!') extensions_ll = parser_get_syntax_extensions(parser) output = render_html(root, options=options, extensions=extensions_ll) finally: parser_free(parser) return output
Render the given text to Markdown, using extensions. This is a high-level wrapper over the various functions needed to enable extensions, attach them to a parser, and render html. Args: text (str): The text to render to Markdown. options (int): The cmark options. extensions (Sequence[str]): The list of extension names to use. Returns: str: The rendered markdown.
entailment
def parse_document(text, options=0): """Parse a document and return the root node. Args: text (str): The text to parse. options (int): The cmark options. Returns: Any: Opaque reference to the root node of the parsed syntax tree. """ encoded_text = text.encode('utf-8') return _cmark.lib.cmark_parse_document( encoded_text, len(encoded_text), options)
Parse a document and return the root node. Args: text (str): The text to parse. options (int): The cmark options. Returns: Any: Opaque reference to the root node of the parsed syntax tree.
entailment
def parser_feed(parser, text): """Direct wrapper over cmark_parser_feed.""" encoded_text = text.encode('utf-8') return _cmark.lib.cmark_parser_feed( parser, encoded_text, len(encoded_text))
Direct wrapper over cmark_parser_feed.
entailment
def render_html(root, options=0, extensions=None): """Render a given syntax tree as HTML. Args: root (Any): The reference to the root node of the syntax tree. options (int): The cmark options. extensions (Any): The reference to the syntax extensions, generally from :func:`parser_get_syntax_extensions` Returns: str: The rendered HTML. """ if extensions is None: extensions = _cmark.ffi.NULL raw_result = _cmark.lib.cmark_render_html( root, options, extensions) return _cmark.ffi.string(raw_result).decode('utf-8')
Render a given syntax tree as HTML. Args: root (Any): The reference to the root node of the syntax tree. options (int): The cmark options. extensions (Any): The reference to the syntax extensions, generally from :func:`parser_get_syntax_extensions` Returns: str: The rendered HTML.
entailment
def find_syntax_extension(name): """Direct wrapper over cmark_find_syntax_extension.""" encoded_name = name.encode('utf-8') extension = _cmark.lib.cmark_find_syntax_extension(encoded_name) if extension == _cmark.ffi.NULL: return None else: return extension
Direct wrapper over cmark_find_syntax_extension.
entailment
def set_basic_params(self, no_expire=None, expire_scan_interval=None, report_freed=None): """ :param bool no_expire: Disable auto sweep of expired items. Since uWSGI 1.2, cache item expiration is managed by a thread in the master process, to reduce the risk of deadlock. This thread can be disabled (making item expiry a no-op) with the this option. :param int expire_scan_interval: Set the frequency (in seconds) of cache sweeper scans. Default: 3. :param bool report_freed: Constantly report the cache item freed by the sweeper. .. warning:: Use only for debug. """ self._set('cache-no-expire', no_expire, cast=bool) self._set('cache-report-freed-items', report_freed, cast=bool) self._set('cache-expire-freq', expire_scan_interval) return self._section
:param bool no_expire: Disable auto sweep of expired items. Since uWSGI 1.2, cache item expiration is managed by a thread in the master process, to reduce the risk of deadlock. This thread can be disabled (making item expiry a no-op) with the this option. :param int expire_scan_interval: Set the frequency (in seconds) of cache sweeper scans. Default: 3. :param bool report_freed: Constantly report the cache item freed by the sweeper. .. warning:: Use only for debug.
entailment
def add_item(self, key, value, cache_name=None): """Add an item into the given cache. This is a commodity option (mainly useful for testing) allowing you to store an item in a uWSGI cache during startup. :param str|unicode key: :param value: :param str|unicode cache_name: If not set, default will be used. """ cache_name = cache_name or '' value = '%s %s=%s' % (cache_name, key, value) self._set('add-cache-item', value.strip(), multi=True) return self._section
Add an item into the given cache. This is a commodity option (mainly useful for testing) allowing you to store an item in a uWSGI cache during startup. :param str|unicode key: :param value: :param str|unicode cache_name: If not set, default will be used.
entailment
def add_file(self, filepath, gzip=False, cache_name=None): """Load a static file in the cache. .. note:: Items are stored with the filepath as is (relative or absolute) as the key. :param str|unicode filepath: :param bool gzip: Use gzip compression. :param str|unicode cache_name: If not set, default will be used. """ command = 'load-file-in-cache' if gzip: command += '-gzip' cache_name = cache_name or '' value = '%s %s' % (cache_name, filepath) self._set(command, value.strip(), multi=True) return self._section
Load a static file in the cache. .. note:: Items are stored with the filepath as is (relative or absolute) as the key. :param str|unicode filepath: :param bool gzip: Use gzip compression. :param str|unicode cache_name: If not set, default will be used.
entailment
def add_cache( self, name, max_items, expires=None, store=None, store_sync_interval=None, store_delete=None, hash_algo=None, hash_size=None, key_size=None, udp_clients=None, udp_servers=None, block_size=None, block_count=None, sync_from=None, mode_bitmap=None, use_lastmod=None, full_silent=None, full_purge_lru=None): """Creates cache. Default mode: single block. .. note:: This uses new generation ``cache2`` option available since uWSGI 1.9. .. note:: When at least one cache is configured without ``full_purge_lru`` and the master is enabled a thread named "the cache sweeper" is started. Its main purpose is deleting expired keys from the cache. If you want auto-expiring you need to enable the master. :param str|unicode name: Set the name of the cache. Must be unique in an instance. :param int max_items: Set the maximum number of cache items. .. note:: Effective number of items is **max_items - 1** - the first item of the cache is always internally used as "NULL/None/undef". :param int expires: The number of seconds after the object is no more valid (and will be removed by the cache sweeper when ``full_purge_lru`` is not set. :param str|unicode store: Set the filename for the persistent storage. If it doesn't exist, the system assumes an empty cache and the file will be created. :param int store_sync_interval: Set the number of seconds after which msync() is called to flush memory cache on disk when in persistent mode. By default it is disabled leaving the decision-making to the kernel. :param bool store_delete: uWSGI, by default, will not start if a cache file exists and the store file does not match the configured items/blocksize. Setting this option will make uWSGI delete the existing file upon mismatch and create a new one. :param str|unicode hash_algo: Set the hash algorithm used in the hash table. Current options are: * djb33x (default) * murmur2 :param int hash_size: This is the size of the hash table in bytes. Generally 65536 (the default) is a good value. .. note:: Change it only if you know what you are doing or if you have a lot of collisions in your cache. :param int key_size: Set the maximum size of a key, in bytes. Default: 2048. :param str|unicode|list udp_clients: List of UDP servers which will receive UDP cache updates. :param str|unicode |list udp_servers: List of UDP addresses on which to bind the cache to wait for UDP updates. :param int block_size: Set the size (in bytes) of a single block. .. note:: It's a good idea to use a multiple of 4096 (common memory page size). :param int block_count: Set the number of blocks in the cache. Useful only in bitmap mode, otherwise the number of blocks is equal to the maximum number of items. :param str|unicode|list sync_from: List of uWSGI addresses which the cache subsystem will connect to for getting a full dump of the cache. It can be used for initial cache synchronization. The first node sending a valid dump will stop the procedure. :param bool mode_bitmap: Enable (more versatile but relatively slower) bitmap mode. http://uwsgi-docs.readthedocs.io/en/latest/Caching.html#single-block-faster-vs-bitmaps-slower .. warning:: Considered production ready only from uWSGI 2.0.2. :param bool use_lastmod: Enabling will update last_modified_at timestamp of each cache on every cache item modification. Enable it if you want to track this value or if other features depend on it. This value will then be accessible via the stats socket. :param bool full_silent: By default uWSGI will print warning message on every cache set operation if the cache is full. To disable this warning set this option. .. note:: Available since 2.0.4. :param bool full_purge_lru: Allows the caching framework to evict Least Recently Used (LRU) item when you try to add new item to cache storage that is full. .. note:: ``expires`` argument will be ignored. """ value = KeyValue( locals(), keys=[ 'name', 'max_items', 'expires', 'store', 'store_sync_interval', 'store_delete', 'hash_algo', 'hash_size', 'key_size', 'udp_clients', 'udp_servers', 'block_size', 'block_count', 'sync_from', 'mode_bitmap', 'use_lastmod', 'full_silent', 'full_purge_lru', ], aliases={ 'max_items': 'maxitems', 'store_sync_interval': 'storesync', 'hash_algo': 'hash', 'udp_clients': 'nodes', 'block_size': 'blocksize', 'block_count': 'blocks', 'sync_from': 'sync', 'mode_bitmap': 'bitmap', 'use_lastmod': 'lastmod', 'full_silent': 'ignore_full', 'full_purge_lru': 'purge_lru', }, bool_keys=['store_delete', 'mode_bitmap', 'use_lastmod', 'full_silent', 'full_purge_lru'], list_keys=['udp_clients', 'udp_servers', 'sync_from'], ) self._set('cache2', value, multi=True) return self._section
Creates cache. Default mode: single block. .. note:: This uses new generation ``cache2`` option available since uWSGI 1.9. .. note:: When at least one cache is configured without ``full_purge_lru`` and the master is enabled a thread named "the cache sweeper" is started. Its main purpose is deleting expired keys from the cache. If you want auto-expiring you need to enable the master. :param str|unicode name: Set the name of the cache. Must be unique in an instance. :param int max_items: Set the maximum number of cache items. .. note:: Effective number of items is **max_items - 1** - the first item of the cache is always internally used as "NULL/None/undef". :param int expires: The number of seconds after the object is no more valid (and will be removed by the cache sweeper when ``full_purge_lru`` is not set. :param str|unicode store: Set the filename for the persistent storage. If it doesn't exist, the system assumes an empty cache and the file will be created. :param int store_sync_interval: Set the number of seconds after which msync() is called to flush memory cache on disk when in persistent mode. By default it is disabled leaving the decision-making to the kernel. :param bool store_delete: uWSGI, by default, will not start if a cache file exists and the store file does not match the configured items/blocksize. Setting this option will make uWSGI delete the existing file upon mismatch and create a new one. :param str|unicode hash_algo: Set the hash algorithm used in the hash table. Current options are: * djb33x (default) * murmur2 :param int hash_size: This is the size of the hash table in bytes. Generally 65536 (the default) is a good value. .. note:: Change it only if you know what you are doing or if you have a lot of collisions in your cache. :param int key_size: Set the maximum size of a key, in bytes. Default: 2048. :param str|unicode|list udp_clients: List of UDP servers which will receive UDP cache updates. :param str|unicode |list udp_servers: List of UDP addresses on which to bind the cache to wait for UDP updates. :param int block_size: Set the size (in bytes) of a single block. .. note:: It's a good idea to use a multiple of 4096 (common memory page size). :param int block_count: Set the number of blocks in the cache. Useful only in bitmap mode, otherwise the number of blocks is equal to the maximum number of items. :param str|unicode|list sync_from: List of uWSGI addresses which the cache subsystem will connect to for getting a full dump of the cache. It can be used for initial cache synchronization. The first node sending a valid dump will stop the procedure. :param bool mode_bitmap: Enable (more versatile but relatively slower) bitmap mode. http://uwsgi-docs.readthedocs.io/en/latest/Caching.html#single-block-faster-vs-bitmaps-slower .. warning:: Considered production ready only from uWSGI 2.0.2. :param bool use_lastmod: Enabling will update last_modified_at timestamp of each cache on every cache item modification. Enable it if you want to track this value or if other features depend on it. This value will then be accessible via the stats socket. :param bool full_silent: By default uWSGI will print warning message on every cache set operation if the cache is full. To disable this warning set this option. .. note:: Available since 2.0.4. :param bool full_purge_lru: Allows the caching framework to evict Least Recently Used (LRU) item when you try to add new item to cache storage that is full. .. note:: ``expires`` argument will be ignored.
entailment
def register_timer(period, target=None): """Add timer. Can be used as a decorator: .. code-block:: python @register_timer(3) def repeat(): do() :param int period: The interval (seconds) at which to raise the signal. :param int|Signal|str|unicode target: Existing signal to raise or Signal Target to register signal implicitly. Available targets: * ``workers`` - run the signal handler on all the workers * ``workerN`` - run the signal handler only on worker N * ``worker``/``worker0`` - run the signal handler on the first available worker * ``active-workers`` - run the signal handlers on all the active [non-cheaped] workers * ``mules`` - run the signal handler on all of the mules * ``muleN`` - run the signal handler on mule N * ``mule``/``mule0`` - run the signal handler on the first available mule * ``spooler`` - run the signal on the first available spooler * ``farmN/farm_XXX`` - run the signal handler in the mule farm N or named XXX :rtype: bool|callable :raises ValueError: If unable to add timer. """ return _automate_signal(target, func=lambda sig: uwsgi.add_timer(int(sig), period))
Add timer. Can be used as a decorator: .. code-block:: python @register_timer(3) def repeat(): do() :param int period: The interval (seconds) at which to raise the signal. :param int|Signal|str|unicode target: Existing signal to raise or Signal Target to register signal implicitly. Available targets: * ``workers`` - run the signal handler on all the workers * ``workerN`` - run the signal handler only on worker N * ``worker``/``worker0`` - run the signal handler on the first available worker * ``active-workers`` - run the signal handlers on all the active [non-cheaped] workers * ``mules`` - run the signal handler on all of the mules * ``muleN`` - run the signal handler on mule N * ``mule``/``mule0`` - run the signal handler on the first available mule * ``spooler`` - run the signal on the first available spooler * ``farmN/farm_XXX`` - run the signal handler in the mule farm N or named XXX :rtype: bool|callable :raises ValueError: If unable to add timer.
entailment
def register_timer_rb(period, repeat=None, target=None): """Add a red-black timer (based on black-red tree). .. code-block:: python @register_timer_rb(3) def repeat(): do() :param int period: The interval (seconds) at which the signal is raised. :param int repeat: How many times to repeat. Default: None - infinitely. :param int|Signal|str|unicode target: Existing signal to raise or Signal Target to register signal implicitly. Available targets: * ``workers`` - run the signal handler on all the workers * ``workerN`` - run the signal handler only on worker N * ``worker``/``worker0`` - run the signal handler on the first available worker * ``active-workers`` - run the signal handlers on all the active [non-cheaped] workers * ``mules`` - run the signal handler on all of the mules * ``muleN`` - run the signal handler on mule N * ``mule``/``mule0`` - run the signal handler on the first available mule * ``spooler`` - run the signal on the first available spooler * ``farmN/farm_XXX`` - run the signal handler in the mule farm N or named XXX :rtype: bool|callable :raises ValueError: If unable to add timer. """ return _automate_signal(target, func=lambda sig: uwsgi.add_rb_timer(int(sig), period, repeat or 0))
Add a red-black timer (based on black-red tree). .. code-block:: python @register_timer_rb(3) def repeat(): do() :param int period: The interval (seconds) at which the signal is raised. :param int repeat: How many times to repeat. Default: None - infinitely. :param int|Signal|str|unicode target: Existing signal to raise or Signal Target to register signal implicitly. Available targets: * ``workers`` - run the signal handler on all the workers * ``workerN`` - run the signal handler only on worker N * ``worker``/``worker0`` - run the signal handler on the first available worker * ``active-workers`` - run the signal handlers on all the active [non-cheaped] workers * ``mules`` - run the signal handler on all of the mules * ``muleN`` - run the signal handler on mule N * ``mule``/``mule0`` - run the signal handler on the first available mule * ``spooler`` - run the signal on the first available spooler * ``farmN/farm_XXX`` - run the signal handler in the mule farm N or named XXX :rtype: bool|callable :raises ValueError: If unable to add timer.
entailment
def register_cron(weekday=None, month=None, day=None, hour=None, minute=None, target=None): """Adds cron. The interface to the uWSGI signal cron facility. .. code-block:: python @register_cron(hour=-3) # Every 3 hours. def repeat(): do() .. note:: Arguments work similarly to a standard crontab, but instead of "*", use -1, and instead of "/2", "/3", etc. use -2 and -3, etc. .. note:: Periods - rules like hour='10-18/2' (from 10 till 18 every 2 hours) - are allowed, but they are emulated by uwsgiconf. Use strings to define periods. Keep in mind, that your actual function will be wrapped into another one, which will check whether it is time to call your function. :param int|str|unicode weekday: Day of a the week number. Defaults to `each`. 0 - Sunday 1 - Monday 2 - Tuesday 3 - Wednesday 4 - Thursday 5 - Friday 6 - Saturday :param int|str|unicode month: Month number 1-12. Defaults to `each`. :param int|str|unicode day: Day of the month number 1-31. Defaults to `each`. :param int|str|unicode hour: Hour 0-23. Defaults to `each`. :param int|str|unicode minute: Minute 0-59. Defaults to `each`. :param int|Signal|str|unicode target: Existing signal to raise or Signal Target to register signal implicitly. Available targets: * ``workers`` - run the signal handler on all the workers * ``workerN`` - run the signal handler only on worker N * ``worker``/``worker0`` - run the signal handler on the first available worker * ``active-workers`` - run the signal handlers on all the active [non-cheaped] workers * ``mules`` - run the signal handler on all of the mules * ``muleN`` - run the signal handler on mule N * ``mule``/``mule0`` - run the signal handler on the first available mule * ``spooler`` - run the signal on the first available spooler * ``farmN/farm_XXX`` - run the signal handler in the mule farm N or named XXX :rtype: bool|callable :raises ValueError: If unable to add cron rule. """ task_args_initial = {name: val for name, val in locals().items() if val is not None and name != 'target'} task_args_casted = {} def skip_task(check_funcs): now = datetime.now() allright = all((func(now) for func in check_funcs)) return not allright def check_date(now, attr, target_range): attr = getattr(now, attr) if callable(attr): # E.g. weekday. attr = attr() return attr in target_range check_date_funcs = [] for name, val in task_args_initial.items(): # uWSGI won't accept strings, so we emulate ranges here. if isinstance(val, string_types): # Rules like 10-18/2 (from 10 till 18 every 2 hours). val, _, step = val.partition('/') step = int(step) if step else 1 start, _, end = val.partition('-') if not (start and end): raise RuntimeConfigurationError( 'String cron rule without a range is not supported. Use integer notation.') start = int(start) end = int(end) now_attr_name = name period_range = set(range(start, end+1, step)) if name == 'weekday': # Special case for weekday indexes: swap uWSGI Sunday 0 for ISO Sunday 7. now_attr_name = 'isoweekday' if 0 in period_range: period_range.discard(0) period_range.add(7) # Gather date checking functions in one place. check_date_funcs.append(partial(check_date, attr=now_attr_name, target_range=period_range)) # Use minimal duration (-1). val = None task_args_casted[name] = val if not check_date_funcs: # No special handling of periods, quit early. args = [(-1 if arg is None else arg) for arg in (minute, hour, day, month, weekday)] return _automate_signal(target, func=lambda sig: uwsgi.add_cron(int(sig), *args)) skip_task = partial(skip_task, check_date_funcs) def decor(func_action): """Decorator wrapping.""" @wraps(func_action) def func_action_wrapper(*args, **kwargs): """Action function wrapper to handle periods in rules.""" if skip_task(): # todo Maybe allow user defined value for this return. return None return func_action(*args, **kwargs) args = [] for arg_name in ['minute', 'hour', 'day', 'month', 'weekday']: arg = task_args_casted.get(arg_name, None) args.append(-1 if arg is None else arg) return _automate_signal(target, func=lambda sig: uwsgi.add_cron(int(sig), *args))(func_action_wrapper) return decor
Adds cron. The interface to the uWSGI signal cron facility. .. code-block:: python @register_cron(hour=-3) # Every 3 hours. def repeat(): do() .. note:: Arguments work similarly to a standard crontab, but instead of "*", use -1, and instead of "/2", "/3", etc. use -2 and -3, etc. .. note:: Periods - rules like hour='10-18/2' (from 10 till 18 every 2 hours) - are allowed, but they are emulated by uwsgiconf. Use strings to define periods. Keep in mind, that your actual function will be wrapped into another one, which will check whether it is time to call your function. :param int|str|unicode weekday: Day of a the week number. Defaults to `each`. 0 - Sunday 1 - Monday 2 - Tuesday 3 - Wednesday 4 - Thursday 5 - Friday 6 - Saturday :param int|str|unicode month: Month number 1-12. Defaults to `each`. :param int|str|unicode day: Day of the month number 1-31. Defaults to `each`. :param int|str|unicode hour: Hour 0-23. Defaults to `each`. :param int|str|unicode minute: Minute 0-59. Defaults to `each`. :param int|Signal|str|unicode target: Existing signal to raise or Signal Target to register signal implicitly. Available targets: * ``workers`` - run the signal handler on all the workers * ``workerN`` - run the signal handler only on worker N * ``worker``/``worker0`` - run the signal handler on the first available worker * ``active-workers`` - run the signal handlers on all the active [non-cheaped] workers * ``mules`` - run the signal handler on all of the mules * ``muleN`` - run the signal handler on mule N * ``mule``/``mule0`` - run the signal handler on the first available mule * ``spooler`` - run the signal on the first available spooler * ``farmN/farm_XXX`` - run the signal handler in the mule farm N or named XXX :rtype: bool|callable :raises ValueError: If unable to add cron rule.
entailment
def truncate_ellipsis(line, length=30): """Truncate a line to the specified length followed by ``...`` unless its shorter than length already.""" l = len(line) return line if l < length else line[:length - 3] + "..."
Truncate a line to the specified length followed by ``...`` unless its shorter than length already.
entailment
def pyle_evaluate(expressions=None, modules=(), inplace=False, files=None, print_traceback=False): """The main method of pyle.""" eval_globals = {} eval_globals.update(STANDARD_MODULES) for module_arg in modules or (): for module in module_arg.strip().split(","): module = module.strip() if module: eval_globals[module] = __import__(module) if not expressions: # Default 'do nothing' program expressions = ['line'] files = files or ['-'] eval_locals = {} for file in files: if file == '-': file = sys.stdin out_buf = sys.stdout if not inplace else StringIO.StringIO() out_line = None with (open(file, 'rb') if not hasattr(file, 'read') else file) as in_file: for num, line in enumerate(in_file.readlines()): was_whole_line = False if line[-1] == '\n': was_whole_line = True line = line[:-1] expr = "" try: for expr in expressions: words = [word.strip() for word in re.split(r'\s+', line) if word] eval_locals.update({ 'line': line, 'words': words, 'filename': in_file.name, 'num': num }) out_line = eval(expr, eval_globals, eval_locals) if out_line is None: continue # If the result is something list-like or iterable, # output each item space separated. if not isinstance(out_line, str) and not isinstance(out_line, unicode): try: out_line = u' '.join(unicode(part) for part in out_line) except: # Guess it wasn't a list after all. out_line = unicode(out_line) line = out_line except Exception as e: sys.stdout.flush() sys.stderr.write("At %s:%d ('%s'): `%s`: %s\n" % ( in_file.name, num, truncate_ellipsis(line), expr, e)) if print_traceback: traceback.print_exc(None, sys.stderr) else: if out_line is None: continue out_line = out_line or u'' out_buf.write(out_line) if was_whole_line: out_buf.write('\n') if inplace: with open(file, 'wb') as out_file: out_file.write(out_buf.getvalue()) out_buf.close()
The main method of pyle.
entailment
def pyle(argv=None): """Execute pyle with the specified arguments, or sys.argv if no arguments specified.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("-m", "--modules", dest="modules", action='append', help="import MODULE before evaluation. May be specified more than once.") parser.add_argument("-i", "--inplace", dest="inplace", action='store_true', default=False, help="edit files in place. When used with file name arguments, the files will be replaced by the output of the evaluation") parser.add_argument("-e", "--expression", action="append", dest="expressions", help="an expression to evaluate for each line") parser.add_argument('files', nargs='*', help="files to read as input. If used with --inplace, the files will be replaced with the output") parser.add_argument("--traceback", action="store_true", default=False, help="print a traceback on stderr when an expression fails for a line") args = parser.parse_args() if not argv else parser.parse_args(argv) pyle_evaluate(args.expressions, args.modules, args.inplace, args.files, args.traceback)
Execute pyle with the specified arguments, or sys.argv if no arguments specified.
entailment
def convert_to_international_phonetic_alphabet(self, arpabet): ''' θ½¬ζ’ζˆε›½ι™…ιŸ³ζ ‡ :param arpabet: :return: ''' word = self._convert_to_word(arpabet=arpabet) if not word: return None return word.translate_to_international_phonetic_alphabet()
θ½¬ζ’ζˆε›½ι™…ιŸ³ζ ‡ :param arpabet: :return:
entailment
def convert_to_american_phonetic_alphabet(self, arpabet): ''' 转捒成美音 :param arpabet: :return: ''' word = self._convert_to_word(arpabet=arpabet) if not word: return None return word.translate_to_american_phonetic_alphabet()
转捒成美音 :param arpabet: :return:
entailment
def convert_to_english_phonetic_alphabet(self, arpabet): ''' θ½¬ζ’ζˆθ‹±ιŸ³ :param arpabet: :return: ''' word = self._convert_to_word(arpabet=arpabet) if not word: return None return word.translate_to_english_phonetic_alphabet()
θ½¬ζ’ζˆθ‹±ιŸ³ :param arpabet: :return:
entailment
def translate_to_arpabet(self): ''' 转捒成arpabet :return: ''' translations = [] for phoneme in self._phoneme_list: if phoneme.is_vowel: translations.append(phoneme.arpabet + self.stress.mark_arpabet()) else: translations.append(phoneme.arpabet) return " ".join(translations)
转捒成arpabet :return:
entailment
def translate_to_american_phonetic_alphabet(self, hide_stress_mark=False): ''' θ½¬ζ’ζˆηΎŽιŸ³ιŸ³γ€‚εͺ要一δΈͺε…ƒιŸ³ηš„ζ—Άε€™ιœ€θ¦ιšθ—ι‡ιŸ³ζ ‡θ―† :param hide_stress_mark: :return: ''' translations = self.stress.mark_ipa() if (not hide_stress_mark) and self.have_vowel else "" for phoneme in self._phoneme_list: translations += phoneme.american return translations
θ½¬ζ’ζˆηΎŽιŸ³ιŸ³γ€‚εͺ要一δΈͺε…ƒιŸ³ηš„ζ—Άε€™ιœ€θ¦ιšθ—ι‡ιŸ³ζ ‡θ―† :param hide_stress_mark: :return:
entailment
def translate_to_english_phonetic_alphabet(self, hide_stress_mark=False): ''' θ½¬ζ’ζˆθ‹±ιŸ³γ€‚εͺ要一δΈͺε…ƒιŸ³ηš„ζ—Άε€™ιœ€θ¦ιšθ—ι‡ιŸ³ζ ‡θ―† :param hide_stress_mark: :return: ''' translations = self.stress.mark_ipa() if (not hide_stress_mark) and self.have_vowel else "" for phoneme in self._phoneme_list: translations += phoneme.english return translations
θ½¬ζ’ζˆθ‹±ιŸ³γ€‚εͺ要一δΈͺε…ƒιŸ³ηš„ζ—Άε€™ιœ€θ¦ιšθ—ι‡ιŸ³ζ ‡θ―† :param hide_stress_mark: :return:
entailment
def translate_to_international_phonetic_alphabet(self, hide_stress_mark=False): ''' θ½¬ζ’ζˆε›½ι™…ιŸ³ζ ‡γ€‚εͺ要一δΈͺε…ƒιŸ³ηš„ζ—Άε€™ιœ€θ¦ιšθ—ι‡ιŸ³ζ ‡θ―† :param hide_stress_mark: :return: ''' translations = self.stress.mark_ipa() if (not hide_stress_mark) and self.have_vowel else "" for phoneme in self._phoneme_list: translations += phoneme.ipa return translations
θ½¬ζ’ζˆε›½ι™…ιŸ³ζ ‡γ€‚εͺ要一δΈͺε…ƒιŸ³ηš„ζ—Άε€™ιœ€θ¦ιšθ—ι‡ιŸ³ζ ‡θ―† :param hide_stress_mark: :return:
entailment
def get_login_form_component(self): """Initializes and returns the login form component @rtype: LoginForm @return: Initialized component """ self.dw.wait_until( lambda: self.dw.is_present(LoginForm.locators.form), failure_message='login form was never present so could not get the model ' 'upload form component' ) self.login_form = LoginForm( parent_page=self, element=self.dw.find(LoginForm.locators.form), ) return self.login_form
Initializes and returns the login form component @rtype: LoginForm @return: Initialized component
entailment
def objectify(dictionary, name='Object'): """Converts a dictionary into a named tuple (shallow) """ o = namedtuple(name, dictionary.keys())(*dictionary.values()) return o
Converts a dictionary into a named tuple (shallow)
entailment
def create_directory(directory): """Creates a directory if it does not exist (in a thread-safe way) @param directory: The directory to create @return: The directory specified """ try: os.makedirs(directory) except OSError, e: if e.errno == errno.EEXIST and os.path.isdir(directory): pass return directory
Creates a directory if it does not exist (in a thread-safe way) @param directory: The directory to create @return: The directory specified
entailment
def __add_query_comment(sql): """ Adds a comment line to the query to be executed containing the line number of the calling function. This is useful for debugging slow queries, as the comment will show in the slow query log @type sql: str @param sql: sql needing comment @return: """ # Inspect the call stack for the originating call file_name = '' line_number = '' caller_frames = inspect.getouterframes(inspect.currentframe()) for frame in caller_frames: if "ShapewaysDb" not in frame[1]: file_name = frame[1] line_number = str(frame[2]) break comment = "/*COYOTE: Q_SRC: {file}:{line} */\n".format(file=file_name, line=line_number) return comment + sql,
Adds a comment line to the query to be executed containing the line number of the calling function. This is useful for debugging slow queries, as the comment will show in the slow query log @type sql: str @param sql: sql needing comment @return:
entailment