Generate HTTP parameters for passing to Solr.

        In general you should not need to call this directly, calling exec() on a query object
        will transparently perform this step for you.
426406
def solr_params(self):
        

        ## Main query params for solr
        fq=self.fq
        if fq is None:
            fq = {}
        logging.info("TEMPx FQ={}".format(fq))

        # subject_or_object_ids is a list of identifiers that can be matched to either subjects or objects
        subject_or_object_ids = self.subject_or_object_ids
        if subject_or_object_ids is not None:
            subject_or_object_ids = [self.make_canonical_identifier(c) for c in subject_or_object_ids]

        # canonical form for MGI is a CURIE MGI:nnnn
        #if subject is not None and subject.startswith('MGI:MGI:'):
        #    logging.info('Unhacking MGI ID presumably from GO:'+str(subject))
        #    subject = subject.replace("MGI:MGI:","MGI")
        subject=self.subject
        if subject is not None:
            subject = self.make_canonical_identifier(subject)
        subjects=self.subjects
        if subjects is not None:
            subjects = [self.make_canonical_identifier(s) for s in subjects]

        # temporary: for querying go solr, map fields. TODO
        object_category=self.object_category
        logging.info("Object category: {}".format(object_category))

        object=self.object
        if object_category is None and object is not None and object.startswith('GO:'):
            # Infer category
            object_category = 'function'
            logging.info("Inferring Object category: {} from {}".
                         format(object_category, object))

        solr_config = {'url': self.url, 'timeout': 5}
        if self.solr is None:
            if self.url is None:
                endpoint = self.get_config().solr_assocs
                solr_config = {'url': endpoint.url, 'timeout': endpoint.timeout}
            else:
                solr_config = {'url': self.url, 'timeout': 5}

        # URL to use for querying solr
        if self._use_amigo_schema(object_category):
            if self.url is None:
                endpoint = self.get_config().amigo_solr_assocs
                solr_config = {'url': endpoint.url, 'timeout': endpoint.timeout}
            self.field_mapping=goassoc_fieldmap(self.relationship_type)

            # awkward hack: we want to avoid typing on the amigo golr gene field,
            # UNLESS this is a planteome golr
            if "planteome" in self.get_config().amigo_solr_assocs.url:
                self.field_mapping[M.SUBJECT_CATEGORY] = 'type'

            fq['document_category'] = 'annotation'
            if subject is not None:
                subject = self.make_gostyle_identifier(subject)
            if subjects is not None:
                subjects = [self.make_gostyle_identifier(s) for s in subjects]

            # the AmiGO schema lacks an object_category field;
            # we could use the 'aspect' field but instead we use a mapping of
            # the category to a root class
            if object_category is not None:
                cc = self.get_config().get_category_class(object_category)
                if cc is not None and object is None:
                    object = cc

        self.update_solr_url(**solr_config)

        ## subject params
        subject_taxon=self.subject_taxon
        subject_category=self.subject_category

        # heuristic procedure to guess unspecified subject_category
        if subject_category is None and subject is not None:
            subject_category = self.infer_category(subject)

        if subject_category is not None and subject_category == 'disease':
            if subject_taxon is not None and subject_taxon=='NCBITaxon:9606':
                logging.info("Unsetting taxon, until indexed correctly")
                subject_taxon = None

        if self.invert_subject_object is None:
            # TODO: consider placing in a separate lookup
            p = (subject_category, object_category)
            if p == ('disease', 'gene'):
                self.invert_subject_object = True
            elif p == ('disease', 'model'):
                self.invert_subject_object = True
            else:
                self.invert_subject_object = False
            if self.invert_subject_object:
                logging.info("Inferred that subject/object should be inverted for {}".format(p))

        ## taxon of object of triple
        object_taxon=self.object_taxon

        # typically information is stored one-way, e.g. model-disease;
        # sometimes we want associations from perspective of object
        if self.invert_subject_object:
            (subject,object) = (object,subject)
            (subject_category,object_category) = (object_category,subject_category)
            (subject_taxon,object_taxon) = (object_taxon,subject_taxon)

        ## facet fields
        facet_fields=self.facet_fields
        facet_on=self.facet_on
        facet_limit=self.facet_limit
        select_fields=self.select_fields

        if self.use_compact_associations:
            facet_fields = []
            facet_on = 'off'
            facet_limit = 0
            select_fields = [
                M.SUBJECT,
                M.SUBJECT_LABEL,
                M.RELATION,
                M.OBJECT]

        if subject_category is not None:
            fq['subject_category'] = subject_category
        if object_category is not None:
            fq['object_category'] = object_category


        if object is not None:
            # TODO: make configurable whether to use closure
            fq['object_closure'] = object
        if subject is not None:
            # note: by including subject closure by default,
            # we automaticaly get equivalent nodes
            if self.subject_direct:
                fq['subject'] = subject
            else:
                fq['subject_closure'] = subject
        if subjects is not None:
            # lists are assumed to be disjunctive
            if self.subject_direct:
                fq['subject'] = subjects
            else:
                fq['subject_closure'] = subjects

        objects=self.objects
        if objects is not None:
            # lists are assumed to be disjunctive
            fq['object_closure'] = objects
        relation=self.relation
        if relation is not None:
            fq['relation_closure'] = relation
        if subject_taxon is not None:
            fq['subject_taxon_closure'] = subject_taxon
        if object_taxon is not None:
            fq['object_taxon_closure'] = object_taxon
        if self.id is not None:
            fq['id'] = self.id
        if self.evidence is not None:
            e = self.evidence
            if e.startswith("-"):
                fq['-evidence_object_closure'] = e.replace("-","")
            else:
                fq['evidence_object_closure'] = e

        if self.exclude_automatic_assertions:
            fq['-evidence_object_closure'] = 'ECO:0000501'

        # Homolog service params
        # TODO can we sync with argparse.choices?
        if self.homology_type is not None:
            if self.homology_type == 'O':
                fq['relation_closure'] = HomologyTypes.Ortholog.value
            elif self.homology_type == 'P':
                fq['relation_closure'] = HomologyTypes.Paralog.value
            elif self.homology_type == 'LDO':
                fq['relation_closure'] = \
            HomologyTypes.LeastDivergedOrtholog.value


        ## pivots
        facet_pivot_fields=self.facet_pivot_fields
        if self.pivot_subject_object:
            facet_pivot_fields = [M.SUBJECT, M.OBJECT]


        # Map solr field names for fq. The generic Monarch schema is
        # canonical, GO schema is mapped to this using
        # field_mapping dictionary
        if self.field_mapping is not None:
            for (k,v) in self.field_mapping.items():

                # map fq[k] -> fq[k]
                if k in fq:
                    if v is None:
                        del fq[k]
                    else:
                        fq[v] = fq[k]
                        del fq[k]

                # in solr, the fq field can be
                # a negated expression, e.g. -evidence_object_closure:"ECO:0000501"
                # ideally we would have a higher level representation rather than
                # relying on string munging...
                negk = '-' + k
                if negk in fq:
                    if v is None:
                        del fq[negk]
                    else:
                        negv = '-' + v
                        fq[negv] = fq[negk]
                        del fq[negk]


        filter_queries = []
        qstr = "*:*"
        if self.q is not None:
            qstr = self.q
        filter_queries = [ '{}:{}'.format(k,solr_quotify(v)) for (k,v) in fq.items()]

        # We want to match all associations that have either a subject or object
        # with an ID that is contained in subject_or_object_ids.
        if subject_or_object_ids is not None:
            quotified_ids = solr_quotify(subject_or_object_ids)
            subject_id_filter = '{}:{}'.format('subject_closure', quotified_ids)
            object_id_filter = '{}:{}'.format('object_closure', quotified_ids)

            # If subject_or_object_category is provided, we add it to the filter.
            if self.subject_or_object_category is not None:
                quotified_categories = solr_quotify(self.subject_or_object_category)
                subject_category_filter = '{}:{}'.format('subject_category', quotified_categories)
                object_category_filter = '{}:{}'.format('object_category', quotified_categories)

                filter_queries.append(
                    '(' + subject_id_filter + ' AND ' + object_category_filter + ')' \
                    ' OR '                                                      \
                    '(' + object_id_filter + ' AND ' + subject_category_filter + ')'
                )

            else:
                filter_queries.append(subject_id_filter + ' OR ' + object_id_filter)

        # unless caller specifies a field list, use default
        if select_fields is None:
            select_fields = [
                M.ID,
                M.IS_DEFINED_BY,
                M.SOURCE,
                M.SUBJECT,
                M.SUBJECT_LABEL,
                M.SUBJECT_TAXON,
                M.SUBJECT_TAXON_LABEL,
                M.RELATION,
                M.RELATION_LABEL,
                M.OBJECT,
                M.OBJECT_LABEL,
                M.OBJECT_TAXON,
                M.OBJECT_TAXON_LABEL
            ]
            if not self.unselect_evidence:
                select_fields += [
                    M.EVIDENCE_OBJECT,
                    M.EVIDENCE_GRAPH
                ]

        if not self._use_amigo_schema(object_category):
            select_fields.append(M.SUBJECT_CATEGORY)
            select_fields.append(M.OBJECT_CATEGORY)

        if self.map_identifiers is not None:
            select_fields.append(M.SUBJECT_CLOSURE)

        if self.slim is not None and len(self.slim)>0:
            select_fields.append(M.OBJECT_CLOSURE)

        if self.field_mapping is not None:
            logging.info("Applying field mapping to SELECT: {}".format(self.field_mapping))
            select_fields = [ map_field(fn, self.field_mapping) for fn in select_fields ]
            if facet_pivot_fields is not None:
                logging.info("Applying field mapping to PIV: {}".format(facet_pivot_fields))
                facet_pivot_fields = [ map_field(fn, self.field_mapping) for fn in facet_pivot_fields ]
                logging.info("APPLIED field mapping to PIV: {}".format(facet_pivot_fields))

        facet_fields = [ map_field(fn, self.field_mapping) for fn in facet_fields ]

        if self._use_amigo_schema(object_category):
            select_fields += [x for x in M.AMIGO_SPECIFIC_FIELDS if x not in select_fields]

        ## true if iterate in windows of max_size until all results found
        iterate=self.iterate

        #logging.info('FL'+str(select_fields))
        is_unlimited = False
        rows=self.rows
        if rows < 0:
            is_unlimited = True
            iterate = True
            rows = self.max_rows

        for field in self.non_null_fields:
            filter_queries.append(field + ":['' TO *]")

        params = {
            'q': qstr,
            'fq': filter_queries,
            'facet': facet_on,
            'facet.field': facet_fields,
            'facet.limit': facet_limit,
            'facet.mincount': self.facet_mincount,
            'fl': ",".join(select_fields),
            'rows': rows
        }

        if self.start is not None:
            params['start'] = self.start

        json_facet=self.json_facet
        if json_facet:
            params['json.facet'] = json.dumps(json_facet)

        facet_field_limits=self.facet_field_limits
        if facet_field_limits is not None:
            for (f,flim) in facet_field_limits.items():
                params["f."+f+".facet.limit"] = flim


        if len(facet_pivot_fields) > 0:
            params['facet.pivot'] = ",".join(facet_pivot_fields)
            params['facet.pivot.mincount'] = 1

        if self.stats_field:
            self.stats = True
            params['stats.field'] = self.stats_field
        params['stats'] = json.dumps(self.stats)

        return params
