Prepares a MIME object by applying the headers
        to the *mime* object. Ignores any Bcc or
        Resent-Bcc headers.
433781
def prepare(self, mime):
        
        for key in self:
            if key == 'Bcc' or key == 'Resent-Bcc':
                continue
            del mime[key]
            # Python 3.* email's compatibility layer will handle
            # unicode field values in proper way but Python 2
            # won't (it will encode not only additional field
            # values but also all header values)
            parsed_header, additional_fields = parse_header(
                self[key] if IS_PY3 else
                self[key].encode("utf-8")
            )
            mime.add_header(key, parsed_header, **additional_fields)
966494
protected function prepare()
    {
        $this->initPurifier($this->config->getPurifierCacheLocation());

        $this->oldText = $this->purifyHtml($this->oldText);
        $this->newText = $this->purifyHtml($this->newText);
    }
204659
function setContentType($mime_type, $charset='utf-8') {
		
		$header = 'Content-Type: ' . $mime_type;
		if ($charset) {
			$header .= '; charset='.$charset;
		}
		
		$this->headers[] = array($header, TRUE);
		
		return $this;
	}
1139817
def with_headers(self, headers=None, **params):
                
        if isinstance(headers, (tuple, list)):
            headers = dict(headers)

        if params:
            if isinstance(headers, dict):
                headers.update(params)
            elif headers is None:
                headers = params

        self._headers.update(headers)
        return self
862137
def request(self, method, uri, **kw):
        
        expect = kw.pop("expect", [])
        mime_body = kw.pop("mime_body", None)

        headers = kw.pop("headers", {})
        data = kw.pop("data", None)

        if mime_body:
            mimevalues = self.mimeobjects.get(mime_body.__class__)

            if not mimevalues:
                raise ClientException(
                    ("Cannot handle object of type "
                     "{0!r}").format(mime_body.__class__))

            mapping = mimevalues[0]

            document_type, mimetype, validator = mapping

            data = document_type.render(validator, mime_body)
            headers["Content-Type"] = mimetype

        if uri[0] != '/':
            uri = '/' + uri

        url = "{self.scheme}://{self.host}{uri}".format(self=self, uri=uri)

        response = self.session.request(
            method, url,
            headers=headers,
            data=data,
            **kw)

        content_type = response.headers.get("Content-Type")

        if content_type is None or not response.content:
            return response, None

        mimetype, opts = werkzeug.http.parse_options_header(content_type)

        if mimetype not in self.mimetypes:
            raise ClientException(
                "Cannot handle response type: {0}".format(mimetype))

        document_type, document_class, validator = self.mimetypes.get(mimetype)

        if expect and document_class not in expect:
            raise ClientException(
                "Unexpected response type: {0}".format(mimetype))

        try:
            obj = document_type.parse(validator,
                                      document_class,
                                      response.content)
        except MimeValidationError as e:
            raise ClientException(
                "Response format invalid: {0}".format(str(e)))
        except:
            log.error(
                "Failed to parse content of type: {0}".format(mimetype),
                exc_info=sys.exc_info())
            raise ClientException(
                "Failed to parse content of type: {0}".format(mimetype))

        return response, obj
976552
public function setDefaultHeader()
    {
        $this->headers[] = "Mime-Version: 1.0";
        $this->headers[] = "Date: " . date("r");
        $this->headers[] = "X-Mailer: PHP/".phpversion();

        if ($this->subject) {
            $this->headers[] = "Subject: " . $this->subject;
        }
    }
132170
def set_deserializer_by_mime_type(self, mime_type):
        

        for deserializer in self._deserializers:
            if deserializer.content_type() == mime_type:
                self._selected_deserializer = deserializer
                return

        raise exception.UnsupportedContentTypeError(mime_type, self.supported_mime_types_str)
904835
def mime(self):
        '''
        
        '''
        return self.metadata['ContentType'] if 'ContentType' in self.metadata else BaseEngine.get_mimetype(self.buffer)
432072
def python_mime(fn):
    
    @wraps(fn)
    def python_mime_decorator(*args, **kwargs):
        response.content_type = "text/x-python"

        return fn(*args, **kwargs)

    return python_mime_decorator
