text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Format given text using ANSI formatting escape sequences.
<END_TASK>
<USER_TASK:>
Description:
def format_print_text(text, color_fg=None, color_bg=None):
"""Format given text using ANSI formatting escape sequences.
Could be useful gfor print command.
:param str|unicode text:
:param str|unicode color_fg: text (foreground) color
:param str|unicode color_bg: text (background) color
:rtype: str|unicode
""" |
from .config import Section
color_fg = {
'black': '30',
'red': '31',
'reder': '91',
'green': '32',
'greener': '92',
'yellow': '33',
'yellower': '93',
'blue': '34',
'bluer': '94',
'magenta': '35',
'magenter': '95',
'cyan': '36',
'cyaner': '96',
'gray': '37',
'grayer': '90',
'white': '97',
}.get(color_fg, '39')
color_bg = {
'black': '40',
'red': '41',
'reder': '101',
'green': '42',
'greener': '102',
'yellow': '43',
'yellower': '103',
'blue': '44',
'bluer': '104',
'magenta': '45',
'magenter': '105',
'cyan': '46',
'cyaner': '106',
'gray': '47',
'grayer': '100',
'white': '107',
}.get(color_bg, '49')
mod = ';'.join([color_fg, color_bg])
text = '%(esc)s[%(mod)sm%(value)s%(end)s' % {
'esc': Section.vars.FORMAT_ESCAPE,
'end': Section.vars.FORMAT_END,
'mod': mod,
'value': text,
}
return text |
<SYSTEM_TASK:>
Iterates configuration sections groups options.
<END_TASK>
<USER_TASK:>
Description:
def iter_options(self):
"""Iterates configuration sections groups options.""" |
for section in self.sections:
name = str(section)
for key, value in section._get_options():
yield name, key, value |
<SYSTEM_TASK:>
Set memory related parameters.
<END_TASK>
<USER_TASK:>
Description:
def set_memory_params(self, ksm_interval=None, no_swap=None):
"""Set memory related parameters.
:param int ksm_interval: Kernel Samepage Merging frequency option, that can reduce memory usage.
Accepts a number of requests (or master process cycles) to run page scanner after.
.. note:: Linux only.
* http://uwsgi.readthedocs.io/en/latest/KSM.html
:param bool no_swap: Lock all memory pages avoiding swapping.
""" |
self._set('ksm', ksm_interval)
self._set('never_swap', no_swap, cast=bool)
return self._section |
<SYSTEM_TASK:>
Daemonize uWSGI.
<END_TASK>
<USER_TASK:>
Description:
def daemonize(self, log_into, after_app_loading=False):
"""Daemonize uWSGI.
:param str|unicode log_into: Logging destination:
* File: /tmp/mylog.log
* UPD: 192.168.1.2:1717
.. note:: This will require an UDP server to manage log messages.
Use ``networking.register_socket('192.168.1.2:1717, type=networking.SOCK_UDP)``
to start uWSGI UDP server.
:param str|unicode bool after_app_loading: Whether to daemonize after
or before applications loading.
""" |
self._set('daemonize2' if after_app_loading else 'daemonize', log_into)
return self._section |
<SYSTEM_TASK:>
Chdir to specified directory before or after apps loading.
<END_TASK>
<USER_TASK:>
Description:
def change_dir(self, to, after_app_loading=False):
"""Chdir to specified directory before or after apps loading.
:param str|unicode to: Target directory.
:param bool after_app_loading:
*True* - after load
*False* - before load
""" |
self._set('chdir2' if after_app_loading else 'chdir', to)
return self._section |
<SYSTEM_TASK:>
Set process owner params - user, group.
<END_TASK>
<USER_TASK:>
Description:
def set_owner_params(self, uid=None, gid=None, add_gids=None, set_asap=False):
"""Set process owner params - user, 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.
:param list|str|unicode|int add_gids: Add the specified group id to the process credentials.
This options allows you to add additional group ids to the current process.
You can specify it multiple times.
:param bool set_asap: Set as soon as possible.
Setting them on top of your vassal file will force the instance to setuid()/setgid()
as soon as possible and without the (theoretical) possibility to override them.
""" |
prefix = 'immediate-' if set_asap else ''
self._set(prefix + 'uid', uid)
self._set(prefix + 'gid', gid)
self._set('add-gid', add_gids, multi=True)
# This may be wrong for subsequent method calls.
self.owner = [uid, gid]
return self._section |
<SYSTEM_TASK:>
Allows running certain action when the specified file is touched.
<END_TASK>
<USER_TASK:>
Description:
def set_hook_touch(self, fpath, action):
"""Allows running certain action when the specified file is touched.
:param str|unicode fpath: File path.
:param str|unicode|list|HookAction|list[HookAction] action:
""" |
self._set('hook-touch', '%s %s' % (fpath, action), multi=True)
return self._section |
<SYSTEM_TASK:>
Set params related to process exit procedure.
<END_TASK>
<USER_TASK:>
Description:
def set_on_exit_params(self, skip_hooks=None, skip_teardown=None):
"""Set params related to process exit procedure.
:param bool skip_hooks: Skip ``EXIT`` phase hook.
.. note:: Ignored by the master.
:param bool skip_teardown: Allows skipping teardown (finalization) processes for some plugins.
.. note:: Ignored by the master.
Supported by:
* Perl
* Python
""" |
self._set('skip-atexit', skip_hooks, cast=bool)
self._set('skip-atexit-teardown', skip_teardown, cast=bool)
return self._section |
<SYSTEM_TASK:>
Run the given command on a given phase.
<END_TASK>
<USER_TASK:>
Description:
def run_command_on_event(self, command, phase=phases.ASAP):
"""Run the given command on a given phase.
:param str|unicode command:
:param str|unicode phase: See constants in ``Phases`` class.
""" |
self._set('exec-%s' % phase, command, multi=True)
return self._section |
<SYSTEM_TASK:>
Creates pidfile before or after privileges drop.
<END_TASK>
<USER_TASK:>
Description:
def set_pid_file(self, fpath, before_priv_drop=True, safe=False):
"""Creates pidfile before or after privileges drop.
:param str|unicode fpath: File path.
:param bool before_priv_drop: Whether to create pidfile before privileges are dropped.
.. note:: Vacuum is made after privileges drop, so it may not be able
to delete PID file if it was created before dropping.
:param bool safe: The safe-pidfile works similar to pidfile
but performs the write a little later in the loading process.
This avoids overwriting the value when app loading fails,
with the consequent loss of a valid PID number.
""" |
command = 'pidfile'
if not before_priv_drop:
command += '2'
if safe:
command = 'safe-' + command
self._set(command, fpath)
return self._section |
<SYSTEM_TASK:>
Setups processes naming parameters.
<END_TASK>
<USER_TASK:>
Description:
def set_naming_params(self, autonaming=None, prefix=None, suffix=None, name=None):
"""Setups processes naming parameters.
:param bool autonaming: Automatically set process name to something meaningful.
Generated process names may be 'uWSGI Master', 'uWSGI Worker #', etc.
:param str|unicode prefix: Add prefix to process names.
:param str|unicode suffix: Append string to process names.
:param str|unicode name: Set process names to given static value.
""" |
self._set('auto-procname', autonaming, cast=bool)
self._set('procname-prefix%s' % ('-spaced' if prefix and prefix.endswith(' ') else ''), prefix)
self._set('procname-append', suffix)
self._set('procname', name)
return self._section |
<SYSTEM_TASK:>
Runs uWSGI passing to it using the default or another `uwsgiconf` configuration module.
<END_TASK>
<USER_TASK:>
Description:
def run(conf, only):
"""Runs uWSGI passing to it using the default or another `uwsgiconf` configuration module.
""" |
with errorprint():
config = ConfModule(conf)
spawned = config.spawn_uwsgi(only)
for alias, pid in spawned:
click.secho("Spawned uWSGI for configuration aliased '%s'. PID %s" % (alias, pid), fg='green') |
<SYSTEM_TASK:>
Compiles classic uWSGI configuration file using the default
<END_TASK>
<USER_TASK:>
Description:
def compile(conf):
"""Compiles classic uWSGI configuration file using the default
or given `uwsgiconf` configuration module.
""" |
with errorprint():
config = ConfModule(conf)
for conf in config.configurations:
conf.format(do_print=True) |
<SYSTEM_TASK:>
Outputs configuration for system initialization subsystem.
<END_TASK>
<USER_TASK:>
Description:
def sysinit(systype, conf, project):
"""Outputs configuration for system initialization subsystem.""" |
click.secho(get_config(
systype,
conf=ConfModule(conf).configurations[0],
conf_path=conf,
project_name=project,
)) |
<SYSTEM_TASK:>
Runs uWSGI to determine what plugins are available and prints them out.
<END_TASK>
<USER_TASK:>
Description:
def probe_plugins():
"""Runs uWSGI to determine what plugins are available and prints them out.
Generic plugins come first then after blank line follow request plugins.
""" |
plugins = UwsgiRunner().get_plugins()
for plugin in sorted(plugins.generic):
click.secho(plugin)
click.secho('')
for plugin in sorted(plugins.request):
click.secho(plugin) |
<SYSTEM_TASK:>
Decorator for a function to be used as a signal handler.
<END_TASK>
<USER_TASK:>
Description:
def register_handler(self, target=None):
"""Decorator for a function to be used as a signal handler.
:param str|unicode target: Where this signal will be delivered to. Default: ``worker``.
* ``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
* http://uwsgi.readthedocs.io/en/latest/Signals.html#signals-targets
""" |
target = target or 'worker'
sign_num = self.num
def wrapper(func):
_LOG.debug("Registering '%s' as signal '%s' handler ...", func.__name__, sign_num)
uwsgi.register_signal(sign_num, target, func)
return func
return wrapper |
<SYSTEM_TASK:>
Run a spooler on the specified directory.
<END_TASK>
<USER_TASK:>
Description:
def add(self, work_dir, external=False):
"""Run a spooler on the specified directory.
:param str|unicode work_dir:
.. note:: Placeholders can be used to build paths, e.g.: {project_runtime_dir}/spool/
See ``Section.project_name`` and ``Section.runtime_dir``.
:param bool external: map spoolers requests to a spooler directory managed by an external instance
""" |
command = 'spooler'
if external:
command += '-external'
self._set(command, self._section.replace_placeholders(work_dir), multi=True)
return self._section |
<SYSTEM_TASK:>
Configures broodlord mode and returns emperor and zerg sections.
<END_TASK>
<USER_TASK:>
Description:
def configure(self):
"""Configures broodlord mode and returns emperor and zerg sections.
:rtype: tuple
""" |
section_emperor = self.section_emperor
section_zerg = self.section_zerg
socket = self.socket
section_emperor.workers.set_zerg_server_params(socket=socket)
section_emperor.empire.set_emperor_params(vassals_home=self.vassals_home)
section_emperor.empire.set_mode_broodlord_params(**self.broodlord_params)
section_zerg.name = 'zerg'
section_zerg.workers.set_zerg_client_params(server_sockets=socket)
if self.die_on_idle:
section_zerg.master_process.set_idle_params(timeout=30, exit=True)
return section_emperor, section_zerg |
<SYSTEM_TASK:>
Returns default log message format.
<END_TASK>
<USER_TASK:>
Description:
def get_log_format_default(self):
"""Returns default log message format.
.. note:: Some params may be missing.
""" |
vars = self.logging.vars
format_default = (
'[pid: %s|app: %s|req: %s/%s] %s (%s) {%s vars in %s bytes} [%s] %s %s => '
'generated %s bytes in %s %s%s(%s %s) %s headers in %s bytes (%s switches on core %s)' % (
vars.WORKER_PID,
'-', # app id
'-', # app req count
'-', # worker req count
vars.REQ_REMOTE_ADDR,
vars.REQ_REMOTE_USER,
vars.REQ_COUNT_VARS_CGI,
vars.SIZE_PACKET_UWSGI,
vars.REQ_START_CTIME,
vars.REQ_METHOD,
vars.REQ_URI,
vars.RESP_SIZE_BODY,
vars.RESP_TIME_MS, # or RESP_TIME_US,
'-', # tsize
'-', # via sendfile/route/offload
vars.REQ_SERVER_PROTOCOL,
vars.RESP_STATUS,
vars.RESP_COUNT_HEADERS,
vars.RESP_SIZE_HEADERS,
vars.ASYNC_SWITCHES,
vars.CORE,
))
return format_default |
<SYSTEM_TASK:>
Shortcut to set process owner data.
<END_TASK>
<USER_TASK:>
Description:
def configure_owner(self, owner='www-data'):
"""Shortcut to set process owner data.
:param str|unicode owner: Sets user and group. Default: ``www-data``.
""" |
if owner is not None:
self.main_process.set_owner_params(uid=owner, gid=owner)
return self |
<SYSTEM_TASK:>
Triggers the alarm when the specified file descriptor is ready for read.
<END_TASK>
<USER_TASK:>
Description:
def alarm_on_fd_ready(self, alarm, fd, message, byte_count=None):
"""Triggers the alarm when the specified file descriptor is ready for read.
This is really useful for integration with the Linux eventfd() facility.
Pretty low-level and the basis of most of the alarm plugins.
* http://uwsgi-docs.readthedocs.io/en/latest/Changelog-1.9.7.html#alarm-fd
:param AlarmType|list[AlarmType] alarm: Alarm.
:param str|unicode fd: File descriptor.
:param str|unicode message: Message to send.
:param int byte_count: Files to read. Default: 1 byte.
.. note:: For ``eventfd`` set 8.
""" |
self.register_alarm(alarm)
value = fd
if byte_count:
value += ':%s' % byte_count
value += ' %s' % message
for alarm in listify(alarm):
self._set('alarm-fd', '%s %s' % (alarm.alias, value), multi=True)
return self._section |
<SYSTEM_TASK:>
Raise the specified alarm when the segmentation fault handler is executed.
<END_TASK>
<USER_TASK:>
Description:
def alarm_on_segfault(self, alarm):
"""Raise the specified alarm when the segmentation fault handler is executed.
Sends a backtrace.
:param AlarmType|list[AlarmType] alarm: Alarm.
""" |
self.register_alarm(alarm)
for alarm in listify(alarm):
self._set('alarm-segfault', alarm.alias, multi=True)
return self._section |
<SYSTEM_TASK:>
Returns init system configuration file contents.
<END_TASK>
<USER_TASK:>
Description:
def get_config(systype, conf, conf_path, runner=None, project_name=None):
"""Returns init system configuration file contents.
:param str|unicode systype: System type alias, e.g. systemd, upstart
:param Section|Configuration conf: Configuration/Section object.
:param str|unicode conf_path: File path to a configuration file or a command producing such a configuration.
:param str|unicode runner: Runner command to execute conf_path. Defaults to ``uwsgiconf`` runner.
:param str|unicode project_name: Project name to override.
:rtype: str|unicode
""" |
runner = runner or ('%s run' % Finder.uwsgiconf())
conf_path = abspath(conf_path)
if isinstance(conf, Configuration):
conf = conf.sections[0] # todo Maybe something more intelligent.
tpl = dedent(TEMPLATES.get(systype)(conf=conf))
formatted = tpl.strip().format(
project=project_name or conf.project_name or basename(dirname(conf_path)),
command='%s %s' % (runner, conf_path),
)
return formatted |
<SYSTEM_TASK:>
This is simple WSGI application that will be served by uWSGI.
<END_TASK>
<USER_TASK:>
Description:
def app_1(env, start_response):
"""This is simple WSGI application that will be served by uWSGI.""" |
from uwsgiconf.runtime.environ import uwsgi_env
start_response('200 OK', [('Content-Type','text/html')])
data = [
'<h1>uwsgiconf demo: one file</h1>',
'<div>uWSGI version: %s</div>' % uwsgi_env.get_version(),
'<div>uWSGI request ID: %s</div>' % uwsgi_env.request.id,
]
return encode(data) |
<SYSTEM_TASK:>
This is another simple WSGI application that will be served by uWSGI.
<END_TASK>
<USER_TASK:>
Description:
def app_2(env, start_response):
"""This is another simple WSGI application that will be served by uWSGI.""" |
import random
start_response('200 OK', [('Content-Type','text/html')])
data = [
'<h1>uwsgiconf demo: one file second app</h1>',
'<div>Some random number for you: %s</div>' % random.randint(1, 99999),
]
return encode(data) |
<SYSTEM_TASK:>
Configure uWSGI.
<END_TASK>
<USER_TASK:>
Description:
def configure():
"""Configure uWSGI.
This returns several configuration objects, which will be used
to spawn several uWSGI processes.
Applications are on 127.0.0.1 on ports starting from 8000.
""" |
import os
from uwsgiconf.presets.nice import PythonSection
FILE = os.path.abspath(__file__)
port = 8000
configurations = []
for idx in range(2):
alias = 'app_%s' % (idx + 1)
section = PythonSection(
# Automatically reload uWSGI if this file is changed.
touch_reload=FILE,
# To differentiate easily.
process_prefix=alias,
# Serve WSGI application (see above) from this very file.
wsgi_module=FILE,
# Custom WSGI callable for second app.
wsgi_callable=alias,
# One is just enough, no use in worker on every core
# for this demo.
workers=1,
).networking.register_socket(
PythonSection.networking.sockets.http('127.0.0.1:%s' % port)
)
port += 1
configurations.append(
# We give alias for configuration to prevent clashes.
section.as_configuration(alias=alias))
return configurations |
<SYSTEM_TASK:>
Simple file or UDP logging.
<END_TASK>
<USER_TASK:>
Description:
def log_into(self, target, before_priv_drop=True):
"""Simple file or UDP logging.
.. note:: This doesn't require any Logger plugin and can be used
if no log routing is required.
:param str|unicode target: Filepath or UDP address.
:param bool before_priv_drop: Whether to log data before or after privileges drop.
""" |
command = 'logto'
if not before_priv_drop:
command += '2'
self._set(command, target)
return self._section |
<SYSTEM_TASK:>
Set various parameters related to file logging.
<END_TASK>
<USER_TASK:>
Description:
def set_file_params(
self, reopen_on_reload=None, trucate_on_statup=None, max_size=None, rotation_fname=None,
touch_reopen=None, touch_rotate=None, owner=None, mode=None):
"""Set various parameters related to file logging.
:param bool reopen_on_reload: Reopen log after reload.
:param bool trucate_on_statup: Truncate log on startup.
:param int max_size: Set maximum logfile size in bytes after which log should be rotated.
:param str|unicode rotation_fname: Set log file name after rotation.
:param str|unicode|list touch_reopen: Trigger log reopen if the specified file
is modified/touched.
.. note:: This can be set to a file touched by ``postrotate`` script of ``logrotate``
to implement rotation.
:param str|unicode|list touch_rotate: Trigger log rotation if the specified file
is modified/touched.
:param str|unicode owner: Set owner chown() for logs.
:param str|unicode mode: Set mode chmod() for logs.
""" |
self._set('log-reopen', reopen_on_reload, cast=bool)
self._set('log-truncate', trucate_on_statup, cast=bool)
self._set('log-maxsize', max_size)
self._set('log-backupname', rotation_fname)
self._set('touch-logreopen', touch_reopen, multi=True)
self._set('touch-logrotate', touch_rotate, multi=True)
self._set('logfile-chown', owner)
self._set('logfile-chmod', mode)
return self._section |
<SYSTEM_TASK:>
Sets logging params for delegating logging to master process.
<END_TASK>
<USER_TASK:>
Description:
def set_master_logging_params(
self, enable=None, dedicate_thread=None, buffer=None,
sock_stream=None, sock_stream_requests_only=None):
"""Sets logging params for delegating logging to master process.
:param bool enable: Delegate logging to master process.
Delegate the write of the logs to the master process
(this will put all of the logging I/O to a single process).
Useful for system with advanced I/O schedulers/elevators.
:param bool dedicate_thread: Delegate log writing to a thread.
As error situations could cause the master to block while writing
a log line to a remote server, it may be a good idea to use this option and delegate
writes to a secondary thread.
:param int buffer: Set the buffer size for the master logger in bytes.
Bigger log messages will be truncated.
:param bool|tuple sock_stream: Create the master logpipe as SOCK_STREAM.
:param bool|tuple sock_stream_requests_only: Create the master requests logpipe as SOCK_STREAM.
""" |
self._set('log-master', enable, cast=bool)
self._set('threaded-logger', dedicate_thread, cast=bool)
self._set('log-master-bufsize', buffer)
self._set('log-master-stream', sock_stream, cast=bool)
if sock_stream_requests_only:
self._set('log-master-req-stream', sock_stream_requests_only, cast=bool)
return self._section |
<SYSTEM_TASK:>
Log to the specified named logger if regexp applied on log item matches.
<END_TASK>
<USER_TASK:>
Description:
def add_logger_route(self, logger, matcher, requests_only=False):
"""Log to the specified named logger if regexp applied on log item matches.
:param str|unicode|list|Logger|list[Logger] logger: Logger to associate route with.
:param str|unicode matcher: Regular expression to apply to log item.
:param bool requests_only: Matching should be used only for requests information messages.
""" |
command = 'log-req-route' if requests_only else 'log-route'
for logger in listify(logger):
self._set(command, '%s %s' % (logger, matcher), multi=True)
return self._section |
<SYSTEM_TASK:>
Add an item in the log encoder or request encoder chain.
<END_TASK>
<USER_TASK:>
Description:
def add_logger_encoder(self, encoder, logger=None, requests_only=False, for_single_worker=False):
"""Add an item in the log encoder or request encoder chain.
* http://uwsgi-docs.readthedocs.io/en/latest/LogEncoders.html
.. note:: Encoders automatically enable master log handling (see ``.set_master_logging_params()``).
.. note:: For best performance consider allocating a thread
for log sending with ``dedicate_thread``.
:param str|unicode|list|Encoder encoder: Encoder (or a list) to add into processing.
:param str|unicode|Logger logger: Logger apply associate encoders to.
:param bool requests_only: Encoder to be used only for requests information messages.
:param bool for_single_worker: Encoder to be used in single-worker setup.
""" |
if for_single_worker:
command = 'worker-log-req-encoder' if requests_only else 'worker-log-encoder'
else:
command = 'log-req-encoder' if requests_only else 'log-encoder'
for encoder in listify(encoder):
value = '%s' % encoder
if logger:
if isinstance(logger, Logger):
logger = logger.alias
value += ':%s' % logger
self._set(command, value, multi=True)
return self._section |
<SYSTEM_TASK:>
Sets basic Metrics subsystem params.
<END_TASK>
<USER_TASK:>
Description:
def set_metrics_params(self, enable=None, store_dir=None, restore=None, no_cores=None):
"""Sets basic Metrics subsystem params.
uWSGI metrics subsystem allows you to manage "numbers" from your apps.
When enabled, the subsystem configures a vast amount of metrics
(like requests per-core, memory usage, etc) but, in addition to this,
you can configure your own metrics, such as the number of active users or, say,
hits of a particular URL, as well as the memory consumption of your app or the whole server.
* http://uwsgi.readthedocs.io/en/latest/Metrics.html
* SNMP Integration - http://uwsgi.readthedocs.io/en/latest/Metrics.html#snmp-integration
:param bool enable: Enables the subsystem.
:param str|unicode store_dir: Directory to store metrics.
The metrics subsystem can expose all of its metrics in the form
of text files in a directory. The content of each file is the value
of the metric (updated in real time).
.. note:: Placeholders can be used to build paths, e.g.: {project_runtime_dir}/metrics/
See ``Section.project_name`` and ``Section.runtime_dir``.
:param bool restore: Restore previous metrics from ``store_dir``.
When you restart a uWSGI instance, all of its metrics are reset.
Use the option to force the metric subsystem to read-back the values
from the metric directory before starting to collect values.
:param bool no_cores: Disable generation of cores-related metrics.
""" |
self._set('enable-metrics', enable, cast=bool)
self._set('metrics-dir', self._section.replace_placeholders(store_dir))
self._set('metrics-dir-restore', restore, cast=bool)
self._set('metrics-no-cores', no_cores, cast=bool)
return self._section |
<SYSTEM_TASK:>
Sets metric threshold parameters.
<END_TASK>
<USER_TASK:>
Description:
def set_metrics_threshold(self, name, value, check_interval=None, reset_to=None, alarm=None, alarm_message=None):
"""Sets metric threshold parameters.
:param str|unicode name: Metric name.
:param int value: Threshold value.
:param int reset_to: Reset value to when threshold is reached.
:param int check_interval: Threshold check interval in seconds.
:param str|unicode|AlarmType alarm: Alarm to trigger when threshold is reached.
:param str|unicode alarm_message: Message to pass to alarm. If not set metrics name is passed.
""" |
if alarm is not None and isinstance(alarm, AlarmType):
self._section.alarms.register_alarm(alarm)
alarm = alarm.alias
value = KeyValue(
locals(),
aliases={
'name': 'key',
'reset_to': 'reset',
'check_interval': 'rate',
'alarm_message': 'msg',
},
)
self._set('metric-threshold', value, multi=True)
return self._section |
<SYSTEM_TASK:>
Enables stats server on the specified address.
<END_TASK>
<USER_TASK:>
Description:
def set_stats_params(
self, address=None, enable_http=None,
minify=None, no_cores=None, no_metrics=None, push_interval=None):
"""Enables stats server on the specified address.
* http://uwsgi.readthedocs.io/en/latest/StatsServer.html
:param str|unicode address: Address/socket to make stats available on.
Examples:
* 127.0.0.1:1717
* /tmp/statsock
* :5050
:param bool enable_http: Server stats over HTTP.
Prefixes stats server json output with http headers.
:param bool minify: Minify statistics json output.
:param bool no_cores: Disable generation of cores-related stats.
:param bool no_metrics: Do not include metrics in stats output.
:param int push_interval: Set the default frequency of stats pushers in seconds/
""" |
self._set('stats-server', address)
self._set('stats-http', enable_http, cast=bool)
self._set('stats-minified', minify, cast=bool)
self._set('stats-no-cores', no_cores, cast=bool)
self._set('stats-no-metrics', no_metrics, cast=bool)
self._set('stats-pusher-default-freq', push_interval)
return self._section |
<SYSTEM_TASK:>
Enables SNMP.
<END_TASK>
<USER_TASK:>
Description:
def enable_snmp(self, address, community_string):
"""Enables SNMP.
uWSGI server embeds a tiny SNMP server that you can use to integrate
your web apps with your monitoring infrastructure.
* http://uwsgi.readthedocs.io/en/latest/SNMP.html
.. note:: SNMP server is started in the master process after dropping the privileges.
If you want it to listen on a privileged port, you can either use Capabilities on Linux,
or use the ``as-root`` option to run the master process as root.
:param str|unicode address: UDP address to bind to.
Examples:
* 192.168.1.1:2222
:param str|unicode community_string: SNMP instance identifier to address it.
""" |
self._set('snmp', address)
self._set('snmp-community', community_string)
return self._section |
<SYSTEM_TASK:>
Load application under mountpoint.
<END_TASK>
<USER_TASK:>
Description:
def mount(self, mountpoint, app, into_worker=False):
"""Load application under mountpoint.
Example:
* .mount('', 'app0.py') -- Root URL part
* .mount('/app1', 'app1.py') -- URL part
* .mount('/pinax/here', '/var/www/pinax/deploy/pinax.wsgi')
* .mount('the_app3', 'app3.py') -- Variable value: application alias (can be set by ``UWSGI_APPID``)
* .mount('example.com', 'app2.py') -- Variable value: Hostname (variable set in nginx)
* http://uwsgi-docs.readthedocs.io/en/latest/Nginx.html#hosting-multiple-apps-in-the-same-process-aka-managing-script-name-and-path-info
:param str|unicode mountpoint: URL part, or variable value.
.. note:: In case of URL part you may also want to set ``manage_script_name`` basic param to ``True``.
.. warning:: In case of URL part a trailing slash may case problems in some cases
(e.g. with Django based projects).
:param str|unicode app: App module/file.
:param bool into_worker: Load application under mountpoint
in the specified worker or after workers spawn.
""" |
# todo check worker mount -- uwsgi_init_worker_mount_app() expects worker://
self._set('worker-mount' if into_worker else 'mount', '%s=%s' % (mountpoint, app), multi=True)
return self._section |
<SYSTEM_TASK:>
Load apps in workers instead of master.
<END_TASK>
<USER_TASK:>
Description:
def switch_into_lazy_mode(self, affect_master=None):
"""Load apps in workers instead of master.
This option may have memory usage implications
as Copy-on-Write semantics can not be used.
.. note:: Consider using ``touch_chain_reload`` option in ``workers`` basic params
for lazy apps reloading.
:param bool affect_master: If **True** only workers will be
reloaded by uWSGI's reload signals; the master will remain alive.
.. warning:: uWSGI configuration changes are not picked up on reload by the master.
""" |
self._set('lazy' if affect_master else 'lazy-apps', True, cast=bool)
return self._section |
<SYSTEM_TASK:>
Allows enabling various automatic management mechanics.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Drop http router privileges to specified user and group.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Sets buffering params.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Adds a routing rule to the tuntap router.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Adds a tuntap device rule.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Adds a firewall rule to the router.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Allows configuring uWSGI using Configuration objects returned
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Prints out a stamp containing useful information,
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Prints out the given value.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Prints out magic variables available in config files
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Sets plugin-related parameters.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Sets a fallback configuration for section.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Placeholders are custom magic variables defined during configuration
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Includes target contents into config.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Creates a new section based on the given.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Validates sections types and uniqueness.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Applies formatting to configuration.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Saves configuration into a file and returns its path.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Sets ``sys.argv`` for python apps.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Set wsgi related parameters.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Sets autoreload related parameters.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Imports a python module.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Sets subscription server related params.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Sets peer verification params for subscription server.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Sets subscribers related params.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Registers a subscription intent.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Runs up the stack to find the location of manage.py
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Runs uWSGI using the given section configuration.
<END_TASK>
<USER_TASK:>
Description:
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]) |
<SYSTEM_TASK:>
Alternative constructor. Creates a mutator and returns section object.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Contributes static and media file serving settings to an existing section.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Contributes generic static error massage pages to an existing section.
<END_TASK>
<USER_TASK:>
Description:
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')) |
<SYSTEM_TASK:>
Sets metric value.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Block until a mule message is received and return it.
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Parses ``plugin-list`` command output from uWSGI
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Returns attributes difference two elements tuple between
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Allows managing of uWSGI log related stuff
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Reloads uWSGI master process, workers.
<END_TASK>
<USER_TASK:>
Description:
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') |
<SYSTEM_TASK:>
Sends a generic command into FIFO.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Prepares current environment and returns Python binary name.
<END_TASK>
<USER_TASK:>
Description:
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()) |
<SYSTEM_TASK:>
Spawns uWSGI using the given configuration module.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Gets a value from the cache.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Sets the specified key value.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Decrements the specified key value by the specified value.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Multiplies the specified key value by the specified value.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Divides the specified key value by the specified value.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Receives data from websocket.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Sends a message to websocket.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Add an item into the given cache.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Load a static file in the cache.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Add timer.
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Adds cron. The interface to the uWSGI signal cron facility.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Truncate a line to the specified length followed by ``...`` unless its shorter than length already.
<END_TASK>
<USER_TASK:>
Description:
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] + "..." |
<SYSTEM_TASK:>
Execute pyle with the specified arguments, or sys.argv if no arguments specified.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Initializes and returns the login form component
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Adds a comment line to the query to be executed containing the line number of the calling
<END_TASK>
<USER_TASK:>
Description:
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, |
<SYSTEM_TASK:>
Returns an instance of class_type populated with attributes from the DB record; throws an error if no
<END_TASK>
<USER_TASK:>
Description:
def get_single_instance(sql, class_type, *args, **kwargs):
"""Returns an instance of class_type populated with attributes from the DB record; throws an error if no
records are found
@param sql: Sql statement to execute
@param class_type: The type of class to instantiate and populate with DB record
@return: Return an instance with attributes set to values from DB
""" |
record = CoyoteDb.get_single_record(sql, *args, **kwargs)
try:
instance = CoyoteDb.get_object_from_dictionary_representation(dictionary=record, class_type=class_type)
except AttributeError:
raise NoRecordsFoundException('No records found for {class_type} with sql run on {host}: \n {sql}'.format(
sql=sql,
host=DatabaseConfig().get('mysql_host'),
class_type=class_type
))
return instance |
<SYSTEM_TASK:>
Returns a list of instances of class_type populated with attributes from the DB record
<END_TASK>
<USER_TASK:>
Description:
def get_all_instances(sql, class_type, *args, **kwargs):
"""Returns a list of instances of class_type populated with attributes from the DB record
@param sql: Sql statement to execute
@param class_type: The type of class to instantiate and populate with DB record
@return: Return a list of instances with attributes set to values from DB
""" |
records = CoyoteDb.get_all_records(sql, *args, **kwargs)
instances = [CoyoteDb.get_object_from_dictionary_representation(
dictionary=record, class_type=class_type) for record in records]
for instance in instances:
instance._query = sql
return instances |
<SYSTEM_TASK:>
Escape dictionary values with keys as column names and values column values
<END_TASK>
<USER_TASK:>
Description:
def escape_dictionary(dictionary, datetime_format='%Y-%m-%d %H:%M:%S'):
"""Escape dictionary values with keys as column names and values column values
@type dictionary: dict
@param dictionary: Key-values
""" |
for k, v in dictionary.iteritems():
if isinstance(v, datetime.datetime):
v = v.strftime(datetime_format)
if isinstance(v, basestring):
v = CoyoteDb.db_escape(str(v))
v = '"{}"'.format(v)
if v is True:
v = 1
if v is False:
v = 0
if v is None:
v = 'NULL'
dictionary[k] = v |
<SYSTEM_TASK:>
Formats a dictionary to strings of fields and values for insert statements
<END_TASK>
<USER_TASK:>
Description:
def get_insert_fields_and_values_from_dict(dictionary, datetime_format='%Y-%m-%d %H:%M:%S', db_escape=True):
"""Formats a dictionary to strings of fields and values for insert statements
@param dictionary: The dictionary whose keys and values are to be inserted
@param db_escape: If true, will db escape values
@return: Tuple of strings containing string fields and values, e.g. ('user_id, username', '5, "pandaman"')
""" |
if db_escape:
CoyoteDb.escape_dictionary(dictionary, datetime_format=datetime_format)
fields = get_delimited_string_from_list(dictionary.keys(), delimiter=',') # keys have no quotes
vals = get_delimited_string_from_list(dictionary.values(), delimiter=',') # strings get quotes
return fields, vals |
<SYSTEM_TASK:>
This method should be used in query functions where user can query on any number of fields
<END_TASK>
<USER_TASK:>
Description:
def get_kwargs(**kwargs):
"""This method should be used in query functions where user can query on any number of fields
>>> def get_instances(entity_id=NOTSET, my_field=NOTSET):
>>> kwargs = CoyoteDb.get_kwargs(entity_id=entity_id, my_field=my_field)
""" |
d = dict()
for k, v in kwargs.iteritems():
if v is not NOTSET:
d[k] = v
return d |
<SYSTEM_TASK:>
Builds the update values clause of an update statement based on the dictionary representation of an
<END_TASK>
<USER_TASK:>
Description:
def get_update_clause_from_dict(dictionary, datetime_format='%Y-%m-%d %H:%M:%S'):
"""Builds the update values clause of an update statement based on the dictionary representation of an
instance""" |
items = []
CoyoteDb.escape_dictionary(dictionary, datetime_format=datetime_format)
for k,v in dictionary.iteritems():
item = '{k} = {v}'.format(k=k, v=v)
items.append(item)
clause = ', '.join(item for item in items)
return clause |
<SYSTEM_TASK:>
Builds a where clause from a dictionary
<END_TASK>
<USER_TASK:>
Description:
def get_where_clause_from_dict(dictionary, join_operator='AND'):
"""Builds a where clause from a dictionary
""" |
CoyoteDb.escape_dictionary(dictionary)
clause = join_operator.join(
(' {k} is {v} ' if str(v).lower() == 'null' else ' {k} = {v} ').format(k=k, v=v) # IS should be the operator for null values
for k, v in dictionary.iteritems())
return clause |
<SYSTEM_TASK:>
Returns a dictionary of object's attributes, ignoring methods
<END_TASK>
<USER_TASK:>
Description:
def get_dictionary_representation_of_object_attributes(obj, omit_null_fields=False):
"""Returns a dictionary of object's attributes, ignoring methods
@param obj: The object to represent as dict
@param omit_null_fields: If true, will not include fields in the dictionary that are null
@return: Dictionary of the object's attributes
""" |
obj_dictionary = obj.__dict__
obj_dictionary_temp = obj_dictionary.copy()
for k, v in obj_dictionary.iteritems():
if omit_null_fields:
if v is None:
obj_dictionary_temp.pop(k, None)
if k.startswith('_'):
obj_dictionary_temp.pop(k, None)
return obj_dictionary_temp |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.