1365381
private Map<String, String> buildQueryParams(String queryFieldName, String queryFieldValue) {
        checkNotNullAndEmpty(queryFieldValue, queryFieldName);

        Map<String, String> queryParams = new TreeMap<>();
        buildConfigParams(queryParams);
        queryParams.put(WepayField.NONCE_STR, RandomStrs.generate(16));
        queryParams.put(queryFieldName, queryFieldValue);
        buildSignParams(queryParams);

        return queryParams;
    }
195473
def serialize_params(self, params, complex=False):
        
        if complex:
            # See climata.acis for an example implementation
            raise NotImplementedError("Cannot serialize %s!" % params)
        else:
            # Simpler queries can use traditional URL parameters
            return {
                self.get_url_param(key): ','.join(val)
                for key, val in params.items()
            }
416476
def add_query_params(url, params):
    
    def encode(s):
        return force_bytes(s, settings.DEFAULT_CHARSET)
    params = dict([(encode(k), encode(v)) for k, v in params.items() if v])

    parts = list(urlparse(url))
    query = dict(parse_qsl(parts[4]))
    query.update(params)
    parts[4] = urlencode(query)
    return urlunparse(parts)
381614
function proxyMethods(exec, query) {
    const methods = [].concat(END_POINT_METHODS).concat(CHAINABLE_METHODS);
    for (let name of methods) {
        const oldMethod = query[name];
        query[name] = function (...args) {
            const clonedQuery = query.clone();
            proxyMethods(exec, clonedQuery);
            oldMethod.apply(clonedQuery, args);
            if (CHAINABLE_METHODS.indexOf(name) > -1) {
                return clonedQuery;
            } else {
                return exec(clonedQuery.toString());
            }
        }
    }
}
432793
@Override
    public Map<String, Object> getQueryParameters() {
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("type", this.type.toString());
        return params;
    }