374011
def prepare_message(user, useralias, addresses, subject, contents, attachments, headers, encoding, newline_to_break=True):
    # check if closed!!!!!! XXX
    
    if isinstance(contents, text_type):
        contents = [contents]
    if isinstance(attachments, text_type):
        attachments = [attachments]

    # merge contents and attachments for now.
    if attachments is not None:
        for a in attachments:
            if not os.path.isfile(a):
                raise TypeError("'{0}' is not a valid filepath".format(a))
        contents = attachments if contents is None else contents + attachments

    has_included_images, content_objects = prepare_contents(contents, encoding)
    msg = MIMEMultipart()
    if headers is not None:
        # Strangely, msg does not have an update method, so then manually.
        for k, v in headers.items():
            msg[k] = v
    if headers is None or "Date" not in headers:
        msg["Date"] = formatdate()

    msg_alternative = MIMEMultipart("alternative")
    msg_related = MIMEMultipart("related")
    msg_related.attach("-- HTML goes here --")
    msg.attach(msg_alternative)
    add_subject(msg, subject)
    add_recipients_headers(user, useralias, msg, addresses)
    htmlstr = ""
    altstr = []
    if has_included_images:
        msg.preamble = "This message is best displayed using a MIME capable email reader."

    if contents is not None:
        for content_object, content_string in zip(content_objects, contents):
            if content_object["main_type"] == "image":
                # all image objects need base64 encoding, so do it now
                email.encoders.encode_base64(content_object["mime_object"])
                # aliased image {'path' : 'alias'}
                if isinstance(content_string, dict) and len(content_string) == 1:
                    for key in content_string:
                        hashed_ref = str(abs(hash(key)))
                        alias = content_string[key]
                    # pylint: disable=undefined-loop-variable
                    content_string = key
                else:
                    alias = os.path.basename(str(content_string))
                    hashed_ref = str(abs(hash(alias)))

                # TODO: I should probably remove inline now that there is "attachments"
                # if string is `inline`, inline, else, attach
                # pylint: disable=unidiomatic-typecheck
                if type(content_string) == inline:
                    htmlstr += '<img src="cid:{0}" title="{1}"/>'.format(hashed_ref, alias)
                    content_object["mime_object"].add_header(
                        "Content-ID", "<{0}>".format(hashed_ref)
                    )
                    altstr.append("-- img {0} should be here -- ".format(alias))
                    # inline images should be in related MIME block
                    msg_related.attach(content_object["mime_object"])
                else:
                    # non-inline images get attached like any other attachment
                    msg.attach(content_object["mime_object"])

            else:
                if content_object["encoding"] == "base64":
                    email.encoders.encode_base64(content_object["mime_object"])
                    msg.attach(content_object["mime_object"])
                elif content_object["sub_type"] not in ["html", "plain"]:
                    msg.attach(content_object["mime_object"])
                else:
                    if newline_to_break:
                        content_string = content_string.replace("\n", "<br>")
                    try:
                        htmlstr += "<div>{0}</div>".format(content_string)
                    except UnicodeEncodeError:
                        htmlstr += u"<div>{0}</div>".format(content_string)
                    altstr.append(content_string)

    msg_related.get_payload()[0] = MIMEText(htmlstr, "html", _charset=encoding)
    msg_alternative.attach(MIMEText("\n".join(altstr), _charset=encoding))
    msg_alternative.attach(msg_related)
    return msg
841695
def _generate_base_mimetypes(self):
        
        for t in self.type_instances:
            if t.custom_mime:
                continue

            yield t.mime, (t, None, None)
