Render SetCookies into a Response.
491322
public function renderIntoSetCookieHeader(ResponseInterface $response) : ResponseInterface
    {
        $response = $response->withoutHeader(static::SET_COOKIE_HEADER);
        foreach ($this->setCookies as $setCookie) {
            $response = $response->withAddedHeader(static::SET_COOKIE_HEADER, (string) $setCookie);
        }

        return $response;
    }
160217
def _embed(self, request, response):
        """"""
        if self._match(request, response):
            # Render the <link> and the <script> tags to include Chosen.
            head = render_to_string(
                "chosenadmin/_head_css.html",
                {"chosen_css": self._chosen_css()}
            )
            body = render_to_string(
                "chosenadmin/_script.html",
                {"chosen_js": self._chosen_js()}
            )

            # Re-write the Response's content to include our new html
            content = response.rendered_content
            content = content.replace('</head>', head)
            content = content.replace('</body>', body)
            response.content = content
        return response
83211
def save_config_value(request, response, key, value):
    """"""
    request.session[key] = value
    response.set_cookie(key, value, expires=one_year_from_now())
    return response
34931
def build_response(
        self, request, response, from_cache=False, cacheable_methods=None
    ):
        
        cacheable = cacheable_methods or self.cacheable_methods
        if not from_cache and request.method in cacheable:
            # Check for any heuristics that might update headers
            # before trying to cache.
            if self.heuristic:
                response = self.heuristic.apply(response)

            # apply any expiration heuristics
            if response.status == 304:
                # We must have sent an ETag request. This could mean
                # that we've been expired already or that we simply
                # have an etag. In either case, we want to try and
                # update the cache if that is the case.
                cached_response = self.controller.update_cached_response(
                    request, response
                )

                if cached_response is not response:
                    from_cache = True

                # We are done with the server response, read a
                # possible response body (compliant servers will
                # not return one, but we cannot be 100% sure) and
                # release the connection back to the pool.
                response.read(decode_content=False)
                response.release_conn()

                response = cached_response

            # We always cache the 301 responses
            elif response.status == 301:
                self.controller.cache_response(request, response)
            else:
                # Wrap the response file with a wrapper that will cache the
                #   response when the stream has been consumed.
                response._fp = CallbackFileWrapper(
                    response._fp,
                    functools.partial(
                        self.controller.cache_response, request, response
                    ),
                )
                if response.chunked:
                    super_update_chunk_length = response._update_chunk_length

                    def _update_chunk_length(self):
                        super_update_chunk_length()
                        if self.chunk_left == 0:
                            self._fp._close()

                    response._update_chunk_length = types.MethodType(
                        _update_chunk_length, response
                    )

        resp = super(CacheControlAdapter, self).build_response(request, response)

        # See if we should invalidate the cache.
        if request.method in self.invalidating_methods and resp.ok:
            cache_url = self.controller.cache_url(request.url)
            self.cache.delete(cache_url)

        # Give the request a from_cache attr to let people use it
        resp.from_cache = from_cache

        return resp
877349
function parseCookies(req, res, next) {
		var self = this;
		var cookieHeader = req.headers.cookie;

		if (cookieHeader) {
			req.cookies = cookie.parse(cookieHeader);
		} else {
			req.cookies = {};
		}

		/**
		 * Add a cookie to our response.  Uses a Set-Cookie header
		 * per cookie added.
		 * 
		 * @param {String} key  - Cookie name
		 * @param {String} val  - Cookie value
		 * @param {[type]} opts - Options object can contain path, secure, 
		 *     expires, domain, http
		 */
		res.setCookie = function setCookie(key, val, opts) {
			var HEADER = "Set-Cookie";

			if (res.header(HEADER)) {
				var curCookies = res.header(HEADER);

				if (!(curCookies instanceof Array)) {
					curCookies = [curCookies];
				}

				curCookies.push(cookie.serialize(key, val, opts));

				res.setHeader(HEADER, curCookies);

			} else {

				res.setHeader(HEADER, cookie.serialize(key, val, opts));

			}
		};

		res.clearCookie = function clearCookie (key, opts) {
			var options = merge({
				expires: new Date(1)
			}, opts);

			res.setCookie(key, '', options)
		}

		next();

	}
799530
def from_response(cls, header_data, ignore_bad_cookies=False,
                      ignore_bad_attributes=True):
        ""
        cookies = cls()
        cookies.parse_response(
            header_data,
            ignore_bad_cookies=ignore_bad_cookies,
            ignore_bad_attributes=ignore_bad_attributes)
        return cookies