15443
def __make_http_query(self, params, topkey=''):
        
        if len(params) == 0:
            return ""
        result = ""
        # is a dictionary?
        if type(params) is dict:
            for key in params.keys():
                newkey = quote(key)
                if topkey != '':
                    newkey = topkey + quote('[' + key + ']')
                if type(params[key]) is dict:
                    result += self.__make_http_query(params[key], newkey)
                elif type(params[key]) is list:
                    i = 0
                    for val in params[key]:
                        if type(val) is dict:
                            result += self.__make_http_query(
                                val, newkey + quote('['+str(i)+']'))
                        else:
                            result += newkey + \
                                quote('['+str(i)+']') + "=" + \
                                quote(str(val)) + "&"
                        i = i + 1
                # boolean should have special treatment as well
                elif type(params[key]) is bool:
                    result += newkey + "=" + \
                        quote(str(params[key]).lower()) + "&"
                # assume string (integers and floats work well)
                else:
                    result += newkey + "=" + quote(str(params[key])) + "&"
        # remove the last '&'
        if (result) and (topkey == '') and (result[-1] == '&'):
            result = result[:-1]
        return result
934908
function collectQueryParams(req, paramNames) {
    var result = {
        query: {},
        fields: {},
        options: {},
        params: {}
    };
    paramNames.forEach(function (paramName) {
        var paramValue = req.anyParam(paramName);
        if (paramValue) {
            paramValue = paramValue.trim();
            if (paramValue && paramValue !== '*') {
                if (paramValue.charAt(paramValue.length - 1) === '*') {
                    // regexp to match prefix
                    paramValue = new RegExp('^' + paramValue.substring(0, paramValue.length - 1));
                }
                result.query[paramName] = paramValue;
            }
            result.params[paramName] = paramValue;
        }
    });
    var fields = req.anyParam('fields');
    if (fields) {
        result.fields = {};
        fields.split(',').forEach(function (field) {
            field = field.trim();
            if (field) {
                var select = 1;
                switch (field.charAt(0)) {
                    case '-':
                        field = field.substring(1);
                        select = 0;
                        break;
                    case '+':
                        field = field.substring(1);
                        break;
                }
                result.fields[field] = select;
            }
        });
    }
    var sort = req.anyParam('sort');
    if (sort) {
        result.options.sort = {};
        sort.split(',').forEach(function (field) {
            field = field.trim();
            if (field) {
                var order = 1;
                switch (field.charAt(0)) {
                    case '-':
                        field = field.substring(1);
                        order = -1;
                        break;
                    case '+':
                        field = field.substring(1);
                        break;
                }
                result.options.sort[field] = order;
            }
        });
        result.params.sort = sort;
    }
    var skip = req.anyParam('skip') || req.anyParam('offset');
    if (skip) {
        result.options.skip = parseInt(skip, 10);
        result.params.skip = skip;
    }
    var limit = req.anyParam('limit');
    if (limit) {
        result.options.limit = parseInt(limit, 10);
        result.params.limit = limit;
    }
    return result;
}
503348
function extractQueryParameters (query) {
  return Object.keys(query.values)
    .reduce((queryParameters, name) => {
      // arrays in routing definitions are not supported
      if (util.isArray(query.values[name])) {
        return queryParameters;
      }

      // escape regular expression characters
      var escaped = query.values[name].replace(EXPRESSION_ESCAPE_REG_EXP, '\\$&');

      // get all occurrences of routing parameters in URI path
      var regExpSource = '^' + escaped.replace(PARAMETER_REG_EXP, URI_QUERY_REPLACEMENT_REG_EXP_SOURCE) + '$';
      var queryParameterMatches = escaped.match(PARAMETER_REG_EXP);

      if (!queryParameterMatches ||
          queryParameterMatches.length === 0) {
        return;
      }

      var parameter = getParameterDescriptor(queryParameterMatches[queryParameterMatches.length - 1]);
      var expression = new RegExp(regExpSource, 'i');
      parameter.map = createUriQueryValueMapper(expression);
      queryParameters[name] = parameter;
      return queryParameters;
    }, Object.create(null));
}
777464
def get_query_param(request, key):
    """"""
    value = request.query_params.get(key) or request.data.get(key)
    if value is None:
        raise KeyError()
    return value