1306181
def prepare(self, scheme='http', handle_files=True, encoding='utf-8'):
        

        if isinstance(scheme, list):
            if self.__scheme is None:
                scheme = scheme.pop()
            else:
                if self.__scheme in scheme:
                    scheme = self.__scheme
                else:
                    raise Exception('preferred scheme:{} is not supported by the client or spec:{}'.format(self.__scheme, scheme))
        elif not isinstance(scheme, six.string_types):
            raise ValueError('"scheme" should be a list or string')

        # combine path parameters into path
        # TODO: 'dot' is allowed in swagger, but it won't work in python-format
        path_params = {}
        for k, v in six.iteritems(self.__p['path']):
            path_params[k] = six.moves.urllib.parse.quote_plus(v)

        self.__path = self.__path.format(**path_params)

        # combine path parameters into url
        self.__url = ''.join([scheme, ':', self.__url.format(**path_params)])

        # header parameters
        self.__header.update(self.__p['header'])

        # update data parameter
        content_type = None
        if self.__p['file']:
            if handle_files:
                content_type, self.__data = self._prepare_files(encoding)
            else:
                # client that can encode multipart/form-data, should
                # access form-data via data property and file from file
                # property.

                # only form data can be carried along with files,
                self.__data = self.__p['formData']

        elif self.__p['formData']:
            content_type, self.__data = self._prepare_forms()
        elif self.__p['body']:
            content_type, self.__data = self._prepare_body()
        else:
            self.__data = None

        if content_type:
            self.__header.update({'Content-Type': content_type})

        accept = self.__produce
        if not accept and self.__op.produces:
            accept = self.__op.produces[0]
        if accept:
            if self.__op.produces and accept not in self.__op.produces:
                raise errs.SchemaError('accept {0} does not present in {1}'.format(accept, self.__op.produces))
            self.__header.update({'Accept': accept})

        return self
883543
def prepare_zoho_headers(token, headers=None):
        
        headers = headers or {}
        headers["Authorization"] = "{token_header} {token}".format(
            token_header=ZOHO_TOKEN_HEADER, token=token
        )
        return headers
743763
def prepare(self):
        
        # Maybe the Brok is a old daemon one or was already prepared
        # if so, the data is already ok
        if hasattr(self, 'prepared') and not self.prepared:
            self.data = unserialize(self.data)
            if self.instance_id:
                self.data['instance_id'] = self.instance_id
        self.prepared = True
951811
def prepare_content_length(self, body):
        """"""
        if body is not None:
            length = super_len(body)
            if length:
                # If length exists, set it. Otherwise, we fallback
                # to Transfer-Encoding: chunked.
                self.headers['Content-Length'] = builtin_str(length)
        elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None:
            # Set Content-Length to 0 for methods that can have a body
            # but don't provide one. (i.e. not GET or HEAD)
            self.headers['Content-Length'] = '0'
75287
protected function _headers($options, $mime, $charset, $encoding, $length)
    {
        $headers = !empty($options['headers']) ? $options['headers'] : [];

        if (!empty($options['disposition'])) {
            $parts = [$options['disposition']];
            foreach (['name', 'filename'] as $name) {
                if (!empty($options[$name])) {
                    $value = htmlspecialchars_decode(htmlspecialchars($options[$name], ENT_NOQUOTES | ENT_IGNORE, 'UTF-8'), ENT_NOQUOTES);
                    $value = preg_replace('~[\s/\\\]~', '', $value);
                    $value = addcslashes($value, '"');
                    $parts[] = "{$name}=\"{$value}\"";
                }
            }
            $headers[] = "Content-Disposition: " . join('; ', $parts);
        }

        if (!empty($options['id'])) {
            $headers[] = 'Content-ID: ' . $options['id'];
        }

        if (!empty($mime)) {
            $charset = $charset ? '; charset=' . $charset : '';
            $headers[] = 'Content-Type: ' . $mime . $charset;
        }

        if (!empty($encoding)) {
            $headers[] = 'Content-Transfer-Encoding: ' . $encoding;
        }

        if (!empty($options['length'])) {
            $headers[] = 'Content-Length: ' . $length;
        }

        if (!empty($options['description'])) {
            $headers[] = 'Content-Description: ' . $options['description'];
        }

        if (!empty($options['location'])) {
            $headers[] = 'Content-Location: ' . $options['location'];
        }

        if (!empty($options['language'])) {
            $headers[] = 'Content-Language: ' . $options['language'];
        }
        return $headers;
    }
240585
def prepare_post_parameters(self, post_params=None, files=None):
        
        params = post_params or []
        for key, values in (files or {}).items():
            for maybe_file_or_path in values if isinstance(values, list) else [values]:
                try:
                    # use the parameter as if it was an open file object
                    data = maybe_file_or_path.read()
                    maybe_file_or_path = maybe_file_or_path.name
                except AttributeError:
                    # then it is presumably a file path
                    with open(maybe_file_or_path, 'rb') as fh:
                        data = fh.read()
                basepath = os.path.basename(maybe_file_or_path)
                mimetype = mimetypes.guess_type(basepath)[0] or 'application/octet-stream'
                params.append((key, (basepath, data, mimetype)))
        return params