signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def clear_request():
if hasattr(_thread_locals, REQUEST_LOCAL_KEY):<EOL><INDENT>setattr(_thread_locals, REQUEST_LOCAL_KEY, None)<EOL><DEDENT>
Clears request for this thread.
f14989:m2
def supports(self, config, context):
request = current_request()<EOL>return request is not None and re.match(r'<STR_LIT>', request.__module__)<EOL>
Check whether this is a django request or not. :param config: honeybadger configuration. :param context: current honeybadger configuration. :return: True if this is a django request, False else.
f14989:c0:m1
def generate_payload(self, config, context):
request = current_request()<EOL>payload = {<EOL>'<STR_LIT:url>': request.build_absolute_uri(),<EOL>'<STR_LIT>': request.resolver_match.app_name,<EOL>'<STR_LIT:action>': request.resolver_match.func.__name__,<EOL>'<STR_LIT>': {},<EOL>'<STR_LIT>': {},<EOL>'<STR_LIT>': dict(request.META),<EOL>'<STR_LIT>': context<EOL>}<EOL>if hasattr(request, '<STR_LIT>'):<EOL><INDENT>payload['<STR_LIT>'] = filter_dict(dict(request.session), config.params_filters)<EOL><DEDENT>payload['<STR_LIT>'] = filter_dict(dict(getattr(request, request.method)), config.params_filters)<EOL>return payload<EOL>
Generate payload by checking Django request object. :param context: current context. :param config: honeybadger configuration. :return: a dict with the generated payload.
f14989:c0:m2
def supports(self, config, context):
try:<EOL><INDENT>from flask import request<EOL><DEDENT>except ImportError:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return bool(request)<EOL><DEDENT>
Check whether we are in a Flask request context. :param config: honeybadger configuration. :param context: current honeybadger configuration. :return: True if this is a django request, False else.
f14991:c0:m1
def generate_payload(self, config, context):
from flask import current_app, session, request as _request<EOL>current_view = current_app.view_functions[_request.endpoint]<EOL>if hasattr(current_view, '<STR_LIT>'):<EOL><INDENT>component = '<STR_LIT:.>'.join((current_view.__module__, current_view.view_class.__name__))<EOL><DEDENT>else:<EOL><INDENT>component = current_view.__module__<EOL><DEDENT>cgi_data = {<EOL>k: v<EOL>for k, v in iteritems(_request.headers)<EOL>}<EOL>cgi_data.update({<EOL>'<STR_LIT>': _request.method<EOL>})<EOL>payload = {<EOL>'<STR_LIT:url>': _request.base_url,<EOL>'<STR_LIT>': component,<EOL>'<STR_LIT:action>': _request.endpoint,<EOL>'<STR_LIT>': {},<EOL>'<STR_LIT>': filter_dict(dict(session), config.params_filters),<EOL>'<STR_LIT>': cgi_data,<EOL>'<STR_LIT>': context<EOL>}<EOL>params = filter_dict(dict(_request.args), config.params_filters)<EOL>params.update(filter_dict(dict(_request.form), config.params_filters))<EOL>payload['<STR_LIT>'] = params<EOL>return payload<EOL>
Generate payload by checking Flask request object. :param context: current context. :param config: honeybadger configuration. :return: a dict with the generated payload.
f14991:c0:m2
def __init__(self, app=None, report_exceptions=False, reset_context_after_request=False):
self.app = app<EOL>self.report_exceptions = False<EOL>self.reset_context_after_request = False<EOL>default_plugin_manager.register(FlaskPlugin())<EOL>if app is not None:<EOL><INDENT>self.init_app(app,<EOL>report_exceptions=report_exceptions,<EOL>reset_context_after_request=reset_context_after_request)<EOL><DEDENT>
Initialize Honeybadger. :param flask.Application app: the application to wrap for the exception. :param bool report_exceptions: whether to automatically report exceptions raised by Flask on requests (i.e. by calling abort) or not. :param bool reset_context_after_request: whether to reset honeybadger context after each request.
f14991:c1:m0
def init_app(self, app, report_exceptions=False, reset_context_after_request=False):
from flask import request_tearing_down, got_request_exception<EOL>self.app = app<EOL>self.app.logger.info('<STR_LIT>')<EOL>self.report_exceptions = report_exceptions<EOL>self.reset_context_after_request = reset_context_after_request<EOL>self._initialize_honeybadger(app.config)<EOL>if self.report_exceptions:<EOL><INDENT>self._register_signal_handler('<STR_LIT>',<EOL>got_request_exception,<EOL>self._handle_exception)<EOL><DEDENT>if self.reset_context_after_request:<EOL><INDENT>self._register_signal_handler('<STR_LIT>',<EOL>request_tearing_down,<EOL>self._reset_context)<EOL><DEDENT>logger.info('<STR_LIT>')<EOL>
Initialize honeybadger and listen for errors. :param Flask app: the Flask application object. :param bool report_exceptions: whether to automatically report exceptions raised by Flask on requests (i.e. by calling abort) or not. :param bool reset_context_after_request: whether to reset honeybadger context after each request.
f14991:c1:m1
def _register_signal_handler(self, description, signal, handler):
from flask import signals<EOL>if not signals.signals_available:<EOL><INDENT>self.app.logger.warn('<STR_LIT>'.format(description))<EOL><DEDENT>self.app.logger.info('<STR_LIT>'.format(description))<EOL>signal.connect(handler, sender=self.app, weak=False)<EOL>
Registers a handler for the given signal. :param description: a short description of the signal to handle. :param signal: the signal to handle. :param handler: the function to use for handling the signal.
f14991:c1:m2
def _initialize_honeybadger(self, config):
if config.get('<STR_LIT>', False):<EOL><INDENT>honeybadger.configure(environment='<STR_LIT>')<EOL><DEDENT>honeybadger_config = {}<EOL>for key, value in iteritems(config):<EOL><INDENT>if key.startswith(self.CONFIG_PREFIX):<EOL><INDENT>honeybadger_config[key[len(self.CONFIG_PREFIX):].lower()] = value<EOL><DEDENT><DEDENT>honeybadger.configure(**honeybadger_config)<EOL>honeybadger.config.set_12factor_config()<EOL>
Initializes honeybadger using the given config object. :param dict config: a dict or dict-like object that contains honeybadger configuration properties.
f14991:c1:m3
def _reset_context(self, *args, **kwargs):
honeybadger.reset_context()<EOL>
Resets context when request is done.
f14991:c1:m4
def _handle_exception(self, sender, exception=None):
honeybadger.notify(exception)<EOL>if self.reset_context_after_request:<EOL><INDENT>self._reset_context()<EOL><DEDENT>
Actual code handling the exception and sending it to honeybadger if it's enabled. :param T sender: the object sending the exception event. :param Exception exception: the exception to handle.
f14991:c1:m5
def is_dev(self):
return self.environment in self.DEVELOPMENT_ENVIRONMENTS<EOL>
Returns wether you are in a dev environment or not A dev environment is defined in the constant DEVELOPMENT_ENVIRONMENTS :rtype: bool
f14992:c0:m3
def __init__(self, name):
self.name = name<EOL>
Initialize plugin. :param name: the name of the plugin.
f15007:c0:m0
def supports(self, config, context):
return False<EOL>
Whether this plugin supports generating payload for the current configuration, request and context. :param exception: current exception. :param config: honeybadger configuration. :param context: current honeybadger context. :return: True if plugin can generate payload for current exception, False else.
f15007:c0:m1
@abstractmethod<EOL><INDENT>def generate_payload(self, config, context):<DEDENT>
pass<EOL>
Return additional payload for given exception. May be used by actual plugin implementations to gather additional information. :param config: honeybadger configuration :param context: context gathered so far to send to honeybadger. :return: a dictionary with the generated payload.
f15007:c0:m2
def register(self, plugin):
if plugin.name not in self._registered:<EOL><INDENT>logger.info('<STR_LIT>' % plugin.name)<EOL>self._registered[plugin.name] = plugin<EOL><DEDENT>else:<EOL><INDENT>logger.warn('<STR_LIT>' % plugin.name)<EOL><DEDENT>
Register the given plugin. Registration order is kept. :param plugin: the plugin to register.
f15007:c1:m1
def generate_payload(self, config=None, context=None):
for name, plugin in iteritems(self._registered):<EOL><INDENT>if plugin.supports(config, context):<EOL><INDENT>logger.debug('<STR_LIT>' % name)<EOL>return plugin.generate_payload(config, context)<EOL><DEDENT><DEDENT>logger.debug('<STR_LIT>')<EOL>return {<EOL>'<STR_LIT>': context<EOL>}<EOL>
Generate payload by iterating over registered plugins. Merges . :param context: current context. :param config: honeybadger configuration. :return: a dict with the generated payload.
f15007:c1:m2
def generic_div(a, b):
logger.debug('<STR_LIT>'.format(a, b))<EOL>return a / b<EOL>
Simple function to divide two numbers
f15016:m0
def generic_div(a, b):
logger.debug('<STR_LIT>'.format(a, b))<EOL>return a / b<EOL>
Simple function to divide two numbers
f15017:m0
def buggy_div(request):
a = float(request.GET.get('<STR_LIT:a>', '<STR_LIT:0>'))<EOL>b = float(request.GET.get('<STR_LIT:b>', '<STR_LIT:0>'))<EOL>return JsonResponse({'<STR_LIT:result>': a / b})<EOL>
A buggy endpoint to perform division between query parameters a and b. It will fail if b is equal to 0 or either a or b are not float. :param request: request object :return:
f15021:m1
def get_site_by_name(name):
return sites.get(name)<EOL>
Return site according to name (default is IS)
f15041:m0
def get_model_core(model):
model_label = lower('<STR_LIT>' % (model._meta.app_label, model._meta.object_name))<EOL>return registered_model_cores.get(model_label)<EOL>
Return core view of given model or None
f15041:m1
def _get_error_response(self, exception):
response_exceptions = {<EOL>MimerDataException: HTTPBadRequestResponseException,<EOL>NotAllowedException: HTTPForbiddenResponseException,<EOL>UnsupportedMediaTypeException: HTTPUnsupportedMediaTypeResponseException,<EOL>Http404: Http404,<EOL>ResourceNotFoundException: Http404,<EOL>NotAllowedMethodException: HTTPMethodNotAllowedResponseException,<EOL>DuplicateEntryException: HTTPDuplicateResponseException,<EOL>ConflictException: HTTPDuplicateResponseException,<EOL>}<EOL>response_exception = response_exceptions.get(type(exception))<EOL>if response_exception:<EOL><INDENT>raise response_exception<EOL><DEDENT>return super(RESTResourceMixin, self)._get_error_response(exception)<EOL>
Trasform pyston exceptions to Is-core exceptions and raise it
f15042:c2:m2
def get_method_returning_field_value(self, field_name):
return (<EOL>super().get_method_returning_field_value(field_name)<EOL>or self.core.get_method_returning_field_value(field_name)<EOL>)<EOL>
Field values can be obtained from resource or core.
f15042:c2:m3
def get_success_url(self, obj):
return self.request.get_full_path()<EOL>
URL string for redirect after saving
f15051:c0:m0
def is_changed(self, form, **kwargs):
return form.has_changed()<EOL>
Return true if form was changed
f15051:c0:m8
def save_obj(self, obj, form, change):
raise NotImplementedError<EOL>
Must be added for non model forms this method should save object or raise exception
f15051:c0:m9
def save_form(self, form, **kwargs):
obj = form.save(commit=False)<EOL>change = obj.pk is not None<EOL>self.save_obj(obj, form, change)<EOL>if hasattr(form, '<STR_LIT>'):<EOL><INDENT>form.save_m2m()<EOL><DEDENT>return obj<EOL>
Contains formset save, prepare obj for saving
f15051:c0:m10
@property<EOL><INDENT>def is_ajax_form(self):<DEDENT>
return self.has_snippet()<EOL>
Return if form will be rendered for ajax
f15051:c0:m15
@property<EOL><INDENT>def is_popup_form(self):<DEDENT>
return '<STR_LIT>' in self.request.GET<EOL>
Return if form will be rendnered as popup
f15051:c0:m16
@property<EOL><INDENT>def form_snippet_name(self):<DEDENT>
return '<STR_LIT>' % (self.view_name, '<STR_LIT>')<EOL>
Return name for name for snippet which surround form
f15051:c0:m17
def get_method_returning_field_value(self, field_name):
return (<EOL>super().get_method_returning_field_value(field_name)<EOL>or self.core.get_method_returning_field_value(field_name)<EOL>)<EOL>
Field values can be obtained from view or core.
f15051:c0:m31
def _get_perm_obj_or_404(self, pk=None):
if pk:<EOL><INDENT>obj = get_object_or_none(self.core.model, pk=pk)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>obj = self.get_obj(False)<EOL><DEDENT>except Http404:<EOL><INDENT>obj = get_object_or_none(self.core.model, **self.get_obj_filters())<EOL><DEDENT><DEDENT>if not obj:<EOL><INDENT>raise Http404<EOL><DEDENT>return obj<EOL>
If is send parameter pk is returned object according this pk, else is returned object from get_obj method, but it search only inside filtered values for current user, finally if object is still None is returned according the input key from all objects. If object does not exist is raised Http404
f15051:c4:m3
def redirect_to_login(next, redirect_field_name=REDIRECT_FIELD_NAME):
resolved_url = reverse('<STR_LIT>')<EOL>login_url_parts = list(urlparse(resolved_url))<EOL>if redirect_field_name:<EOL><INDENT>querystring = QueryDict(login_url_parts[<NUM_LIT:4>], mutable=True)<EOL>querystring[redirect_field_name] = next<EOL>login_url_parts[<NUM_LIT:4>] = querystring.urlencode(safe='<STR_LIT:/>')<EOL><DEDENT>raise HTTPRedirectResponseException(urlunparse(login_url_parts))<EOL>
Redirects the user to the login page, passing the given 'next' page
f15052:m0
def _check_permission(self, name, obj=None):
def redirect_or_exception(ex):<EOL><INDENT>if not self.request.user or not self.request.user.is_authenticated:<EOL><INDENT>if self.auto_login_redirect:<EOL><INDENT>redirect_to_login(self.request.get_full_path())<EOL><DEDENT>else:<EOL><INDENT>raise HTTPUnauthorizedResponseException<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ex<EOL><DEDENT><DEDENT>try:<EOL><INDENT>if not self._has_permission(name, obj):<EOL><INDENT>redirect_or_exception(HTTPForbiddenResponseException)<EOL><DEDENT><DEDENT>except Http404 as ex:<EOL><INDENT>redirect_or_exception(ex)<EOL><DEDENT>
If customer is not authorized he should not get information that object is exists. Therefore 403 is returned if object was not found or is redirected to the login page. If custmer is authorized and object was not found is returned 404. If object was found and user is not authorized is returned 403 or redirect to login page. If object was found and user is authorized is returned 403 or 200 according of result of _has_permission method.
f15052:c0:m4
def get_objects(self):
raise NotImplementedError<EOL>
This method must return a queryset of models, dictionaries or any iterable objects. Dictionaries must have keys defined in the attribute 'fields'. For eg: {'company_name': 'ABC', 'zip': '44455'} Objects / models must have attributes defined in the attribute 'fields'. Or it may have a humanizing methods 'get_attributename_humanized', for eg: method 'get_zip_hunanized'.
f15053:c1:m2
def get_widget(self, request):
widget = self.widget<EOL>if isinstance(widget, type):<EOL><INDENT>widget = widget()<EOL><DEDENT>return widget<EOL>
Returns concrete widget that will be used for rendering table filter.
f15059:c1:m0
def get_operator(self, widget):
return self.get_allowed_operators()[<NUM_LIT:0>]<EOL>
Returns operator used for filtering. By default it is first operator defined in Pyston filter.
f15059:c1:m1
def _update_widget_choices(self, widget):
widget.choices = FilterChoiceIterator(widget.choices, self.field)<EOL>return widget<EOL>
Updates widget choices with special choice iterator that removes blank values and adds none value to clear filter data. :param widget: widget with choices :return: updated widget with filter choices
f15060:c2:m0
def get_operator(self, widget):
return OPERATORS.CONTAINS if widget.is_restricted else OPERATORS.EQ<EOL>
Because related form field can be restricted (if choices is too much it is used textarea without select box) for situation without choices (textarea) is used contains operator. :param widget: restricted widget :return: operator that will be used for filtering
f15060:c2:m1
def get_widget(self, request):
return self._update_widget_choices(self.field.formfield(widget=RestrictedSelectWidget).widget)<EOL>
Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for filtering.
f15060:c3:m0
def get_widget(self, request):
return self._update_widget_choices(self.field.formfield(widget=RestrictedSelectWidget).widget)<EOL>
Field widget is replaced with "RestrictedSelectWidget" because "MultipleChoiceField" is not optional for filtering purposes.
f15060:c4:m0
def get_widget(self, request):
return self._update_widget_choices(<EOL>forms.ModelChoiceField(<EOL>widget=RestrictedSelectWidget, queryset=self.field.related_model._default_manager.all()<EOL>).widget<EOL>)<EOL>
Table view is not able to get form field from reverse relation. Therefore this widget returns similar form field as direct relation (ModelChoiceField). Because there is used "RestrictedSelectWidget" it is returned textarea or selectox with choices according to count objects in the queryset.
f15060:c5:m0
def flatten_fieldsets(fieldsets):
field_names = []<EOL>for _, opts in fieldsets or ():<EOL><INDENT>if '<STR_LIT>' in opts:<EOL><INDENT>field_names += flatten_fieldsets(opts.get('<STR_LIT>'))<EOL><DEDENT>else:<EOL><INDENT>for field in opts.get('<STR_LIT>', ()):<EOL><INDENT>if isinstance(field, (list, tuple)):<EOL><INDENT>field_names.extend(field)<EOL><DEDENT>else:<EOL><INDENT>field_names.append(field)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return field_names<EOL>
Returns a list of field names from an admin fieldsets structure.
f15063:m3
def get_inline_views_from_fieldsets(fieldsets):
inline_views = []<EOL>for _, opts in fieldsets or ():<EOL><INDENT>if '<STR_LIT>' in opts:<EOL><INDENT>inline_views += get_inline_views_from_fieldsets(opts.get('<STR_LIT>'))<EOL><DEDENT>elif '<STR_LIT>' in opts:<EOL><INDENT>inline_views.append(opts.get('<STR_LIT>'))<EOL><DEDENT><DEDENT>return inline_views<EOL>
Returns a list of field names from an admin fieldsets structure.
f15063:m4
def get_inline_views_opts_from_fieldsets(fieldsets):
inline_views = []<EOL>for _, opts in fieldsets or ():<EOL><INDENT>if '<STR_LIT>' in opts:<EOL><INDENT>inline_views += get_inline_views_opts_from_fieldsets(opts.get('<STR_LIT>'))<EOL><DEDENT>elif '<STR_LIT>' in opts:<EOL><INDENT>inline_views.append(opts)<EOL><DEDENT><DEDENT>return inline_views<EOL>
Returns a list of field names from an admin fieldsets structure.
f15063:m5
def get_readonly_field_data(field_name, instance, view=None, fun_kwargs=None):
fun_kwargs = fun_kwargs or {}<EOL>if view:<EOL><INDENT>view_readonly_data = _get_view_readonly_data(field_name, view, fun_kwargs)<EOL>if view_readonly_data is not None:<EOL><INDENT>return view_readonly_data<EOL><DEDENT><DEDENT>field_data = _get_model_readonly_data(field_name, instance, fun_kwargs)<EOL>if field_data is not None:<EOL><INDENT>return field_data<EOL><DEDENT>raise FieldOrMethodDoesNotExist('<STR_LIT>'.format(field_name))<EOL>
Returns field humanized value, label and widget which are used to display of instance or view readonly data. Args: field_name: name of the field which will be displayed instance: model instance view: view instance fun_kwargs: kwargs that can be used inside method call Returns: field humanized value, label and widget which are used to display readonly data
f15063:m15
def display_object_data(obj, field_name, request=None):
from is_core.forms.utils import ReadonlyValue<EOL>value, _, _ = get_readonly_field_data(field_name, obj)<EOL>return display_for_value(value.humanized_value if isinstance(value, ReadonlyValue) else value, request=request)<EOL>
Returns humanized value of model object that can be rendered to HTML or returned as part of REST examples: boolean True/Talse ==> Yes/No objects ==> object display name with link if current user has permissions to see the object field with choices ==> string value of choice field with humanize function ==> result of humanize function
f15063:m16
def display_for_value(value, request=None):
from is_core.utils.compatibility import admin_display_for_value<EOL>if request and isinstance(value, Model):<EOL><INDENT>return render_model_object_with_link(request, value)<EOL><DEDENT>else:<EOL><INDENT>return (<EOL>(value and ugettext('<STR_LIT>') or ugettext('<STR_LIT>')) if isinstance(value, bool) else admin_display_for_value(value)<EOL>)<EOL><DEDENT>
Converts humanized value examples: boolean True/Talse ==> Yes/No objects ==> object display name with link if current user has permissions to see the object datetime ==> in localized format
f15063:m17
def get_url_from_model_core(request, obj):
from is_core.site import get_model_core<EOL>model_core = get_model_core(obj.__class__)<EOL>if model_core and hasattr(model_core, '<STR_LIT>'):<EOL><INDENT>edit_pattern = model_core.ui_patterns.get('<STR_LIT>')<EOL>return (<EOL>edit_pattern.get_url_string(request, obj=obj)<EOL>if edit_pattern and edit_pattern.has_permission('<STR_LIT>', request, obj=obj) else None<EOL>)<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
Returns object URL from model core.
f15063:m18
def get_obj_url(request, obj):
if (is_callable(getattr(obj, '<STR_LIT>', None)) and<EOL>(not hasattr(obj, '<STR_LIT>') or<EOL>(is_callable(getattr(obj, '<STR_LIT>', None)) and obj.can_see_edit_link(request)))):<EOL><INDENT>return call_method_with_unknown_input(obj.get_absolute_url, request=request)<EOL><DEDENT>else:<EOL><INDENT>return get_url_from_model_core(request, obj)<EOL><DEDENT>
Returns object URL if current logged user has permissions to see the object
f15063:m19
def get_link_or_none(pattern_name, request, view_kwargs=None):
from is_core.patterns import reverse_pattern<EOL>pattern = reverse_pattern(pattern_name)<EOL>assert pattern is not None, '<STR_LIT>'.format(pattern_name)<EOL>if pattern.has_permission('<STR_LIT>', request, view_kwargs=view_kwargs):<EOL><INDENT>return pattern.get_url_string(request, view_kwargs=view_kwargs)<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
Helper that generate URL prom pattern name and kwargs and check if current request has permission to open the URL. If not None is returned. Args: pattern_name (str): slug which is used for view registratin to pattern request (django.http.request.HttpRequest): Django request object view_kwargs (dict): list of kwargs necessary for URL generator Returns:
f15063:m24
def get_method_returning_field_value(self, field_name):
method = getattr(self, field_name, None)<EOL>return method if method and callable(method) else None<EOL>
Method should return object method that can be used to get field value. Args: field_name: name of the field Returns: method for obtaining a field value
f15063:c2:m0
def short_description(description):
def decorator(func):<EOL><INDENT>if isinstance(func, property):<EOL><INDENT>func = func.fget<EOL><DEDENT>func.short_description = description<EOL>return func<EOL><DEDENT>return decorator<EOL>
Sets 'short_description' attribute (this attribute is in exports to generate header name).
f15065:m0
def build_attrs(self, base_attrs, extra_attrs=None, **kwargs):
attrs = dict(base_attrs, **kwargs)<EOL>if extra_attrs:<EOL><INDENT>attrs.update(extra_attrs)<EOL><DEDENT>return attrs<EOL>
Helper function for building an attribute dictionary. This is combination of the same method from Django<=1.10 and Django1.11+
f15066:c1:m0
def smart_generic_inlineformset_factory(model, request, form=ModelForm, formset=BaseGenericInlineFormSet,<EOL>ct_field='<STR_LIT>', fk_field='<STR_LIT>', fields=None, exclude=None,<EOL>extra=<NUM_LIT:3>, can_order=False, can_delete=True, min_num=None, max_num=None,<EOL>formfield_callback=None, widgets=None, validate_min=False, validate_max=False,<EOL>localized_fields=None, labels=None, help_texts=None, error_messages=None,<EOL>formreadonlyfield_callback=None, readonly_fields=None, for_concrete_model=True,<EOL>readonly=False):
opts = model._meta<EOL>ct_field = opts.get_field(ct_field)<EOL>if not isinstance(ct_field, models.ForeignKey) or ct_field.related_model != ContentType:<EOL><INDENT>raise Exception("<STR_LIT>" % ct_field)<EOL><DEDENT>fk_field = opts.get_field(fk_field) <EOL>if exclude is not None:<EOL><INDENT>exclude = list(exclude)<EOL>exclude.extend([ct_field.name, fk_field.name])<EOL><DEDENT>else:<EOL><INDENT>exclude = [ct_field.name, fk_field.name]<EOL><DEDENT>kwargs = {<EOL>'<STR_LIT>': form,<EOL>'<STR_LIT>': formfield_callback,<EOL>'<STR_LIT>': formset,<EOL>'<STR_LIT>': extra,<EOL>'<STR_LIT>': can_delete,<EOL>'<STR_LIT>': can_order,<EOL>'<STR_LIT>': fields,<EOL>'<STR_LIT>': exclude,<EOL>'<STR_LIT>': max_num,<EOL>'<STR_LIT>': min_num,<EOL>'<STR_LIT>': widgets,<EOL>'<STR_LIT>': validate_min,<EOL>'<STR_LIT>': validate_max,<EOL>'<STR_LIT>': localized_fields,<EOL>'<STR_LIT>': formreadonlyfield_callback,<EOL>'<STR_LIT>': readonly_fields,<EOL>'<STR_LIT>': readonly,<EOL>'<STR_LIT>': labels,<EOL>'<STR_LIT>': help_texts,<EOL>'<STR_LIT>': error_messages,<EOL>}<EOL>FormSet = smartmodelformset_factory(model, request, **kwargs)<EOL>FormSet.ct_field = ct_field<EOL>FormSet.ct_fk_field = fk_field<EOL>FormSet.for_concrete_model = for_concrete_model<EOL>return FormSet<EOL>
Returns a ``GenericInlineFormSet`` for the given kwargs. You must provide ``ct_field`` and ``fk_field`` if they are different from the defaults ``content_type`` and ``object_id`` respectively.
f15068:m0
def as_widget(self, widget=None, attrs=None, only_initial=False):
if not widget:<EOL><INDENT>widget = self.field.widget<EOL><DEDENT>if self.field.localize:<EOL><INDENT>widget.is_localized = True<EOL><DEDENT>attrs = attrs or {}<EOL>attrs = self.build_widget_attrs(attrs, widget)<EOL>auto_id = self.auto_id<EOL>if auto_id and '<STR_LIT:id>' not in attrs and '<STR_LIT:id>' not in widget.attrs:<EOL><INDENT>if not only_initial:<EOL><INDENT>attrs['<STR_LIT:id>'] = auto_id<EOL><DEDENT>else:<EOL><INDENT>attrs['<STR_LIT:id>'] = self.html_initial_id<EOL><DEDENT><DEDENT>if not only_initial:<EOL><INDENT>name = self.html_name<EOL><DEDENT>else:<EOL><INDENT>name = self.html_initial_name<EOL><DEDENT>if isinstance(widget, SmartWidgetMixin) and hasattr(self.form, '<STR_LIT>'):<EOL><INDENT>return force_text(widget.smart_render(self.form._request, name, self.value(), self.initial,<EOL>self.form, attrs=attrs))<EOL><DEDENT>else:<EOL><INDENT>return force_text(widget.render(name, self.value(), attrs=attrs))<EOL><DEDENT>
Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs. If no widget is specified, then the field's default widget will be used.
f15069:c0:m0
def as_hidden(self, attrs=None, **kwargs):
return mark_safe('<STR_LIT>')<EOL>
Returns a string of HTML for representing this as an <input type="hidden">. Because readonly has not hidden input there must be returned empty string.
f15069:c1:m2
def __getitem__(self, name):
try:<EOL><INDENT>field = self.fields[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise KeyError(<EOL>"<STR_LIT>" % (<EOL>name,<EOL>self.__class__.__name__,<EOL>'<STR_LIT:U+002CU+0020>'.join(sorted(f for f in self.fields)),<EOL>)<EOL>)<EOL><DEDENT>if name not in self._bound_fields_cache:<EOL><INDENT>self._bound_fields_cache[name] = self._get_bound_field(name, field)<EOL><DEDENT>return self._bound_fields_cache[name]<EOL>
Returns a BoundField with the given name.
f15070:c1:m3
def smartformset_factory(form, formset=BaseFormSet, extra=<NUM_LIT:1>, can_order=False,<EOL>can_delete=False, min_num=None, max_num=None, validate_min=False, validate_max=False):
if max_num is None:<EOL><INDENT>max_num = DEFAULT_MAX_NUM<EOL><DEDENT>absolute_max = max_num + DEFAULT_MAX_NUM<EOL>if min_num is None:<EOL><INDENT>min_num = <NUM_LIT:0><EOL><DEDENT>attrs = {'<STR_LIT>': form, '<STR_LIT>': extra,<EOL>'<STR_LIT>': can_order, '<STR_LIT>': can_delete, '<STR_LIT>': min_num,<EOL>'<STR_LIT>': max_num, '<STR_LIT>': absolute_max, '<STR_LIT>': validate_min,<EOL>'<STR_LIT>': validate_max}<EOL>return type(form.__name__ + str('<STR_LIT>'), (formset,), attrs)<EOL>
Return a FormSet for the given form class.
f15071:m0
def build_attrs(self, *args, **kwargs):
self.attrs = self.widget.build_attrs(*args, **kwargs)<EOL>return self.attrs<EOL>
Helper function for building an attribute dictionary.
f15074:c0:m3
def get_template_substitution_values(self, value):
return {<EOL>'<STR_LIT>': os.path.basename(conditional_escape(value)),<EOL>'<STR_LIT>': conditional_escape(value.url),<EOL>}<EOL>
Return value-related substitutions.
f15074:c3:m1
@cached_property<EOL><INDENT>def is_restricted(self):<DEDENT>
return (<EOL>not hasattr(self.choices, '<STR_LIT>') or<EOL>self.choices.queryset.count() > settings.FOREIGN_KEY_MAX_SELECBOX_ENTRIES<EOL>)<EOL>
Returns True or False according to number of objects in queryset. If queryset contains too much objects the widget will be restricted and won't be used select box with choices.
f15074:c25:m0
def humanized_model_to_dict(instance, readonly_fields, fields=None, exclude=None):
opts = instance._meta<EOL>data = {}<EOL>for f in itertools.chain(opts.concrete_fields, opts.private_fields, opts.many_to_many):<EOL><INDENT>if not getattr(f, '<STR_LIT>', False):<EOL><INDENT>continue<EOL><DEDENT>if fields and f.name not in fields:<EOL><INDENT>continue<EOL><DEDENT>if f.name not in readonly_fields:<EOL><INDENT>continue<EOL><DEDENT>if exclude and f.name in exclude:<EOL><INDENT>continue<EOL><DEDENT>if f.humanized:<EOL><INDENT>data[f.name] = f.humanized(getattr(instance, f.name), instance)<EOL><DEDENT><DEDENT>return data<EOL>
Returns a dict containing the humanized data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument. ``fields`` is an optional list of field names. If provided, only the named fields will be included in the returned dict. ``exclude`` is an optional list of field names. If provided, the named fields will be excluded from the returned dict, even if they are listed in the ``fields`` argument.
f15076:m0
def has_permission(self, name, request, view, obj=None):
raise NotImplementedError<EOL>
Checks if request has permission to the given action. Args: name (str): name of the permission request (django.http.request.HttpRequest): Django request object view (object): Django view or REST view object obj (object): Object that is related with the given request Returns: True/False
f15088:c0:m0
def __init__(self, **permissions_set):
super().__init__()<EOL>self._permissions = permissions_set<EOL>
Args: **permissions_set (BasePermission): permissions data
f15088:c5:m0
def set(self, name, permission):
assert isinstance(permission, BasePermission), '<STR_LIT>'<EOL>self._permissions[name] = permission<EOL>
Adds permission with the given name to the set. Permission with the same name will be overridden. Args: name: name of the permission permission: permission instance
f15088:c5:m1
def compare_json(j1: str, j2: str, log: TextIO) -> bool:
d1 = jao_loads(j1)<EOL>d2 = jao_loads(j2)<EOL>return compare_dicts(as_dict(d1), as_dict(d2), file=log)<EOL>
Compare two JSON strings
f15161:m0
def validate_shexj_json(json_str: str, input_fname: str, parser: JSGPython) -> bool:
rslt = parser.conforms(json_str, input_fname)<EOL>if not rslt.success:<EOL><INDENT>print("<STR_LIT>".format(input_fname))<EOL>print(str(rslt.fail_reason))<EOL>return False<EOL><DEDENT>else:<EOL><INDENT>log = StringIO()<EOL>if not compare_json(json_str, as_json(parser.json_obj), cast(TextIO, log)):<EOL><INDENT>print("<STR_LIT>".format(input_fname))<EOL>print(log.getvalue())<EOL>print(as_json(parser.json_obj))<EOL>return False<EOL><DEDENT><DEDENT>return True<EOL>
Validate json_str against ShEx Schema :param json_str: String to validate :param input_fname: Name of source file for error reporting :param parser: JSGPython parser :return: True if pass
f15161:m1
def download_github_file(github_url: str) -> Optional[str]:
print("<STR_LIT>".format(github_url))<EOL>resp = requests.get(github_url)<EOL>if resp.ok:<EOL><INDENT>resp = requests.get(resp.json()['<STR_LIT>'])<EOL>if resp.ok:<EOL><INDENT>return resp.text<EOL><DEDENT><DEDENT>print("<STR_LIT>".format(resp.status_code, resp.reason))<EOL>return None<EOL>
Download the file in github_url :param github_url: github url to download :return: file contents if success, None otherwise
f15161:m2
def parse(text: str, production_rule: str, listener) -> Optional[jsgParserVisitor]:
error_listener = ParseErrorListener()<EOL>lexer = jsgLexer(InputStream(text))<EOL>lexer.addErrorListener(error_listener)<EOL>tokens = CommonTokenStream(lexer)<EOL>tokens.fill()<EOL>if error_listener.n_errors:<EOL><INDENT>return None<EOL><DEDENT>parser = jsgParser(tokens)<EOL>parser.addErrorListener(error_listener)<EOL>base_node = getattr(parser, production_rule)()<EOL>listener_module = listener(JSGDocContext())<EOL>listener_module.visit(base_node)<EOL>return listener_module if not error_listener.n_errors else None<EOL>
Parse text fragment according to supplied production rule and evaluate with listener class. Example: parse("{1,*}", "ebnfSuffix", JSGEbnf)
f15162:m0
def genargs() -> ArgumentParser:
parser = ArgumentParser()<EOL>parser.add_argument("<STR_LIT>", help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", "<STR_LIT>", help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", "<STR_LIT>", help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", "<STR_LIT>", help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", "<STR_LIT>", help="<STR_LIT>", nargs='<STR_LIT:*>')<EOL>return parser<EOL>
Create a command line parser :return: parser
f15206:m0
def __init__(self, jsg: Optional[str]=None, python: Optional[str]=None, print_python: bool=False) -> None:
if jsg is not None:<EOL><INDENT>self.schema = self._to_string(jsg) if not self._is_jsg(jsg) else jsg<EOL><DEDENT>else:<EOL><INDENT>self.schema = None<EOL><DEDENT>self.python = parse(self.schema, self.__class__.__name__) if self.schema else self._to_string(python)<EOL>if print_python:<EOL><INDENT>print(self.python)<EOL><DEDENT>self.json_obj = None<EOL>if not self.python:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>spec = compile(self.python, self.__class__.__name__, '<STR_LIT>')<EOL>self.module = ModuleType(self.__class__.__name__)<EOL>exec(spec, self.module.__dict__)<EOL>
Construct a jsg validation module :param jsg: JSG specification. If none, use python :param python: Python specification. :param print_python: True means print Python to stdout
f15206:c1:m0
@staticmethod<EOL><INDENT>def _is_jsg(s: str) -> bool:<DEDENT>
return isinstance(s, str) and ('<STR_LIT:\n>' in s or '<STR_LIT:{>' in s)<EOL>
Determine whether s looks like a JSG spec
f15206:c1:m1
@staticmethod<EOL><INDENT>def is_json(s: str) -> bool:<DEDENT>
return s.strip().startswith(('<STR_LIT:{>', '<STR_LIT:[>'))<EOL>
Determine whether s looks like JSON
f15206:c1:m2
@staticmethod<EOL><INDENT>def _to_string(inp: str) -> str:<DEDENT>
if '<STR_LIT>' in inp:<EOL><INDENT>req = requests.get(inp)<EOL>if not req.ok:<EOL><INDENT>raise ValueError(f"<STR_LIT>")<EOL><DEDENT>return req.text<EOL><DEDENT>else:<EOL><INDENT>with open(inp) as infile:<EOL><INDENT>return infile.read()<EOL><DEDENT><DEDENT>
Convert a URL or file name to a string
f15206:c1:m3
def conforms(self, json: str, name: str = "<STR_LIT>", verbose: bool=False) -> ValidationResult:
json = self._to_string(json) if not self.is_json(json) else json<EOL>try:<EOL><INDENT>self.json_obj = loads(json, self.module)<EOL><DEDENT>except ValueError as v:<EOL><INDENT>return ValidationResult(False, str(v), name, None)<EOL><DEDENT>logfile = StringIO()<EOL>logger = Logger(cast(TextIO, logfile)) <EOL>if not is_valid(self.json_obj, logger):<EOL><INDENT>return ValidationResult(False, logfile.getvalue().strip('<STR_LIT:\n>'), name, None)<EOL><DEDENT>return ValidationResult(True, "<STR_LIT>", name, type(self.json_obj).__name__)<EOL>
Determine whether json conforms with the JSG specification :param json: JSON string, URI to JSON or file name with JSON :param name: Test name for ValidationResult -- printed in dx if present :param verbose: True means print the response :return: pass/fail + fail reason
f15206:c1:m4
@abstractmethod<EOL><INDENT>def _is_valid(self, log: Optional[Union[TextIO, Logger]] = None) -> bool:<DEDENT>
raise NotImplementedError("<STR_LIT>")<EOL>
Determine whether the element is valid :param log: Logger or IO device to record errors :return: True if valid, false otherwise
f15208:c0:m0
def proc_forward(etype, namespace: Dict[str, Any]):
return etype._eval_type(namespace, namespace) if type(etype) is _ForwardRef else etype<EOL>
Resolve etype to an actual type if it is a forward reference
f15209:m0
def is_union(etype) -> bool:
return type(etype) == type(Union)<EOL>
Determine whether etype is a Union
f15209:m1
def is_dict(etype) -> bool:
return type(etype) is GenericMeta and etype.__extra__ is dict<EOL>
Determine whether etype is a Dict
f15209:m2
def is_iterable(etype) -> bool:
return type(etype) is GenericMeta and issubclass(etype.__extra__, Iterable)<EOL>
Determine whether etype is a List or other iterable
f15209:m3
def union_conforms(element: Union, etype, namespace: Dict[str, Any], conforms: Callable) -> bool:
union_vals = etype.__union_params__ if sys.version_info < (<NUM_LIT:3>, <NUM_LIT:6>) else etype.__args__<EOL>return any(conforms(element, t, namespace) for t in union_vals)<EOL>
Determine whether element conforms to at least one of the types in etype :param element: element to test :param etype: type to test against :param namespace: Namespace to use for resolving forward references :param conforms: conformance test function :return: True if element conforms to at least one type in etype
f15209:m4
def unvalidated_parm(self, parm: str) -> bool:
return parm.startswith("<STR_LIT:_>") or parm == self.TYPE or parm in self.IGNORE or(self.JSON_LD and parm.startswith('<STR_LIT:@>'))<EOL>
Return true if the pair name should be ignored :param parm: string part of pair string:value :return: True if it should be accepted
f15211:c0:m1
def loads_loader(load_module: types.ModuleType, pairs: Dict[str, str]) -> Optional[JSGValidateable]:
cntxt = load_module._CONTEXT<EOL>possible_type = pairs[cntxt.TYPE] if cntxt.TYPE in pairs else None<EOL>target_class = getattr(load_module, possible_type, None) if isinstance(possible_type, str) else None<EOL>if target_class:<EOL><INDENT>return target_class(**pairs)<EOL><DEDENT>for type_exception in cntxt.TYPE_EXCEPTIONS:<EOL><INDENT>if not hasattr(load_module, type_exception):<EOL><INDENT>raise ValueError(UNKNOWN_TYPE_EXCEPTION.format(type_exception))<EOL><DEDENT>target_class = getattr(load_module, type_exception)<EOL>target_strict = target_class._strict<EOL>target_class._strict = False<EOL>try:<EOL><INDENT>rval = target_class(**pairs)<EOL><DEDENT>finally:<EOL><INDENT>target_class._strict = target_strict<EOL><DEDENT>if is_valid(rval):<EOL><INDENT>return rval<EOL><DEDENT><DEDENT>if not cntxt.TYPE and cntxt.TYPE_EXCEPTIONS:<EOL><INDENT>return getattr(load_module, cntxt.TYPE_EXCEPTIONS[<NUM_LIT:0>])(**pairs)<EOL><DEDENT>if cntxt.TYPE in pairs:<EOL><INDENT>raise ValueError(f'<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(f'<STR_LIT>')<EOL><DEDENT>
json loader objecthook :param load_module: Module that contains the various types :param pairs: key/value tuples (In our case, they are str/str) :return:
f15212:m0
def loads(s: str, load_module: types.ModuleType, **kwargs):
return json.loads(s, object_hook=lambda pairs: loads_loader(load_module, pairs), **kwargs)<EOL>
Convert a JSON string into a JSGObject :param s: string representation of JSON document :param load_module: module that contains declarations for types :param kwargs: arguments see: json.load for details :return: JSGObject representing the json string
f15212:m1
def load(fp: Union[TextIO, str], load_module: types.ModuleType, **kwargs):
if isinstance(fp, str):<EOL><INDENT>with open(fp) as f:<EOL><INDENT>return loads(f.read(), load_module, **kwargs)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return loads(fp.read(), load_module, **kwargs)<EOL><DEDENT>
Convert a file name or file-like object containing stringified JSON into a JSGObject :param fp: file-like object to deserialize :param load_module: module that contains declarations for types :param kwargs: arguments see: json.load for details :return: JSGObject representing the json string
f15212:m2
def isinstance_(x, A_tuple):
if is_union(A_tuple):<EOL><INDENT>return any(isinstance_(x, t) for t in A_tuple.__args__)<EOL><DEDENT>elif getattr(A_tuple, '<STR_LIT>', None) is not None:<EOL><INDENT>return isinstance(x, A_tuple.__origin__)<EOL><DEDENT>else:<EOL><INDENT>return isinstance(x, A_tuple)<EOL><DEDENT>
native isinstance_ with the test for typing.Union overridden
f15212:m3
def is_valid(obj: JSGValidateable, log: Optional[Union[TextIO, Logger]] = None) -> bool:
return obj._is_valid(log)<EOL>
Determine whether obj is valid :param obj: Object to validate :param log: Logger to record validation failures. If absent, no information is recorded
f15212:m4
def __init__(self, pattern: str):
self.pattern_re = re.compile(pattern, flags=re.DOTALL)<EOL>
Compile and record a match pattern :param pattern: regular expression
f15214:c0:m0
def matches(self, txt: str) -> bool:
<EOL>if r'<STR_LIT>' in self.pattern_re.pattern:<EOL><INDENT>txt = txt.encode('<STR_LIT:utf-8>').decode('<STR_LIT>')<EOL><DEDENT>match = self.pattern_re.match(txt)<EOL>return match is not None and match.end() == len(txt)<EOL>
Determine whether txt matches pattern :param txt: text to check :return: True if match
f15214:c0:m2
def element_conforms(element, etype) -> bool:
from pyjsg.jsglib import Empty<EOL>if isinstance(element, etype):<EOL><INDENT>return True<EOL><DEDENT>if (element is None or element is Empty) and issubclass(etype, type(None)):<EOL><INDENT>return True<EOL><DEDENT>elif element is Empty:<EOL><INDENT>return False<EOL><DEDENT>elif isinstance(etype, type(type)) and (issubclass(etype, type(None))):<EOL><INDENT>return element is None<EOL><DEDENT>elif element is None:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return isinstance(element, etype)<EOL><DEDENT>
Determine whether element conforms to etype
f15215:m0
def conforms(element, etype, namespace: Dict[str, Any]) -> bool:
etype = proc_forward(etype, namespace)<EOL>if is_union(etype):<EOL><INDENT>return union_conforms(element, etype, namespace, conforms)<EOL><DEDENT>else:<EOL><INDENT>return element_conforms(element, etype)<EOL><DEDENT>
Determine whether element conforms to etype :param element: Element to test for conformance :param etype: Type to test against :param namespace: Namespace to use to resolve forward references :return:
f15215:m1
def __setattr__(self, key: str, value: Any):
if not key.startswith("<STR_LIT:_>") and not self._context.unvalidated_parm(key):<EOL><INDENT>if self._name_filter is not None:<EOL><INDENT>if not isinstance(key, self._name_filter):<EOL><INDENT>raise ValueError(f"<STR_LIT>")<EOL><DEDENT><DEDENT>if not conforms(value, self._value_type, self._context.NAMESPACE):<EOL><INDENT>raise ValueError("<STR_LIT>".format(key, value))<EOL><DEDENT>if not isinstance(value, JSGValidateable):<EOL><INDENT>value = self._value_type('<STR_LIT>', self._context, value)if self._value_type is AnyType else self._value_type(value)<EOL><DEDENT><DEDENT>self[key] = value<EOL>
Screen attributes for name and type. Anything starting with underscore ('_') goes, anything in the IGNORE list and anything declared in the __init_ signature :param key: :param value: :return:
f15216:c0:m0
def __init__(self, variable_name: str, context: JSGContext, typ, min_: int, max_: Optional[int],<EOL>value: Optional[list]) -> None:
self._variable_name = variable_name<EOL>self._context = context<EOL>self._type = typ<EOL>self._min: int = min_<EOL>self._max: Optional[int] = max_<EOL>if value is not None:<EOL><INDENT>isvalid, errors = self._validate(value)<EOL>if not isvalid:<EOL><INDENT>raise ValueError("<STR_LIT:\n>".join(errors))<EOL><DEDENT><DEDENT>super().__init__([] if value is None else value)<EOL>
Construct an array holder :param variable_name: Name assigned to the variable. Used for error reporting :param context: Supporting context :param typ: array type :param min_: minimum number of elements :param max_: maximum number of elements (None means '*') :param value: Initializer
f15217:c0:m0
def _is_valid(self, log: Optional[Logger] = None) -> bool:
return self._validate(self, log)[<NUM_LIT:0>]<EOL>
Determine whether the current contents are valid
f15217:c0:m1
def _validate(self, val: list, log: Optional[Logger] = None) -> Tuple[bool, List[str]]:
errors = []<EOL>if not isinstance(val, list):<EOL><INDENT>errors.append(f"<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>for i in range(<NUM_LIT:0>, len(val)):<EOL><INDENT>v = val[i]<EOL>if not conforms(v, self._type, self._context.NAMESPACE):<EOL><INDENT>errors.append(f"<STR_LIT>")<EOL><DEDENT><DEDENT>if len(val) < self._min:<EOL><INDENT>errors.append(<EOL>f"<STR_LIT>"<EOL>f"<STR_LIT>")<EOL><DEDENT>if self._max is not None and len(val) > self._max:<EOL><INDENT>errors.append(<EOL>f"<STR_LIT>")<EOL><DEDENT><DEDENT>if log:<EOL><INDENT>for error in errors:<EOL><INDENT>log.log(error)<EOL><DEDENT><DEDENT>return not bool(errors), errors<EOL>
Determine whether val is a valid instance of this array :returns: Success indicator and error list
f15217:c0:m2
def __init__(self, variable_name: str, context: JSGContext, value: Any, **kwargs):
match = False<EOL>if isinstance(value, list):<EOL><INDENT>self.val = JSGArray(variable_name, context, AnyType, <NUM_LIT:0>, None, value)<EOL><DEDENT>else:<EOL><INDENT>for t in any_types:<EOL><INDENT>if isinstance(value, t):<EOL><INDENT>self.val = t(value)<EOL>match = True<EOL>break<EOL><DEDENT><DEDENT>if not match:<EOL><INDENT>self.val = value<EOL><DEDENT><DEDENT>super().__init__(**kwargs)<EOL>
Construct a wild card variable :param variable_name: name of attribute for error reporting :param context: context for use in JSGArrays :param val: value :param kwargs: named arguments
f15218:c1:m0
def proc_forward(etype, namespace: Dict[str, Any]):
return etype._evaluate(namespace, namespace) if type(etype) is ForwardRef else etype<EOL>
Resolve etype to an actual type if it is a forward reference
f15219:m0
def is_union(etype) -> bool:
return getattr(etype, '<STR_LIT>', None) is not None andgetattr(etype.__origin__, '<STR_LIT>', None) andetype.__origin__._name == '<STR_LIT>'<EOL>
Determine whether etype is a Union
f15219:m1