24110
function toQueryParams(object){
	return Object.keys(object)
		.filter(key => !!object[key])
		.map(key => key + "=" + encodeURIComponent(object[key]))
		.join("&")
}
1256856
def build_q(fields_dict, params_dict, request=None):
    
    # Building search query
    # queries generated by different search_fields are ANDed
    # if a search field is defined for more than one field, are put together with OR
    and_query = Q()

    for fieldname in fields_dict:
        search_field = fields_dict[fieldname]
        if fieldname in params_dict and params_dict[fieldname] != '' and params_dict[fieldname] != []:
            or_query = None

            if type(search_field) == type(list()):
                field_list = search_field
                search_operator = "__icontains"
                fixed_filters = None
                multiple_values = False
                custom_query_method = None
                value_mapper = None

            else: # dictionary of field definitions
                if search_field.get('ignore', False):
                    continue

                field_list = search_field['fields']
                search_operator = search_field.get('operator', None)
                fixed_filters = search_field.get('fixed_filters', None)
                multiple_values = search_field.get('multiple', False)
                custom_query_method =  search_field.get('custom_query', None)
                value_mapper =  search_field.get('value_mapper', None)

            for model_field in field_list:

                if multiple_values:
                    if hasattr(params_dict, "getlist"):
                        request_field_value = params_dict.getlist(fieldname)
                    elif type(params_dict[fieldname]) == list:
                        request_field_value = params_dict[fieldname]
                    else:
                        request_field_value = [params_dict[fieldname]]
                    if value_mapper:
                        request_field_value = [value_mapper(value) for value in request_field_value]
                else:
                    request_field_value = params_dict[fieldname] if not value_mapper else value_mapper(params_dict[fieldname])

                if not custom_query_method:
                    fieldname_key = model_field + search_operator
                    filter_dict = { fieldname_key : request_field_value}
                    if not or_query:
                        or_query = Q(**filter_dict)
                    else:
                        or_query = or_query | Q(**filter_dict)
                else:
                    #TODO: this is a hack for using request data in custom_query
                    #it would be better to pass ALSO the request to custom_query_method
                    if not request:
                        cf = custom_query_method(model_field, request_field_value, params_dict)
                    else:
                        cf = custom_query_method(model_field, request_field_value, request)

                    if not or_query:
                        or_query = cf
                    else:
                        or_query = or_query | cf

            #fixed_filters
            fixed_filters_q = Q()
            #fixed_filters must return a Q object or None
            if fixed_filters:
                if callable(fixed_filters):
                    fixed_filters_q = fixed_filters(params_dict)
                elif type(fixed_filters) is dict:
                    fixed_filters_q = Q(**fixed_filters)

            and_query = and_query & or_query
            and_query = and_query & fixed_filters_q


    return and_query
