signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def get(self, request, *args, **kwargs): | try:<EOL><INDENT>kwargs = self.load_object(kwargs)<EOL><DEDENT>except Exception as e:<EOL><INDENT>return self.render_te_response({<EOL>'<STR_LIT:title>': str(e),<EOL>})<EOL><DEDENT>if not self.has_permission(request):<EOL><INDENT>return self.render_te_response({<EOL>'<STR_LIT:title>': '<STR_LIT>',<EOL>})<EOL><DEDENT>return self.render_te_response(self.display_dialog(*args, **kwargs))<EOL> | Handle get request | f12963:c12:m0 |
def post(self, request, *args, **kwargs): | try:<EOL><INDENT>kwargs = self.load_object(kwargs)<EOL><DEDENT>except Exception as e:<EOL><INDENT>return self.render_te_response({<EOL>'<STR_LIT:title>': str(e),<EOL>})<EOL><DEDENT>if not self.has_permission(request):<EOL><INDENT>return self.render_te_response({<EOL>'<STR_LIT:title>': '<STR_LIT>',<EOL>})<EOL><DEDENT>return self.render_te_response(self.handle_dialog(*args, **kwargs))<EOL> | Handle post request | f12963:c12:m1 |
def load_object(self, kwargs): | self.object = None<EOL>self.config = None<EOL>self.model = self.get_model_class()<EOL>kwargs.pop('<STR_LIT>', None)<EOL>kwargs.pop('<STR_LIT>', None)<EOL>if self.model and kwargs.get('<STR_LIT>', False):<EOL><INDENT>try:<EOL><INDENT>self.object = self.model.objects.get(pk=kwargs.pop('<STR_LIT>'))<EOL><DEDENT>except Exception:<EOL><INDENT>raise Exception("<STR_LIT>".format(self.model.__name__.lower()))<EOL><DEDENT>setattr(self, self.model.__name__.lower(), self.object)<EOL><DEDENT>return kwargs<EOL> | Load object and model config and remove pk from kwargs | f12963:c12:m2 |
def has_permission(self, request): | if not self.object and not self.permission:<EOL><INDENT>return True<EOL><DEDENT>if not self.permission:<EOL><INDENT>return request.user.has_perm('<STR_LIT>'.format(<EOL>self.model_permission,<EOL>self.object.__class__.__name__.lower()), self.object<EOL>)<EOL><DEDENT>return request.user.has_perm(self.permission)<EOL> | Check if user has permission | f12963:c12:m3 |
def render_to_string(self, template_file, context): | context = context if context else {}<EOL>if self.object:<EOL><INDENT>context['<STR_LIT:object>'] = self.object<EOL>context[self.object.__class__.__name__.lower()] = self.object<EOL><DEDENT>return render_to_string(template_file, context, self.request)<EOL> | Render given template to string and add object to context | f12963:c12:m4 |
def display_dialog(self, *args, **kwargs): | return {}<EOL> | Override this function to display a dialog popup. Url params are given as function params.
The function must return a dict that can contain the following data:
- **title**: Title of the dialog
- **content**: Html content to display in dialog, shortcut function :class:`trionyx.trionyx.views.core.DialogView.render_to_string`
- **url (optional)**: Post url for dialog form, must be a link to a DialogView.
- **submit_label (optional)**: Label of the submit button, when empty submit button is not shown.
- **redirect_url (optional)**: Redirect page to given url.
- **close (optional)**: Close dialog. | f12963:c12:m5 |
def handle_dialog(self, *args, **kwargs): | return {}<EOL> | Override this function to handle and display popup. Url params are given as function params.
This function must return the same dict structure as :class:`trionyx.trionyx.views.core.DialogView.display_dialog`
Post data can be retrieved with *self.request.POST* | f12963:c12:m6 |
def render_te_response(self, data): | if '<STR_LIT>' in data and '<STR_LIT:url>' not in data:<EOL><INDENT>data['<STR_LIT:url>'] = self.request.get_full_path()<EOL><DEDENT>return JsonResponse(data)<EOL> | Render data to JsonResponse | f12963:c12:m7 |
def get_form_class(self): | <EOL>return self.get_model_config().get_edit_form()<EOL> | Get form class for dialog, default will get form from model config | f12963:c13:m0 |
def display_dialog(self, *args, **kwargs): | form = kwargs.pop('<STR_LIT>', None)<EOL>success_message = kwargs.pop('<STR_LIT>', None)<EOL>if not form:<EOL><INDENT>form = self.get_form_class()(initial=kwargs, instance=self.object)<EOL><DEDENT>if not hasattr(form, "<STR_LIT>"):<EOL><INDENT>form.helper = FormHelper()<EOL><DEDENT>form.helper.form_tag = False<EOL>return {<EOL>'<STR_LIT:title>': self.title.format(<EOL>model_name=self.get_model_config().model_name,<EOL>object=str(self.object) if self.object else '<STR_LIT>',<EOL>),<EOL>'<STR_LIT:content>': self.render_to_string(self.template, {<EOL>'<STR_LIT>': form,<EOL>'<STR_LIT>': success_message,<EOL>}),<EOL>'<STR_LIT>': self.submit_label,<EOL>'<STR_LIT:success>': bool(success_message),<EOL>}<EOL> | Display form and success message when set | f12963:c13:m1 |
def handle_dialog(self, *args, **kwargs): | form = self.get_form_class()(self.request.POST, initial=kwargs, instance=self.object)<EOL>success_message = None<EOL>if form.is_valid():<EOL><INDENT>obj = form.save()<EOL>success_message = self.success_message.format(<EOL>model_name=self.get_model_config().model_name.capitalize(),<EOL>object=str(obj),<EOL>)<EOL><DEDENT>return self.display_dialog(*args, form_instance=form, success_message=success_message, **kwargs)<EOL> | Handle form and save and set success message on valid form | f12963:c13:m2 |
def get_form_class(self): | <EOL>return self.get_model_config().get_create_form()<EOL> | Get create form class | f12963:c14:m0 |
def random_string(size): | return '<STR_LIT>'.join(random.choice(string.ascii_letters + string.digits) for _ in range(size))<EOL> | Create random string containing ascii leters and digits, with the length of given size | f12967:m0 |
def import_object_by_string(namespace): | segments = namespace.split('<STR_LIT:.>')<EOL>module = importlib.import_module('<STR_LIT:.>'.join(segments[:-<NUM_LIT:1>]))<EOL>return getattr(module, segments[-<NUM_LIT:1>])<EOL> | Import object by complete namespace | f12967:m1 |
def create_celerybeat_schedule(apps): | beat_schedule = {}<EOL>for app in apps:<EOL><INDENT>try:<EOL><INDENT>config = import_object_by_string(app)<EOL>module = importlib.import_module('<STR_LIT>'.format(config.name))<EOL><DEDENT>except Exception:<EOL><INDENT>try:<EOL><INDENT>module = importlib.import_module('<STR_LIT>'.format(app))<EOL><DEDENT>except Exception:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>if not (hasattr(module, '<STR_LIT>') and isinstance(module.schedule, dict)):<EOL><INDENT>logger.warning('<STR_LIT>'.format(module.__name__))<EOL>continue<EOL><DEDENT>for name, schedule in module.schedule.items():<EOL><INDENT>options = schedule.get('<STR_LIT>', {})<EOL>if '<STR_LIT>' not in options:<EOL><INDENT>options['<STR_LIT>'] = '<STR_LIT>'<EOL>schedule['<STR_LIT>'] = options<EOL>beat_schedule[name] = schedule<EOL><DEDENT><DEDENT><DEDENT>return beat_schedule<EOL> | Create Celery beat schedule by get schedule from every installed app | f12967:m2 |
def get_current_language(): | if translation.get_language():<EOL><INDENT>return translation.get_language()<EOL><DEDENT>return settings.LANGUAGE_CODE<EOL> | Get active language by django.utils.translation or return settings LANGUAGE_CODE | f12967:m3 |
def get_current_locale(): | return translation.to_locale(get_current_language())<EOL> | Get active locale based on get_current_language function | f12967:m4 |
def __init__(self, *args, **kwargs): | kwargs['<STR_LIT>'] = <NUM_LIT:11><EOL>kwargs['<STR_LIT>'] = <NUM_LIT:4><EOL>super().__init__(*args, **kwargs)<EOL> | Init PriceField | f12968:c0:m0 |
def get_queryset(self): | return super().get_queryset().filter(deleted=False)<EOL> | Give qeuryset where deleted items are filtered | f12968:c1:m0 |
@classmethod<EOL><INDENT>def get_fields(cls, inlcude_base=False, include_id=False):<DEDENT> | for field in cls._meta.fields:<EOL><INDENT>if field.name == '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>if not include_id and field.name == '<STR_LIT:id>':<EOL><INDENT>continue<EOL><DEDENT>if not inlcude_base and field.name in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>continue<EOL><DEDENT>yield field<EOL><DEDENT> | Get model fields | f12968:c2:m0 |
def __str__(self): | app_label = self._meta.app_label<EOL>model_name = type(self).__name__<EOL>verbose_name = models_config.get_config(self).verbose_name<EOL>return verbose_name.format(model_name=model_name, app_label=app_label, **self.__dict__)<EOL> | Give verbose name of object | f12968:c2:m1 |
def get_absolute_url(self): | return reverse('<STR_LIT>', kwargs={<EOL>'<STR_LIT>': self._meta.app_label,<EOL>'<STR_LIT>': self._meta.model_name,<EOL>'<STR_LIT>': self.id<EOL>})<EOL> | Get model url | f12968:c2:m2 |
def __init__(self, *components, **options): | self.object = False<EOL>self.components = list(components)<EOL>self.options = options<EOL> | Initialize Layout | f12969:c0:m0 |
def __getitem__(self, slice): | return self.components[slice]<EOL> | Get component item | f12969:c0:m1 |
def __setitem__(self, slice, value): | self.components[slice] = value<EOL> | Set component | f12969:c0:m2 |
def __delitem__(self, slice): | del self.components[slice]<EOL> | Delete component | f12969:c0:m3 |
def __len__(self): | return len(self.components)<EOL> | Get component length | f12969:c0:m4 |
def render(self, request=None): | return render_to_string('<STR_LIT>', {'<STR_LIT>': self}, request)<EOL> | Render layout for given request | f12969:c0:m5 |
def set_object(self, object): | if self.object is False:<EOL><INDENT>self.object = object<EOL><DEDENT>for component in self.components:<EOL><INDENT>component.set_object(self.object)<EOL><DEDENT> | Set object for rendering layout and set object to all components
:param object:
:return: | f12969:c0:m6 |
def add_component(self, component, after=None, before=None): | pass<EOL> | Add component to existing layout can insert component before or after component path
:param component:
:param after: component code path
:param before: component code path
:return: | f12969:c0:m7 |
def update_component(self, component_path, callback): | pass<EOL> | Update component with given path, calls callback with component
:param component_path:
:param callback:
:return: | f12969:c0:m8 |
def delete_component(self, component_path): | pass<EOL> | Delete component for given path
:param component_path:
:return: | f12969:c0:m9 |
def __init__(self, *components, **options): | self.id = options.get('<STR_LIT:id>')<EOL>self.components = list(components)<EOL>self.object = False<EOL>for key, value in options.items():<EOL><INDENT>setattr(self, key, value)<EOL><DEDENT> | Initialize Component | f12969:c1:m0 |
@cached_property<EOL><INDENT>def css_id(self):<DEDENT> | return '<STR_LIT>'.format(utils.random_string(<NUM_LIT:6>))<EOL> | Generate random css id for component | f12969:c1:m1 |
def set_object(self, object): | if self.object is False:<EOL><INDENT>self.object = object<EOL><DEDENT>for component in self.components:<EOL><INDENT>component.set_object(object)<EOL><DEDENT> | Set object for rendering component and set object to all components
:param object:
:return: | f12969:c1:m2 |
def render(self, context, request=None): | context['<STR_LIT>'] = self<EOL>return render_to_string(self.template_name, context, request)<EOL> | Render component | f12969:c1:m3 |
def get_fields(self): | if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.__fields = [<EOL>self.parse_field(field, index)<EOL>for index, field in enumerate(getattr(self, '<STR_LIT>', []))<EOL>]<EOL><DEDENT>return self.__fields<EOL> | Get all fields | f12969:c2:m0 |
def parse_field(self, field_data, index=<NUM_LIT:0>): | field = {<EOL>'<STR_LIT>': index,<EOL>}<EOL>if isinstance(field_data, str):<EOL><INDENT>field.update(self.parse_string_field(field_data))<EOL><DEDENT>elif isinstance(field_data, dict):<EOL><INDENT>field.update(field_data)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(type(field_data)))<EOL><DEDENT>if '<STR_LIT>' not in field:<EOL><INDENT>field['<STR_LIT>'] = None<EOL><DEDENT>if '<STR_LIT:label>' not in field and field['<STR_LIT>']:<EOL><INDENT>try:<EOL><INDENT>field['<STR_LIT:label>'] = self.object._meta.get_field(field['<STR_LIT>']).verbose_name.capitalize()<EOL><DEDENT>except Exception:<EOL><INDENT>field['<STR_LIT:label>'] = field['<STR_LIT>'].replace('<STR_LIT:_>', '<STR_LIT>').capitalize()<EOL><DEDENT><DEDENT>elif '<STR_LIT:label>' not in field:<EOL><INDENT>field['<STR_LIT:label>'] = '<STR_LIT>'<EOL><DEDENT>if '<STR_LIT>' not in field:<EOL><INDENT>field['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>for name, options in self.fields_options.items():<EOL><INDENT>if '<STR_LIT:default>' in options and name not in field:<EOL><INDENT>field[name] = options['<STR_LIT:default>']<EOL><DEDENT><DEDENT>return field<EOL> | Parse field and add missing options | f12969:c2:m1 |
def parse_string_field(self, field_data): | field_name, *data = field_data.split('<STR_LIT:=>', <NUM_LIT:1>)<EOL>field = {<EOL>'<STR_LIT>': field_name,<EOL>}<EOL>for option_string in '<STR_LIT>'.join(data).split('<STR_LIT:;>'):<EOL><INDENT>option, *value = option_string.split('<STR_LIT::>')<EOL>if option.strip():<EOL><INDENT>field[option.strip()] = value[<NUM_LIT:0>].strip() if value else True<EOL><DEDENT><DEDENT>return field<EOL> | Parse a string field to dict with options
String value is used as field name. Options can be given after = symbol.
Where key value is separated by : and different options by ;, when no : is used then the value becomes True.
**Example 1:** `field_name`
.. code-block:: python
# Output
{
'field': 'field_name'
}
**Example 3** `field_name=option1:some value;option2: other value`
.. code-block:: python
# Output
{
'field': 'field_name',
'option1': 'some value',
'option2': 'other value',
}
**Example 3** `field_name=option1;option2: other value`
.. code-block:: python
# Output
{
'field': 'field_name',
'option1': True,
'option2': 'other value',
}
:param str field_data:
:return dict: | f12969:c2:m2 |
def render_field(self, field, data): | from trionyx.renderer import renderer<EOL>if '<STR_LIT:value>' in field:<EOL><INDENT>value = field['<STR_LIT:value>']<EOL><DEDENT>elif isinstance(data, object) and hasattr(data, field['<STR_LIT>']):<EOL><INDENT>value = getattr(data, field['<STR_LIT>'])<EOL>if '<STR_LIT>' not in field:<EOL><INDENT>value = renderer.render_field(data, field['<STR_LIT>'], **field)<EOL><DEDENT><DEDENT>elif isinstance(data, dict) and field['<STR_LIT>'] in data:<EOL><INDENT>value = data.get(field['<STR_LIT>'])<EOL><DEDENT>elif isinstance(data, list) and field['<STR_LIT>'] < len(data):<EOL><INDENT>value = data[field['<STR_LIT>']]<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>options = {key: value for key, value in field.items() if key not in ['<STR_LIT:value>', '<STR_LIT>']}<EOL>if '<STR_LIT>' in field:<EOL><INDENT>value = field['<STR_LIT>'](value, data_object=data, **options)<EOL><DEDENT>else:<EOL><INDENT>value = renderer.render_value(value, data_object=data, **options)<EOL><DEDENT>return field['<STR_LIT>'].format(value)<EOL> | Render field for given data | f12969:c2:m3 |
def get_rendered_object(self, obj=None): | obj = obj if obj else self.object<EOL>return [<EOL>{<EOL>**field,<EOL>'<STR_LIT:value>': self.render_field(field, obj)<EOL>}<EOL>for field in self.get_fields()<EOL>]<EOL> | Render object | f12969:c2:m4 |
def get_rendered_objects(self): | objects = self.objects<EOL>if isinstance(objects, str):<EOL><INDENT>objects = getattr(self.object, objects).all()<EOL><DEDENT>return [<EOL>self.get_rendered_object(obj)<EOL>for obj in objects<EOL>]<EOL> | Render objects | f12969:c2:m5 |
def __init__(self, *args, **kwargs): | super().__init__(*args, **kwargs)<EOL>self.attr = self.attr if self.attr else {}<EOL> | Initialize HtmlTagWrapper | f12969:c3:m0 |
def get_attr_text(self): | return '<STR_LIT:U+0020>'.join([<EOL>'<STR_LIT>'.format(key, value)<EOL>for key, value in self.attr.items()<EOL>])<EOL> | Get html attr text to render in template | f12969:c3:m1 |
def __init__(self, html=None, **kwargs): | super().__init__(**kwargs)<EOL>self.html = html<EOL>for key, value in kwargs.items():<EOL><INDENT>if key in self.valid_attr:<EOL><INDENT>self.attr[key] = value<EOL><DEDENT><DEDENT> | Init Html | f12969:c4:m0 |
def __init__(self, *args, **kwargs): | super().__init__(*args, **kwargs)<EOL>self.attr['<STR_LIT:class>'] = '<STR_LIT:->'.join(x for x in ['<STR_LIT>', str(self.size), str(self.columns)] if x)<EOL> | Initialize Column | f12969:c8:m0 |
def __init__(self, title, *components, **options): | super().__init__(*components, **options)<EOL>self.title = title<EOL> | Init Panel | f12969:c20:m0 |
def __init__(self, *fields, **options): | super().__init__(**options)<EOL>self.fields = fields<EOL> | Init panel | f12969:c21:m0 |
def __init__(self, *fields, **options): | super().__init__(**options)<EOL>self.fields = fields<EOL> | Init panel | f12969:c22:m0 |
def __init__(self, objects, *fields, **options): | super().__init__(**options)<EOL>self.objects = objects<EOL>"""<STR_LIT>"""<EOL>self.fields = fields<EOL> | Init Table | f12969:c23:m0 |
def run_cmd(self, fifo, options): | raise NotImplementedError<EOL> | Must return FIFO command.
:param Fifo fifo:
:param dict options:
:rtype: bytes | f13024:c0:m0 |
def find_project_dir(): | frame = inspect.currentframe()<EOL>while True:<EOL><INDENT>frame = frame.f_back<EOL>fname = frame.f_globals['<STR_LIT>']<EOL>if os.path.basename(fname) == '<STR_LIT>':<EOL><INDENT>break<EOL><DEDENT><DEDENT>return os.path.dirname(fname)<EOL> | Runs up the stack to find the location of manage.py
which will be considered a project base path.
:rtype: str|unicode | f13031:m0 |
def get_project_name(project_dir): | return os.path.basename(project_dir)<EOL> | Return project name from project directory.
:param str|unicode project_dir:
:rtype: str|unicode | f13031:m1 |
def run_uwsgi(config_section, compile_only=False): | config = config_section.as_configuration()<EOL>if compile_only:<EOL><INDENT>config.print_ini()<EOL>return<EOL><DEDENT>config_path = config.tofile()<EOL>os.execvp('<STR_LIT>', ['<STR_LIT>', '<STR_LIT>' % config_path])<EOL> | 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. | f13031:m2 |
@property<EOL><INDENT>def runtime_dir(self):<DEDENT> | return self.section.replace_placeholders('<STR_LIT>')<EOL> | Project runtime directory.
:rtype: str | f13031:c0:m1 |
def get_pid_filepath(self): | return os.path.join(self.runtime_dir, '<STR_LIT>')<EOL> | Return pidfile path for the given project.
:param str|unicode project_name:
:rtype: str|unicode | f13031:c0:m2 |
def get_fifo_filepath(self): | return os.path.join(self.runtime_dir, '<STR_LIT>')<EOL> | Return master FIFO path for the given project.
:param str|unicode project_name:
:rtype: str|unicode | f13031:c0:m3 |
@classmethod<EOL><INDENT>def spawn(cls, options=None, dir_base=None):<DEDENT> | from uwsgiconf.utils import ConfModule<EOL>options = options or {<EOL>'<STR_LIT>': True,<EOL>}<EOL>dir_base = os.path.abspath(dir_base or find_project_dir())<EOL>name_module = ConfModule.default_name<EOL>name_project = get_project_name(dir_base)<EOL>path_conf = os.path.join(dir_base, name_module)<EOL>if os.path.exists(path_conf):<EOL><INDENT>section = cls._get_section_existing(name_module, name_project)<EOL><DEDENT>else:<EOL><INDENT>section = cls._get_section_new(dir_base)<EOL><DEDENT>mutator = cls(<EOL>section=section,<EOL>dir_base=dir_base,<EOL>project_name=name_project,<EOL>options=options)<EOL>mutator.mutate()<EOL>return mutator<EOL> | Alternative constructor. Creates a mutator and returns section object.
:param dict options:
:param str|unicode dir_base:
:rtype: SectionMutator | f13031:c0:m4 |
@classmethod<EOL><INDENT>def _get_section_existing(self, name_module, name_project):<DEDENT> | from importlib import import_module<EOL>from uwsgiconf.settings import CONFIGS_MODULE_ATTR<EOL>config = getattr(<EOL>import_module(os.path.splitext(name_module)[<NUM_LIT:0>], package=name_project),<EOL>CONFIGS_MODULE_ATTR)[<NUM_LIT:0>]<EOL>return config.sections[<NUM_LIT:0>]<EOL> | Loads config section from existing configuration file (aka uwsgicfg.py)
:param str|unicode name_module:
:param str|unicode name_project:
:rtype: Section | f13031:c0:m5 |
@classmethod<EOL><INDENT>def _get_section_new(cls, dir_base):<DEDENT> | from uwsgiconf.presets.nice import PythonSection<EOL>from django.conf import settings<EOL>wsgi_app = settings.WSGI_APPLICATION<EOL>path_wsgi, filename, _, = wsgi_app.split('<STR_LIT:.>')<EOL>path_wsgi = os.path.join(dir_base, path_wsgi, '<STR_LIT>' %filename)<EOL>section = PythonSection(<EOL>wsgi_module=path_wsgi,<EOL>).networking.register_socket(<EOL>PythonSection.networking.sockets.http('<STR_LIT>')<EOL>).main_process.change_dir(dir_base)<EOL>return section<EOL> | Creates a new section with default settings.
:param str|unicode dir_base:
:rtype: Section | f13031:c0:m6 |
def contribute_static(self): | options = self.options<EOL>if options['<STR_LIT>'] or not options['<STR_LIT>']:<EOL><INDENT>return<EOL><DEDENT>from django.core.management import call_command<EOL>settings = self.settings<EOL>statics = self.section.statics<EOL>statics.register_static_map(settings.STATIC_URL, settings.STATIC_ROOT)<EOL>statics.register_static_map(settings.MEDIA_URL, settings.MEDIA_ROOT)<EOL>call_command('<STR_LIT>', clear=True, interactive=False)<EOL> | Contributes static and media file serving settings to an existing section. | f13031:c0:m7 |
def contribute_error_pages(self): | static_dir = self.settings.STATIC_ROOT<EOL>if not static_dir:<EOL><INDENT>import tempfile<EOL>static_dir = os.path.join(tempfile.gettempdir(), self.project_name)<EOL>self.settings.STATIC_ROOT = static_dir<EOL><DEDENT>self.section.routing.set_error_pages(<EOL>common_prefix=os.path.join(static_dir, '<STR_LIT>'))<EOL> | Contributes generic static error massage pages to an existing section. | f13031:c0:m8 |
def mutate(self): | section = self.section<EOL>project_name = self.project_name<EOL>section.project_name = project_name<EOL>self.contribute_runtime_dir()<EOL>main = section.main_process<EOL>main.set_naming_params(prefix='<STR_LIT>' % project_name)<EOL>main.set_pid_file(<EOL>self.get_pid_filepath(),<EOL>before_priv_drop=False, <EOL>safe=True,<EOL>)<EOL>section.master_process.set_basic_params(<EOL>fifo_file=self.get_fifo_filepath(),<EOL>)<EOL>apps = section.applications<EOL>apps.set_basic_params(<EOL>manage_script_name=True,<EOL>)<EOL>self.contribute_error_pages()<EOL>self.contribute_static()<EOL> | Mutates current section. | f13031:c0:m10 |
def configure_uwsgi(configurator_func): | from .settings import ENV_CONF_READY, ENV_CONF_ALIAS, CONFIGS_MODULE_ATTR<EOL>if os.environ.get(ENV_CONF_READY):<EOL><INDENT>del os.environ[ENV_CONF_READY] <EOL>return None<EOL><DEDENT>configurations = configurator_func()<EOL>registry = OrderedDict()<EOL>if not isinstance(configurations, (list, tuple)):<EOL><INDENT>configurations = [configurations]<EOL><DEDENT>for conf_candidate in configurations:<EOL><INDENT>if not isinstance(conf_candidate, (Section, Configuration)):<EOL><INDENT>continue<EOL><DEDENT>if isinstance(conf_candidate, Section):<EOL><INDENT>conf_candidate = conf_candidate.as_configuration()<EOL><DEDENT>alias = conf_candidate.alias<EOL>if alias in registry:<EOL><INDENT>raise ConfigurationError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % alias)<EOL><DEDENT>registry[alias] = conf_candidate<EOL><DEDENT>if not registry:<EOL><INDENT>raise ConfigurationError(<EOL>"<STR_LIT>")<EOL><DEDENT>target_alias = os.environ.get(ENV_CONF_ALIAS)<EOL>if not target_alias:<EOL><INDENT>last = sys.argv[-<NUM_LIT:2>:]<EOL>if len(last) == <NUM_LIT:2> and last[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>target_alias = last[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>conf_list = list(registry.values())<EOL>if target_alias:<EOL><INDENT>config = registry.get(target_alias)<EOL>if config:<EOL><INDENT>section = config.sections[<NUM_LIT:0>] <EOL>os.environ[ENV_CONF_READY] = '<STR_LIT:1>'<EOL>section.set_placeholder('<STR_LIT>', target_alias)<EOL>config.print_ini()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>import inspect<EOL>config_module = inspect.currentframe().f_back<EOL>config_module.f_locals[CONFIGS_MODULE_ATTR] = conf_list<EOL><DEDENT>return conf_list<EOL> | 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: | f13032:m0 |
def __init__(<EOL>self, name=None, runtime_dir=None, project_name=None, strict_config=None, style_prints=False,<EOL>embedded_plugins=None, **kwargs): | self._style_prints = style_prints<EOL>if callable(embedded_plugins):<EOL><INDENT>if embedded_plugins is self.embedded_plugins_presets.PROBE:<EOL><INDENT>embedded_plugins = embedded_plugins()<EOL><DEDENT>embedded_plugins = embedded_plugins()<EOL><DEDENT>self._plugins = embedded_plugins or []<EOL>self._section = self<EOL>self._options_objects = OrderedDict()<EOL>self._opts = OrderedDict()<EOL>self.name = name or '<STR_LIT>'<EOL>self._runtime_dir = runtime_dir or '<STR_LIT>'<EOL>self._project_name = project_name or '<STR_LIT>'<EOL>super(Section, self).__init__(**kwargs)<EOL>self._set_basic_params_from_dict(kwargs)<EOL>self.set_basic_params(strict_config=strict_config)<EOL> | :param bool strict_config: Enable strict configuration parsing.
If any unknown option is encountered in a configuration file,
an error is shown and uWSGI quits.
To use placeholder variables when using strict mode, use the ``set-placeholder`` option.
:param str|unicode name: Configuration section name.
:param str|unicode runtime_dir: Directory to store runtime files.
See ``.replace_placeholders()``
.. note:: This can be used to store PID files, sockets, master FIFO, etc.
:param str|unicode project_name: Project name (alias) to be used to differentiate projects.
See ``.replace_placeholders()``.
:param bool style_prints: Enables styling (e.g. colouring) for ``print_`` family methods.
Could be nice for console and distracting in logs.
:param list|callable embedded_plugins: List of embedded plugins. Plugins from that list will
be considered already loaded so uwsgiconf won't instruct uWSGI to load it if required.
See ``.embedded_plugins_presets`` for shortcuts.
.. note::
* If you installed uWSGI using PyPI package there should already be basic plugins embedded.
* If using Ubuntu distribution you have to install plugins as separate packages.
* http://uwsgi-docs.readthedocs.io/en/latest/BuildSystem.html#plugins-and-uwsgiplugin-py | f13032:c0:m0 |
def replace_placeholders(self, value): | if not value:<EOL><INDENT>return value<EOL><DEDENT>is_list = isinstance(value, list)<EOL>values = []<EOL>for value in listify(value):<EOL><INDENT>runtime_dir = self.get_runtime_dir()<EOL>project_name = self.project_name<EOL>value = value.replace('<STR_LIT>', runtime_dir)<EOL>value = value.replace('<STR_LIT>', project_name)<EOL>value = value.replace('<STR_LIT>', os.path.join(runtime_dir, project_name))<EOL>values.append(value)<EOL><DEDENT>value = values if is_list else values.pop()<EOL>return value<EOL> | 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] | f13032:c0:m1 |
@property<EOL><INDENT>def project_name(self):<DEDENT> | return self._project_name<EOL> | Project name (alias) to be used to differentiate projects. See ``.replace_placeholders()``.
:rtype: str|unicode | f13032:c0:m2 |
def get_runtime_dir(self, default=True): | dir_ = self._runtime_dir<EOL>if not dir_ and default:<EOL><INDENT>uid = self.main_process.get_owner()[<NUM_LIT:0>]<EOL>dir_ = '<STR_LIT>' % uid if uid else '<STR_LIT>'<EOL><DEDENT>return dir_<EOL> | 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 | f13032:c0:m4 |
def set_runtime_dir(self, value): | self._runtime_dir = value or '<STR_LIT>'<EOL> | Sets user-defined runtime directory value.
:param str|unicode value: | f13032:c0:m5 |
def as_configuration(self, **kwargs): | return Configuration([self], **kwargs)<EOL> | Returns configuration object including only one (this very) section.
:param kwargs: Configuration objects initializer arguments.
:rtype: Configuration | f13032:c0:m7 |
def print_plugins(self): | self._set('<STR_LIT>', True, cast=bool)<EOL>return self<EOL> | Print out enabled plugins. | f13032:c0:m8 |
def print_stamp(self): | from . import VERSION<EOL>print_out = partial(self.print_out, format_options='<STR_LIT>')<EOL>print_out('<STR_LIT>')<EOL>print_out('<STR_LIT>' % ('<STR_LIT:.>'.join(map(str, VERSION)), datetime.now().isoformat('<STR_LIT:U+0020>')))<EOL>return self<EOL> | Prints out a stamp containing useful information,
such as what and when has generated this configuration. | f13032:c0:m9 |
def print_out(self, value, indent=None, format_options=None, asap=False): | if indent is None:<EOL><INDENT>indent = '<STR_LIT>'<EOL><DEDENT>text = indent + str(value)<EOL>if format_options is None:<EOL><INDENT>format_options = '<STR_LIT>'<EOL><DEDENT>if self._style_prints and format_options:<EOL><INDENT>if not isinstance(format_options, dict):<EOL><INDENT>format_options = {'<STR_LIT>': format_options}<EOL><DEDENT>text = format_print_text(text, **format_options)<EOL><DEDENT>command = '<STR_LIT>' if asap else '<STR_LIT>'<EOL>self._set(command, text, multi=True)<EOL>return self<EOL> | 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. | f13032:c0:m10 |
def print_variables(self): | print_out = partial(self.print_out, format_options='<STR_LIT>')<EOL>print_out('<STR_LIT>')<EOL>for var, hint in self.vars.get_descriptions().items():<EOL><INDENT>print_out('<STR_LIT>' + var + '<STR_LIT>' + var + '<STR_LIT>' + hint.replace('<STR_LIT:%>', '<STR_LIT>'))<EOL><DEDENT>print_out('<STR_LIT>')<EOL>return self<EOL> | 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 | f13032:c0:m11 |
def set_plugins_params(self, plugins=None, search_dirs=None, autoload=None, required=False): | plugins = plugins or []<EOL>command = '<STR_LIT>' if required else '<STR_LIT>'<EOL>for plugin in listify(plugins):<EOL><INDENT>if plugin not in self._plugins:<EOL><INDENT>self._set(command, plugin, multi=True)<EOL>self._plugins.append(plugin)<EOL><DEDENT><DEDENT>self._set('<STR_LIT>', search_dirs, multi=True, priority=<NUM_LIT:0>)<EOL>self._set('<STR_LIT>', autoload, cast=bool)<EOL>return self<EOL> | 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. | f13032:c0:m12 |
def set_fallback(self, target): | if isinstance(target, Section):<EOL><INDENT>target = '<STR_LIT::>' + target.name<EOL><DEDENT>self._set('<STR_LIT>', target)<EOL>return self<EOL> | 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. | f13032:c0:m13 |
def set_placeholder(self, key, value): | self._set('<STR_LIT>', '<STR_LIT>' % (key, value), multi=True)<EOL>return self<EOL> | 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: | f13032:c0:m14 |
def env(self, key, value=None, unset=False, asap=False): | if unset:<EOL><INDENT>self._set('<STR_LIT>', key, multi=True)<EOL><DEDENT>else:<EOL><INDENT>if value is None:<EOL><INDENT>value = os.environ.get(key)<EOL><DEDENT>self._set('<STR_LIT>' % ('<STR_LIT:i>' if asap else '<STR_LIT>'), '<STR_LIT>' % (key, value), multi=True)<EOL><DEDENT>return self<EOL> | 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. | f13032:c0:m15 |
def include(self, target): | for target_ in listify(target):<EOL><INDENT>if isinstance(target_, Section):<EOL><INDENT>target_ = '<STR_LIT::>' + target_.name<EOL><DEDENT>self._set('<STR_LIT>', target_, multi=True)<EOL><DEDENT>return self<EOL> | Includes target contents into config.
:param str|unicode|Section|list target: File path or Section to include. | f13032:c0:m16 |
@classmethod<EOL><INDENT>def derive_from(cls, section, name=None):<DEDENT> | new_section = deepcopy(section)<EOL>if name:<EOL><INDENT>new_section.name = name<EOL><DEDENT>return new_section<EOL> | Creates a new section based on the given.
:param Section section: Section to derive from,
:param str|unicode name: New section name.
:rtype: Section | f13032:c0:m17 |
def __init__(self, sections=None, autoinclude_sections=False, alias=None): | super(Configuration, self).__init__()<EOL>sections = sections or [Section()]<EOL>self._validate_sections(sections)<EOL>if autoinclude_sections:<EOL><INDENT>first = sections[<NUM_LIT:0>]<EOL>for section in sections[<NUM_LIT:1>:]:<EOL><INDENT>first.include(section)<EOL><DEDENT><DEDENT>self.sections = sections<EOL>self.alias = alias or '<STR_LIT>'<EOL> | :param list[Section] sections: If not provided, empty section
will be automatically generated.
:param bool autoinclude_sections: Whether to include
in the first sections all subsequent sections.
:param str|unicode alias: Configuration alias.
This will be used in ``tofile`` as file name. | f13032:c1:m0 |
@classmethod<EOL><INDENT>def _validate_sections(cls, sections):<DEDENT> | names = []<EOL>for section in sections:<EOL><INDENT>if not hasattr(section, '<STR_LIT:name>'):<EOL><INDENT>raise ConfigurationError('<STR_LIT>')<EOL><DEDENT>name = section.name<EOL>if name in names:<EOL><INDENT>raise ConfigurationError('<STR_LIT>' % name)<EOL><DEDENT>names.append(name)<EOL><DEDENT> | Validates sections types and uniqueness. | f13032:c1:m1 |
def format(self, do_print=False, stamp=True): | if stamp and self.sections:<EOL><INDENT>self.sections[<NUM_LIT:0>].print_stamp()<EOL><DEDENT>formatted = IniFormatter(self.sections).format()<EOL>if do_print:<EOL><INDENT>print(formatted)<EOL><DEDENT>return formatted<EOL> | 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 | f13032:c1:m2 |
def print_ini(self): | return self.format(do_print=True)<EOL> | Print out this configuration as .ini.
:rtype: str|unicode | f13032:c1:m3 |
def tofile(self, filepath=None): | if filepath is None:<EOL><INDENT>with NamedTemporaryFile(prefix='<STR_LIT>' % self.alias, suffix='<STR_LIT>', delete=False) as f:<EOL><INDENT>filepath = f.name<EOL><DEDENT><DEDENT>else:<EOL><INDENT>filepath = os.path.abspath(filepath)<EOL>if os.path.isdir(filepath):<EOL><INDENT>filepath = os.path.join(filepath, '<STR_LIT>' % self.alias)<EOL><DEDENT><DEDENT>with open(filepath, '<STR_LIT:w>') as target_file:<EOL><INDENT>target_file.write(self.format())<EOL>target_file.flush()<EOL><DEDENT>return filepath<EOL> | 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 | f13032:c1:m4 |
@contextmanager<EOL>def errorprint(): | try:<EOL><INDENT>yield<EOL><DEDENT>except ConfigurationError as e:<EOL><INDENT>click.secho('<STR_LIT:%s>' % e, err=True, fg='<STR_LIT>')<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT> | Print out descriptions from ConfigurationError. | f13034:m0 |
@click.group()<EOL>@click.version_option(version='<STR_LIT:.>'.join(map(str, VERSION)))<EOL>def base(): | uwsgiconf command line utility.
Tools to facilitate uWSGI configuration. | f13034:m1 | |
@base.command()<EOL>@arg_conf<EOL>@click.option('<STR_LIT>', help='<STR_LIT>')<EOL>def run(conf, only): | with errorprint():<EOL><INDENT>config = ConfModule(conf)<EOL>spawned = config.spawn_uwsgi(only)<EOL>for alias, pid in spawned:<EOL><INDENT>click.secho("<STR_LIT>" % (alias, pid), fg='<STR_LIT>')<EOL><DEDENT><DEDENT> | Runs uWSGI passing to it using the default or another `uwsgiconf` configuration module. | f13034:m2 |
@base.command()<EOL>@arg_conf<EOL>def compile(conf): | with errorprint():<EOL><INDENT>config = ConfModule(conf)<EOL>for conf in config.configurations:<EOL><INDENT>conf.format(do_print=True)<EOL><DEDENT><DEDENT> | Compiles classic uWSGI configuration file using the default
or given `uwsgiconf` configuration module. | f13034:m3 |
@base.command()<EOL>@click.argument('<STR_LIT>', type=click.Choice(TYPES), default=TYPE_SYSTEMD)<EOL>@arg_conf<EOL>@click.option('<STR_LIT>', help='<STR_LIT>')<EOL>def sysinit(systype, conf, project): | click.secho(get_config(<EOL>systype,<EOL>conf=ConfModule(conf).configurations[<NUM_LIT:0>],<EOL>conf_path=conf,<EOL>project_name=project,<EOL>))<EOL> | Outputs configuration for system initialization subsystem. | f13034:m4 |
@base.command()<EOL>def probe_plugins(): | plugins = UwsgiRunner().get_plugins()<EOL>for plugin in sorted(plugins.generic):<EOL><INDENT>click.secho(plugin)<EOL><DEDENT>click.secho('<STR_LIT>')<EOL>for plugin in sorted(plugins.request):<EOL><INDENT>click.secho(plugin)<EOL><DEDENT> | Runs uWSGI to determine what plugins are available and prints them out.
Generic plugins come first then after blank line follow request plugins. | f13034:m5 |
def main(): | base(obj={})<EOL> | CLI entry point | f13034:m6 |
def __init__(<EOL>self, name=None, touch_reload=None, workers=None, threads=None, mules=None, owner=None,<EOL>log_into=None, log_dedicated=None,<EOL>process_prefix=None, ignore_write_errors=None,<EOL>**kwargs): | super(Section, self).__init__(strict_config=True, name=name, **kwargs)<EOL>self.env('<STR_LIT>', '<STR_LIT>')<EOL>if touch_reload:<EOL><INDENT>self.main_process.set_basic_params(touch_reload=touch_reload)<EOL><DEDENT>if workers:<EOL><INDENT>self.workers.set_basic_params(count=workers)<EOL><DEDENT>else:<EOL><INDENT>self.workers.set_count_auto()<EOL><DEDENT>set_threads = self.workers.set_thread_params<EOL>if isinstance(threads, bool):<EOL><INDENT>set_threads(enable=threads)<EOL><DEDENT>else:<EOL><INDENT>set_threads(count=threads)<EOL><DEDENT>if log_dedicated:<EOL><INDENT>self.logging.set_master_logging_params(enable=True, dedicate_thread=True)<EOL><DEDENT>self.workers.set_mules_params(mules=mules)<EOL>self.workers.set_harakiri_params(verbose=True)<EOL>self.main_process.set_basic_params(vacuum=True)<EOL>self.main_process.set_naming_params(<EOL>autonaming=True,<EOL>prefix='<STR_LIT>' % process_prefix if process_prefix else None,<EOL>)<EOL>self.master_process.set_basic_params(enable=True)<EOL>self.master_process.set_exit_events(sig_term=True) <EOL>self.locks.set_basic_params(thunder_lock=True)<EOL>self.configure_owner(owner=owner)<EOL>self.logging.log_into(target=log_into)<EOL>if ignore_write_errors:<EOL><INDENT>self.master_process.set_exception_handling_params(no_write_exception=True)<EOL>self.logging.set_filters(write_errors=False, sigpipe=False)<EOL><DEDENT> | :param str|unicode name: Section name.
:param str|list touch_reload: Reload uWSGI if the specified file or directory is modified/touched.
:param int workers: Spawn the specified number of workers (processes).
Default: workers number equals to CPU count.
:param int|bool threads: Number of threads per worker or ``True`` to enable user-made threads support.
:param int mules: Number of mules to spawn.
:param str|unicode owner: Set process owner user and group.
:param str|unicode log_into: Filepath or UDP address to send logs into.
:param bool log_dedicated: If ``True`` all logging will be handled with a separate
thread in master process.
:param str|unicode process_prefix: Add prefix to process names.
:param bool ignore_write_errors: If ``True`` no annoying SIGPIPE/write/writev errors
will be logged, and no related exceptions will be raised.
.. note:: Usually such errors could be seen on client connection cancelling
and are safe to ignore.
:param kwargs: | f13035:c0:m0 |
def get_log_format_default(self): | vars = self.logging.vars<EOL>format_default = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (<EOL>vars.WORKER_PID,<EOL>'<STR_LIT:->', <EOL>'<STR_LIT:->', <EOL>'<STR_LIT:->', <EOL>vars.REQ_REMOTE_ADDR,<EOL>vars.REQ_REMOTE_USER,<EOL>vars.REQ_COUNT_VARS_CGI,<EOL>vars.SIZE_PACKET_UWSGI,<EOL>vars.REQ_START_CTIME,<EOL>vars.REQ_METHOD,<EOL>vars.REQ_URI,<EOL>vars.RESP_SIZE_BODY,<EOL>vars.RESP_TIME_MS, <EOL>'<STR_LIT:->', <EOL>'<STR_LIT:->', <EOL>vars.REQ_SERVER_PROTOCOL,<EOL>vars.RESP_STATUS,<EOL>vars.RESP_COUNT_HEADERS,<EOL>vars.RESP_SIZE_HEADERS,<EOL>vars.ASYNC_SWITCHES,<EOL>vars.CORE,<EOL>))<EOL>return format_default<EOL> | Returns default log message format.
.. note:: Some params may be missing. | f13035:c0:m1 |
def configure_owner(self, owner='<STR_LIT>'): | if owner is not None:<EOL><INDENT>self.main_process.set_owner_params(uid=owner, gid=owner)<EOL><DEDENT>return self<EOL> | Shortcut to set process owner data.
:param str|unicode owner: Sets user and group. Default: ``www-data``. | f13035:c0:m2 |
def __init__(<EOL>self, name=None, params_python=None, wsgi_module=None, wsgi_callable=None,<EOL>embedded_plugins=True, require_app=True, threads=True, **kwargs): | if embedded_plugins is True:<EOL><INDENT>embedded_plugins = self.embedded_plugins_presets.BASIC + ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>super(PythonSection, self).__init__(<EOL>name=name, embedded_plugins=embedded_plugins, threads=threads,<EOL>**kwargs)<EOL>self.python.set_basic_params(**(params_python or {}))<EOL>if callable(wsgi_callable):<EOL><INDENT>wsgi_callable = wsgi_callable.__name__<EOL><DEDENT>self.python.set_wsgi_params(module=wsgi_module, callable_name=wsgi_callable)<EOL>self.applications.set_basic_params(exit_if_none=require_app)<EOL> | :param str|unicode name: Section name.
:param dict params_python: See Python plugin basic params.
:param str|unicode wsgi_module: WSGI application module path or filepath.
Example:
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 wsgi_callable: WSGI application callable name. Default: application.
:param bool|None embedded_plugins: This indicates whether plugins were embedded into uWSGI,
which is the case if you have uWSGI from PyPI.
:param bool require_app: Exit if no app can be loaded.
:param int|bool threads: Number of threads per worker or ``True`` to enable user-made threads support.
:param kwargs: | f13035:c1:m0 |
def __init__(<EOL>self, zerg_socket, zerg_die_on_idle=None, vassals_home=None,<EOL>zerg_count=None, vassal_overload_sos_interval=None, vassal_queue_items_sos=None,<EOL>section_emperor=None, section_zerg=None): | self.socket = zerg_socket<EOL>self.vassals_home = vassals_home<EOL>self.die_on_idle = zerg_die_on_idle<EOL>self.broodlord_params = filter_locals(<EOL>locals(), include=[<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>])<EOL>section_emperor = section_emperor or Section()<EOL>section_zerg = section_zerg or Section.derive_from(section_emperor)<EOL>self.section_emperor = section_emperor<EOL>self.section_zerg = section_zerg<EOL> | :param str|unicode zerg_socket: Unix socket to bind server to.
:param int zerg_die_on_idle: A number of seconds after which an idle zerg will be destroyed.
:param str|unicode|list[str|unicode] vassals_home: Set vassals home.
:param int zerg_count: Maximum number of zergs to spawn.
:param int vassal_overload_sos_interval: Ask emperor for reinforcement when overloaded.
Accepts the number of seconds to wait between asking for a new reinforcements.
:param int vassal_queue_items_sos: Ask emperor for sos if backlog queue has more
items than the value specified | f13036:c0:m0 |
def configure(self): | section_emperor = self.section_emperor<EOL>section_zerg = self.section_zerg<EOL>socket = self.socket<EOL>section_emperor.workers.set_zerg_server_params(socket=socket)<EOL>section_emperor.empire.set_emperor_params(vassals_home=self.vassals_home)<EOL>section_emperor.empire.set_mode_broodlord_params(**self.broodlord_params)<EOL>section_zerg.name = '<STR_LIT>'<EOL>section_zerg.workers.set_zerg_client_params(server_sockets=socket)<EOL>if self.die_on_idle:<EOL><INDENT>section_zerg.master_process.set_idle_params(timeout=<NUM_LIT:30>, exit=True)<EOL><DEDENT>return section_emperor, section_zerg<EOL> | Configures broodlord mode and returns emperor and zerg sections.
:rtype: tuple | f13036:c0:m1 |
def __init__(self, opt_type): | self.opt_type = opt_type<EOL> | :param opt_type: | f13037:c0:m0 |
def __get__(self, section, section_cls): | key = self.opt_type.__name__<EOL>try:<EOL><INDENT>options_obj = section._options_objects.get(key)<EOL><DEDENT>except AttributeError:<EOL><INDENT>return self.opt_type<EOL><DEDENT>if not options_obj:<EOL><INDENT>options_obj = self.opt_type(_section=section)<EOL><DEDENT>section._options_objects[key] = options_obj<EOL>return options_obj<EOL> | :param Section section:
:param OptionsGroup options_obj:
:rtype: OptionsGroup | f13037:c0:m1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.