Extract request fields wherever they may come from: GET, POST, forms, fallback
429193
def _request(request, request_fallback=None):
        '''  '''
        # Use lambdas to avoid evaluating bottle.request.* which may throw an Error
        all_dicts = [
            lambda: request.json,
            lambda: request.forms,
            lambda: request.query,
            lambda: request.files,
            #lambda: request.POST,
            lambda: request_fallback
        ]
        request_dict = dict()
        for req_dict_ in all_dicts:
            try:
                req_dict = req_dict_()
            except KeyError:
                continue
            if req_dict is not None and hasattr(req_dict, 'items'):
                for req_key, req_val in req_dict.items():
                    request_dict[req_key] = req_val
        return request_dict
993357
def fetch_post_data(self):
        '''
        
        '''
        post_data = {}
        ext_dic = {}
        for key in self.request.arguments:
            if key.startswith('def_'):
                ext_dic[key] = self.get_argument(key)
            else:
                post_data[key] = self.get_arguments(key)[0]

        post_data['user_name'] = self.userinfo.user_name

        ext_dic = dict(ext_dic, **self.ext_post_data(postdata=post_data))

        return (post_data, ext_dic)
947787
def get(self, url, params=None, headers=None, content=None, form_content=None):
        # type: (str, Optional[Dict[str, str]], Optional[Dict[str, str]], Any, Optional[Dict[str, Any]]) -> ClientRequest
        
        request = self._request('GET', url, params, headers, content, form_content)
        request.method = 'GET'
        return request
850038
def get_search_form(self):
        
        magic_dico_form = self.get_dict_for_forms()
        forms = []
        initial = list(self.request.GET.lists())

        for key, value in magic_dico_form.items():
            form = Form()
            model = value["model"]
            if not value["fields"]:
                continue
            for field in value["fields"]:
                formfield = get_formfield(model, field)
                formfield.widget.attrs.update({'class': self.css_class})
                form.fields.update({
                    field : formfield
                })

            initial_tmp = {}
            for k, vals in initial:
                tmp_list = k.split(model.__name__ + "-")
                if len(tmp_list) == 2:
                    list_val_tmp = vals[0] if len(vals) == 1 else [val for val in vals if val != '']
                    initial_tmp[tmp_list[-1]] = list_val_tmp

            form.initial = initial_tmp
            form.prefix = model.__name__
            forms.append(form)
        return sorted(forms, key=lambda form: form.prefix)
629669
def get(self, request, *args, **kwargs):
        

        # Prepare base
        if 'pk' in kwargs:
            self.object = self.get_object()
        else:
            self.object = None
        form_class = self.get_form_class()

        # Get prefix
        if 'field_prefix' in form_class.Meta.__dict__:
            # Get name from the form
            field_prefix = form_class.Meta.field_prefix
        else:
            # Get name from the class
            field_prefix = str(form_class).split("'")[1].split(".")[-1]
        self.field_prefix = field_prefix

        # Build form
        form = self.get_form(form_class)

        # Find groups
        if 'groups' in dir(self):
            # Save groups
            groups = self.groups
            # Redefine groups inside the form
            form.__groups__ = lambda: groups
            # Initialize list of fields
            fields = []
        else:
            groups = None

        # Add special prefix support to properly support form independency
        form.add_prefix = lambda fields_name, field_prefix=field_prefix: "%s_%s" % (field_prefix, fields_name)
        if 'autofill' not in dir(form.Meta):
            form.Meta.autofill = {}

        # For every extra form
        forms = []
        position_form_default = 0
        for (formelement, linkerfield, modelfilter) in self.forms:
            if formelement is None:
                formobj = form
                position_form_default = len(forms)
            else:
                # Locate linked element
                if self.object:
                    related_name = formelement._meta.model._meta.get_field(linkerfield).related_query_name()
                    queryset = getattr(self.object, related_name)
                    if modelfilter:
                        queryset = queryset.filter(eval("Q(%s)" % (modelfilter)))
                    get_method = getattr(queryset, 'get', None)
                    if get_method:
                        instance = queryset.get()
                    else:
                        instance = queryset
                else:
                    instance = None

                if 'autofill' in dir(formelement.Meta):
                    formname = str(formelement).split('.')[-1].split("'")[0]
                    for key in formelement.Meta.autofill:
                        form.Meta.autofill['{}_{}'.format(formname, key)] = formelement.Meta.autofill[key]

                # Get prefix
                if 'field_prefix' in formelement.Meta.__dict__:
                    # Get name from the form
                    field_prefix = formelement.Meta.field_prefix
                else:
                    # Get name from the class
                    field_prefix = str(formelement).split("'")[1].split(".")[-1]
                self.field_prefix = field_prefix

                # Prepare form
                formobj = formelement(instance=instance)
                formobj.form_name = form.form_name

                # Excluded fields
                if 'exclude' not in formobj.Meta.__dict__:
                    formobj.Meta.exclude = [linkerfield]
                elif linkerfield not in formobj.Meta.exclude:
                    formobj.Meta.exclude.append(linkerfield)
                if linkerfield in formobj.fields:
                    del(formobj.fields[linkerfield])

                # Add special prefix support to properly support form independency
                formobj.add_prefix = lambda fields_name, field_prefix=field_prefix: "%s_%s" % (field_prefix, fields_name)
                formobj.scope_prefix = field_prefix

            # Save fields to the list
            if groups:
                for field in formobj:
                    fields.append(field)
            else:
                # Add the form to the list of forms
                forms.append(formobj)

        if position_form_default == 0:
            open_tabs = 1
        else:
            open_tabs = 0
        # Remember list of fields
        if groups:
            form.list_fields = fields

        # Add context and return new context
        return self.render_to_response(self.get_context_data(form=form, forms=forms, open_tabs=open_tabs, position_form_default=position_form_default))