1045258
function cookie(req, res, next){
  // cookie getter
  req.cookies = Cookie.parse(req.headers['cookie']);
  /**
   * [function cookie setter]
   * @param  {[type]} key   [description]
   * @param  {[type]} value [description]
   * @param  {[type]} attrs [description]
   * @return {[type]}       [description]
   */
  res.cookie = function(key, value, attrs = {}){
    if(value === null) { attrs.expires = new Date(0); value = ''; }
    res.setHeader('Set-Cookie', Cookie(key, value, attrs).toHeader());
  };
  next();
}
376113
private void saveResponseCookies() throws IOException {
    CookieHandler cookieHandler = CookieHandler.getDefault();
    if (cookieHandler != null) {
      try {
        URI uri = getURL().toURI();
        cookieHandler.put(uri, getHeaderFieldsDoNotForceResponse());
      } catch (URISyntaxException e) {
        throw new IOException(e);
      }
    }
  }
1220661
def make_cookies(self, response, request):
        """"""
        # get cookie-attributes for RFC 2965 and Netscape protocols
        headers = response.info()
        rfc2965_hdrs = headers.get_all("Set-Cookie2", [])
        ns_hdrs = headers.get_all("Set-Cookie", [])

        rfc2965 = self._policy.rfc2965
        netscape = self._policy.netscape

        if ((not rfc2965_hdrs and not ns_hdrs) or
            (not ns_hdrs and not rfc2965) or
            (not rfc2965_hdrs and not netscape) or
            (not netscape and not rfc2965)):
            return []  # no relevant cookie headers: quick exit

        try:
            cookies = self._cookies_from_attrs_set(
                split_header_words(rfc2965_hdrs), request)
        except Exception:
            _warn_unhandled_exception()
            cookies = []

        if ns_hdrs and netscape:
            try:
                # RFC 2109 and Netscape cookies
                ns_cookies = self._cookies_from_attrs_set(
                    parse_ns_headers(ns_hdrs), request)
            except Exception:
                _warn_unhandled_exception()
                ns_cookies = []
            self._process_rfc2109_cookies(ns_cookies)

            # Look for Netscape cookies (from Set-Cookie headers) that match
            # corresponding RFC 2965 cookies (from Set-Cookie2 headers).
            # For each match, keep the RFC 2965 cookie and ignore the Netscape
            # cookie (RFC 2965 section 9.1).  Actually, RFC 2109 cookies are
            # bundled in with the Netscape cookies for this purpose, which is
            # reasonable behaviour.
            if rfc2965:
                lookup = {}
                for cookie in cookies:
                    lookup[(cookie.domain, cookie.path, cookie.name)] = None

                def no_matching_rfc2965(ns_cookie, lookup=lookup):
                    key = ns_cookie.domain, ns_cookie.path, ns_cookie.name
                    return key not in lookup
                ns_cookies = filter(no_matching_rfc2965, ns_cookies)

            if ns_cookies:
                cookies.extend(ns_cookies)

        return cookies
699057
def make_response(self, status, content_type, response):
        """"""
        headers = [('Access-Control-Allow-Origin', '*'),
                   ('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'),
                   ('Access-Control-Allow-Headers', 'Content-Type'),
                   ('Access-Control-Max-Age', '86400'),
                   ('Content-type', content_type)
                  ]
        self.start_response(status, headers)
        return [response.encode()]
440757
def sanitize_http_response_cookies(client, event):
    
    try:
        cookie_string = event["context"]["response"]["headers"]["set-cookie"]
        event["context"]["response"]["headers"]["set-cookie"] = _sanitize_string(cookie_string, ";", "=")
    except (KeyError, TypeError):
        pass
    return event
632524
def make_response(self, content, code=200, headers=None):
        """"""
        if headers:
            for header in headers:
                self.headers[header] = headers[header]
        return make_response(content, code, self.headers)