975891
def prepare_query_params(**kwargs):
    
    return [
        (sub_key, sub_value)
        for key, value in kwargs.items()
        for sub_key, sub_value in expand(value, key)
        if sub_value is not None
    ]
258978
protected SqlQuerySpec generateQuery(@NonNull DocumentQuery query, @NonNull String queryHead) {
        Assert.hasText(queryHead, "query head should have text.");

        final Pair<String, List<Pair<String, Object>>> queryBody = generateQueryBody(query);
        final String queryString = String.join(" ", queryHead, queryBody.getValue0(), generateQueryTail(query));
        final List<Pair<String, Object>> parameters = queryBody.getValue1();
        final SqlParameterCollection sqlParameters = new SqlParameterCollection();

        sqlParameters.addAll(
                parameters.stream()
                        .map(p -> new SqlParameter("@" + p.getValue0(), toDocumentDBValue(p.getValue1())))
                        .collect(Collectors.toList())
        );

        return new SqlQuerySpec(queryString, sqlParameters);
    }
300259
@SuppressWarnings("unused")
    final void handleQueryParameters(ByteBuffer buffer, ParseState state, HttpServerExchange exchange) throws BadRequestException {
        StringBuilder stringBuilder = state.stringBuilder;
        int queryParamPos = state.pos;
        int mapCount = state.mapCount;
        boolean urlDecodeRequired = state.urlDecodeRequired;
        String nextQueryParam = state.nextQueryParam;

        //so this is a bit funky, because it not only deals with parsing, but
        //also deals with URL decoding the query parameters as well, while also
        //maintaining a non-decoded version to use as the query string
        //In most cases these string will be the same, and as we do not want to
        //build up two separate strings we don't use encodedStringBuilder unless
        //we encounter an encoded character

        while (buffer.hasRemaining()) {
            char next = (char) (buffer.get() & 0xFF);
            if(!allowUnescapedCharactersInUrl && !ALLOWED_TARGET_CHARACTER[next]) {
                throw new BadRequestException(UndertowMessages.MESSAGES.invalidCharacterInRequestTarget(next));
            }
            if (next == ' ' || next == '\t') {
                final String queryString = stringBuilder.toString();
                exchange.setQueryString(queryString);
                if (nextQueryParam == null) {
                    if (queryParamPos != stringBuilder.length()) {
                        exchange.addQueryParam(decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true, true), "");
                    }
                } else {
                    exchange.addQueryParam(nextQueryParam, decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true, true));
                }
                state.state = ParseState.VERSION;
                state.stringBuilder.setLength(0);
                state.pos = 0;
                state.nextQueryParam = null;
                state.urlDecodeRequired = false;
                state.mapCount = 0;
                return;
            } else if (next == '\r' || next == '\n') {
                throw UndertowMessages.MESSAGES.failedToParsePath();
            } else {
                if (decode && (next == '+' || next == '%' || next > 127)) { //+ is only a whitespace substitute in the query part of the URL
                    urlDecodeRequired = true;
                } else if (next == '=' && nextQueryParam == null) {
                    nextQueryParam = decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true, true);
                    urlDecodeRequired = false;
                    queryParamPos = stringBuilder.length() + 1;
                } else if (next == '&' && nextQueryParam == null) {
                    if (++mapCount >= maxParameters) {
                        throw UndertowMessages.MESSAGES.tooManyQueryParameters(maxParameters);
                    }
                    if (queryParamPos != stringBuilder.length()) {
                        exchange.addQueryParam(decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true, true), "");
                    }
                    urlDecodeRequired = false;
                    queryParamPos = stringBuilder.length() + 1;
                } else if (next == '&') {
                    if (++mapCount >= maxParameters) {
                        throw UndertowMessages.MESSAGES.tooManyQueryParameters(maxParameters);
                    }
                    exchange.addQueryParam(nextQueryParam, decode(stringBuilder.substring(queryParamPos), urlDecodeRequired, state, true, true));
                    urlDecodeRequired = false;
                    queryParamPos = stringBuilder.length() + 1;
                    nextQueryParam = null;
                }
                stringBuilder.append(next);

            }

        }
        state.pos = queryParamPos;
        state.nextQueryParam = nextQueryParam;
        state.urlDecodeRequired = urlDecodeRequired;
        state.mapCount = mapCount;
    }