583722
def _link_fields(self):
        """"""
        query_params = self.get_request_attribute('query_params', {})
        if 'exclude_links' in query_params:
            return {}
        else:
            all_fields = self.get_all_fields()
            return {
                name: field for name, field in six.iteritems(all_fields)
                if isinstance(field, DynamicRelationField) and
                getattr(field, 'link', True) and
                not (
                    # Skip sideloaded fields
                    name in self.fields and
                    self.is_field_sideloaded(name)
                ) and not (
                    # Skip included single relations
                    # TODO: Use links, when we can generate canonical URLs
                    name in self.fields and
                    not getattr(field, 'many', False)
                )
            }
1366908
def extract_params(env)
      result = env.fetch(QUERY_HASH, {})
      result.merge!(env.fetch(FORM_HASH, {}))
      result.merge!(Utils::Hash.deep_stringify(env.fetch(ROUTER_PARAMS, {})))
      result
    end
997044
def get_form(self, request, obj=None, **kwargs):
        """"""

        template = get_template_from_request(request, obj)

        #model = create_page_model(get_placeholders(template))

        form = make_form(self.model, get_placeholders(template))

        # bound the form
        language = get_language_from_request(request)
        form.base_fields['language'].initial = language
        if obj:
            initial_slug = obj.slug(language=language, fallback=False)
            initial_title = obj.title(language=language, fallback=False)
            form.base_fields['slug'].initial = initial_slug
            form.base_fields['title'].initial = initial_title

        template = get_template_from_request(request, obj)
        page_templates = settings.get_page_templates()
        template_choices = list(page_templates)
        # is default template is not in the list add it
        if not [tpl for tpl in template_choices if tpl[0] == settings.PAGE_DEFAULT_TEMPLATE]:
            template_choices.insert(0, (settings.PAGE_DEFAULT_TEMPLATE,
                    _('Default template')))
        form.base_fields['template'].choices = template_choices
        form.base_fields['template'].initial = force_text(template)

        for placeholder in get_placeholders(template):
            ctype = placeholder.ctype
            if obj:
                initial = placeholder.get_content(obj, language, lang_fallback=False)
            else:
                initial = None
            form.base_fields[ctype] = placeholder.get_field(obj,
                language, initial=initial)

        return form
902100
def get_placeholder_data(self, request, obj=None):
        
        # Return all placeholder fields in the model.
        if not hasattr(self.model, '_meta_placeholder_fields'):
            return []

        data = []
        for name, field in self.model._meta_placeholder_fields.items():
            assert isinstance(field, PlaceholderField)
            data.append(PlaceholderData(
                slot=field.slot,
                title=field.verbose_name.capitalize(),
                fallback_language=None,  # Information cant' be known by "render_placeholder" in the template.
            ))

        return data
1146214
def get_post_data(self, request):
        
        params = dict(request.POST)
        params.update(request.FILES)

        data = defaultdict(dict)

        # Split data and meta parameters
        for param in sorted(params.keys()):
            value = params[param]

            if isinstance(value, list) and len(value) <= 1:
                value = value[0] if value else None

            prefix, _, field = param.partition('[')
            if field:
                field = field[:-1]
                try:
                    data[prefix][field] = value
                except TypeError:
                    raise InvalidNodeData('Got both reserved parameter "data" and plugin specific parameters.')
            else:
                data[prefix] = value

        return data['data'], data['meta']
1060913
def _get_fieldsets_post_form_or_formset(self, request, form, obj=None):
        
        base_fields = self.replace_orig_field(form.base_fields.keys())
        fields = base_fields + list(self.get_readonly_fields(request, obj))
        return [(None, {'fields': self.replace_orig_field(fields)})]
494540
async def parse_form(self, req: Request, name: str, field: Field) -> typing.Any:
        """"""
        post_data = self._cache.get("post")
        if post_data is None:
            self._cache["post"] = await req.post()
        return core.get_value(self._cache["post"], name, field)