466021
def _after_request(self, response):
        
        # This means that if either the new or the old are False, we set
        # insecure cookies.
        # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we
        # don't want people to find it easily.
        cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and
                         current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE',
                                                True))

        if getattr(g, 'oidc_id_token_dirty', False):
            if g.oidc_id_token:
                signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token)
                response.set_cookie(
                    current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'],
                    signed_id_token,
                    secure=cookie_secure,
                    httponly=True,
                    max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL'])
            else:
                # This was a log out
                response.set_cookie(
                    current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'],
                    '',
                    path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'],
                    secure=cookie_secure,
                    httponly=True,
                    expires=0)
        return response
981641
private static Response join(final Response response) throws IOException {
        final StringBuilder cookies = new StringBuilder();
        for (final String header : response.head()) {
            final Matcher matcher =
                TkJoinedCookies.PTN.matcher(header);
            if (!matcher.matches()) {
                continue;
            }
            cookies.append(matcher.group(1)).append(", ");
        }
        final Response out;
        if (cookies.length() > 0) {
            out = new RsWithHeader(
                new RsWithoutHeader(response, "Set-cookie"),
                "Set-Cookie", cookies.toString()
            );
        } else {
            out = response;
        }
        return out;
    }
1161367
def render_to_response(self, context=False):
        """"""
        f = self.openfile()
        wrapper = FileWrapper(f)
        response = HttpResponse(wrapper, content_type=self.content_type())
        self.headers(response)
        return response
1091598
def _build_response(self, resp, is_error=False):
        


        def build(resp):

            response = Response()

            # Pass settings over.
            response.config = self.config

            if resp:

                # Fallback to None if there's no staus_code, for whatever reason.
                response.status_code = getattr(resp, 'status', None)

                # Make headers case-insensitive.
                response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))

                # Start off with our local cookies.
                cookies = self.cookies or dict()

                # Add new cookies from the server.
                if 'set-cookie' in response.headers:
                    cookie_header = response.headers['set-cookie']

                    c = SimpleCookie()
                    c.load(cookie_header)

                    for k,v in c.items():
                        cookies.update({k: v.value})

                # Save cookies in Response.
                response.cookies = cookies

            # Save original resopnse for later.
            response.raw = resp

            if is_error:
                response.error = resp

            response.url = self.full_url

            return response


        history = []

        r = build(resp)
        cookies = self.cookies
        self.cookies.update(r.cookies)

        if r.status_code in REDIRECT_STATI and not self.redirect:

            while (
                ('location' in r.headers) and
                ((r.status_code is codes.see_other) or (self.allow_redirects))
            ):

                if not len(history) < self.config.get('max_redirects'):
                    raise TooManyRedirects()

                history.append(r)

                url = r.headers['location']

                # Handle redirection without scheme (see: RFC 1808 Section 4)
                if url.startswith('//'):
                    parsed_rurl = urlparse(r.url)
                    url = '%s:%s' % (parsed_rurl.scheme, url)

                # Facilitate non-RFC2616-compliant 'location' headers
                # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
                if not urlparse(url).netloc:
                    url = urljoin(r.url, urllib.quote(urllib.unquote(url)))

                # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4
                if r.status_code is codes.see_other:
                    method = 'GET'
                else:
                    method = self.method

                # Remove the cookie headers that were sent.
                headers = self.headers
                try:
                    del headers['Cookie']
                except KeyError:
                    pass

                request = Request(
                    url=url,
                    headers=headers,
                    files=self.files,
                    method=method,
                    params=self.session.params,
                    auth=self._auth,
                    cookies=cookies,
                    redirect=True,
                    config=self.config,
                    timeout=self.timeout,
                    _poolmanager=self._poolmanager,
                    proxies = self.proxies,
                )

                request.send()
                cookies.update(request.response.cookies)
                r = request.response
                self.cookies.update(r.cookies)

            r.history = history

        self.response = r
        self.response.request = self
        self.response.cookies.update(self.cookies)
245792
def build_final_response(request, meta, result, menu, hproject, proxyMode, context):
    """"""

    if 'no_template' in meta and meta['no_template']:  # Just send the json back
        return HttpResponse(result)

    # TODO this breaks pages not using new template
    # Add sidebar toggler if plugit did not add by itself
    # if not "sidebar-toggler" in result:
    #     result = "<div class=\"menubar\"><div class=\"sidebar-toggler visible-xs\"><i class=\"ion-navicon\"></i></div></div>" + result

    # render the template into the whole page
    if not settings.PIAPI_STANDALONE:
        return render_to_response('plugIt/' + hproject.get_plugItTemplate_display(),
                                  {"project": hproject,
                                   "plugit_content": result,
                                   "plugit_menu": menu,
                                   'context': context},
                                  context_instance=RequestContext(request))

    if proxyMode:  # Force inclusion inside template
        return render_to_response('plugIt/base.html',
                                  {'plugit_content': result,
                                   "plugit_menu": menu,
                                   'context': context},
                                  context_instance=RequestContext(request))

    renderPlugItTemplate = 'plugItBase.html'
    if settings.PIAPI_PLUGITTEMPLATE:
        renderPlugItTemplate = settings.PIAPI_PLUGITTEMPLATE

    return render_to_response('plugIt/' + renderPlugItTemplate,
                              {"plugit_content": result,
                               "plugit_menu": menu,
                               'context': context},
                              context_instance=RequestContext(request))