379276
def execute(cls, uri, http_verb, extra_headers=None, batch=False, _body=None, **kw):
        
        if batch:
            urlsplitter = urlparse(API_ROOT).netloc
            ret = {"method": http_verb, "path": uri.split(urlsplitter, 1)[1]}
            if kw:
                ret["body"] = kw
            return ret

        if not ('app_id' in ACCESS_KEYS and 'rest_key' in ACCESS_KEYS):
            raise core.ParseError('Missing connection credentials')

        app_id = ACCESS_KEYS.get('app_id')
        rest_key = ACCESS_KEYS.get('rest_key')
        master_key = ACCESS_KEYS.get('master_key')

        url = uri if uri.startswith(API_ROOT) else cls.ENDPOINT_ROOT + uri
        if _body is None:
            data = kw and json.dumps(kw, default=date_handler) or "{}"
        else:
            data = _body
        if http_verb == 'GET' and data:
            url += '?%s' % urlencode(kw)
            data = None
        else:
            if cls.__name__ == 'File':
                data = data
            else:
                data = data.encode('utf-8')

        headers = {
            'Content-type': 'application/json',
            'X-Parse-Application-Id': app_id,
            'X-Parse-REST-API-Key': rest_key
        }
        headers.update(extra_headers or {})

        if cls.__name__ == 'File':
            request = Request(url.encode('utf-8'), data, headers)
        else:
            request = Request(url, data, headers)

        if ACCESS_KEYS.get('session_token'):
            request.add_header('X-Parse-Session-Token', ACCESS_KEYS.get('session_token'))
        elif master_key:
            request.add_header('X-Parse-Master-Key', master_key)

        request.get_method = lambda: http_verb

        try:
            response = urlopen(request, timeout=CONNECTION_TIMEOUT)
        except HTTPError as e:
            exc = {
                400: core.ResourceRequestBadRequest,
                401: core.ResourceRequestLoginRequired,
                403: core.ResourceRequestForbidden,
                404: core.ResourceRequestNotFound
                }.get(e.code, core.ParseError)
            raise exc(e.read())

        return json.loads(response.read().decode('utf-8'))
1350054
def generate_request_access_signature(parameters, secret_key):
    
    # pull out the parameter keys
    keys = parameters.keys()

    # alphanumerically sort the keys in place
    keys.sort()

    # create an array of url encoded key:value pairs
    encoded_pairs = [urlencode({key: parameters[key]}) for key in keys]

    # create the serialized parameters in a single, URL style string
    serialized_parameters = '&'.join(encoded_pairs)

    # create the string with the secret key and the parameters which will be hashed
    string_to_hash = '%s:%s' % (secret_key, serialized_parameters)

    # return the hex digest of the hashed string
    return sha256(string_to_hash).hexdigest()