448264
function getFormFields(form) {
  // Grab all fields that are enabled, and return them as an array.
  // If enabled, remove that property and apply the field name.
  var fields = Object.keys(form.fields).reduce(function (result, fieldKey) {
    var field = _.clone(form.fields[fieldKey]);

    if (!field.enabled) {
      return result;
    }

    // Append the field to field order in case it's not present.
    if (form.fieldOrder.indexOf(fieldKey) === -1) {
      form.fieldOrder.push(fieldKey);
    }

    field.name = fieldKey;
    delete field.enabled;

    result.push(field);

    return result;
  }, []);

  // Sort fields by the defined fieldOrder.
  // Fields that are not in fieldOrder will be placed at the end of the array.
  fields.sort(function (a, b) {
    var indexA = form.fieldOrder.indexOf(a.name);
    var indexB = form.fieldOrder.indexOf(b.name);

    if (indexA === -1) {
      return 0;
    }

    if (indexB === -1) {
      return -1;
    }

    if (indexA > indexB) {
      return 1;
    }

    if (indexA < indexB) {
      return -1;
    }

    return 0;
  });

  return fields;
}
442866
def get_form(self, request, obj=None, **kwargs):
        
        language = get_language_from_request(request)
        form = super(ArticleAdmin, self).get_form(
            request, obj,
            form=(obj and ArticleForm or ArticleCreateForm),
            **kwargs
        )
        # get_form method operates by overriding initial fields value which
        # may persist across invocation. Code below deepcopies fields definition
        # to avoid leaks
        for field in tuple(form.base_fields.keys()):
            form.base_fields[field] = copy.deepcopy(form.base_fields[field])

        if 'language' in form.base_fields:
            form.base_fields['language'].initial = language

        if obj:
            title_obj = obj.get_title_obj(language=language, fallback=False, force_reload=True)

            if hasattr(title_obj, 'id'):
                for name in ('title', 'description', 'page_title', 'menu_title', 'meta_description', 'image'):
                    if name in form.base_fields:
                        form.base_fields[name].initial = getattr(title_obj, name)
                try:
                    slug = self.SLUG_REGEXP.search(title_obj.slug).groups()[settings.CMS_ARTICLES_SLUG_GROUP_INDEX]
                except AttributeError:
                    warnings.warn('Failed to parse slug from CMS_ARTICLES_SLUG_REGEXP. '
                                  'It probably doesn\'t correspond to CMS_ARTICLES_SLUG_FORMAT.')
                    slug = title_obj.slug
                form.base_fields['slug'].initial = slug

        return form
447203
function getFormData(form) {
    var elements = form.elements;

    var fields = Object.keys(elements).filter(function(k) {
          return (elements[k].name !== "honeypot");
    }).map(function(k) {
      if(elements[k].name !== undefined) {
        return elements[k].name;
      // special case for Edge's html collection
      }else if(elements[k].length > 0){
        return elements[k].item(0).name;
      }
    }).filter(function(item, pos, self) {
      return self.indexOf(item) == pos && item;
    });

    var formData = {};
    fields.forEach(function(name){
      var element = elements[name];
      
      // singular form elements just have one value
      formData[name] = element.value;

      // when our element has multiple items, get their values
      if (element.length) {
        var data = [];
        for (var i = 0; i < element.length; i++) {
          var item = element.item(i);
          if (item.checked || item.selected) {
            data.push(item.value);
          }
        }
        formData[name] = data.join(', ');
      }
    });

    // add form-specific values into the data
    formData.formDataNameOrder = JSON.stringify(fields);
    formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name
    formData.formGoogleSendEmail = form.dataset.email || ""; // no email by default

    console.log(formData);
    return formData;
  }
557779
def get_form_kwargs(self):
        

        kwargs = {}
        for key in six.iterkeys(self.form_classes):
            if self.request.method in ('POST', 'PUT'):
                kwargs[key] = {
                    'data': self.request.POST,
                    'files': self.request.FILES,
                }
            else:
                kwargs[key] = {}
        return kwargs
1103286
def _gen_form_data(self) -> multipart.MultipartWriter:
        """"""
        for dispparams, headers, value in self._fields:
            try:
                if hdrs.CONTENT_TYPE in headers:
                    part = payload.get_payload(
                        value, content_type=headers[hdrs.CONTENT_TYPE],
                        headers=headers, encoding=self._charset)
                else:
                    part = payload.get_payload(
                        value, headers=headers, encoding=self._charset)
            except Exception as exc:
                raise TypeError(
                    'Can not serialize value type: %r\n '
                    'headers: %r\n value: %r' % (
                        type(value), headers, value)) from exc

            if dispparams:
                part.set_content_disposition(
                    'form-data', quote_fields=self._quote_fields, **dispparams
                )
                # FIXME cgi.FieldStorage doesn't likes body parts with
                # Content-Length which were sent via chunked transfer encoding
                assert part.headers is not None
                part.headers.popall(hdrs.CONTENT_LENGTH, None)

            self._writer.append_payload(part)

        return self._writer