当前位置: 首页>>代码示例>>Python>>正文


Python multipartparser.MultiPartParser类代码示例

本文整理汇总了Python中django.http.multipartparser.MultiPartParser的典型用法代码示例。如果您正苦于以下问题:Python MultiPartParser类的具体用法?Python MultiPartParser怎么用?Python MultiPartParser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了MultiPartParser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: parse_headers_and_body_with_django

def parse_headers_and_body_with_django(headers, body):
    """Parse `headers` and `body` with Django's :class:`MultiPartParser`.

    `MultiPartParser` is a curiously ugly and RFC non-compliant concoction.

    Amongst other things, it coerces all field names, field data, and
    filenames into Unicode strings using the "replace" error strategy, so be
    warned that your data may be silently mangled.

    It also, in 1.3.1 at least, does not recognise any transfer encodings at
    *all* because its header parsing code was broken.

    I'm also fairly sure that it'll fall over on headers than span more than
    one line.

    In short, it's a piece of code that inspires little confidence, yet we
    must work with it, hence we need to round-trip test multipart handling
    with it.
    """
    handler = MemoryFileUploadHandler()
    meta = {
        "HTTP_CONTENT_TYPE": headers["Content-Type"],
        "HTTP_CONTENT_LENGTH": headers["Content-Length"],
        }
    parser = MultiPartParser(
        META=meta, input_data=BytesIO(body),
        upload_handlers=[handler])
    return parser.parse()
开发者ID:cloudbase,项目名称:maas,代码行数:28,代码来源:django.py

示例2: parse_file_upload

 def parse_file_upload(self, META, post_data):
     """Returns a tuple of (POST QueryDict, FILES MultiValueDict)."""
     self.upload_handlers = ImmutableList(
         self.upload_handlers, warning="You cannot alter upload handlers after the upload has been processed."
     )
     parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
     return parser.parse()
开发者ID:fitoria,项目名称:django,代码行数:7,代码来源:__init__.py

示例3: wrapper

	def wrapper(request, *args, **kwargs):

		# Update the query dicts only if it's DELETE
		if request.method == 'DELETE':
			parser = MultiPartParser(request.META, request, [], request.encoding)  # We don't need anything special here, we just want to read a couple of parameters here
			query_dict, files = parser.parse()  # And we don't need files, as files are never processed even if sent
			request.DELETE = query_dict

		return function(request, *args, **kwargs)
开发者ID:Pancho,项目名称:db,代码行数:9,代码来源:decorators.py

示例4: parse

 def parse(self, stream):
     """
     Returns a 2-tuple of `(data, files)`.
     
     `data` will be a :class:`QueryDict` containing all the form parameters.
     `files` will be a :class:`QueryDict` containing all the form files.
     """
     upload_handlers = self.view.request._get_upload_handlers()
     django_parser = DjangoMultiPartParser(self.view.request.META, stream, upload_handlers)
     return django_parser.parse()
开发者ID:CSL306,项目名称:loansProject,代码行数:10,代码来源:parsers.py

示例5: parse_request_data

    def parse_request_data(self):
        if self.request.method == 'POST':
            return self.request.POST, self.request.FILES

        data = self.request.raw_post_data
        if self.request.META.get('CONTENT_TYPE', '').startswith('multipart'):
            data = StringIO(data)
            parser = MultiPartParser(self.request.META, data, self.upload_handlers)
            query =  parser.parse()
            return query

        return QueryDict(data), {}
开发者ID:waylybaye,项目名称:kiss,代码行数:12,代码来源:__init__.py

示例6: parse

    def parse(self, stream):
        """
        Returns a 2-tuple of `(data, files)`.

        `data` will be a :class:`QueryDict` containing all the form parameters.
        `files` will be a :class:`QueryDict` containing all the form files.
        """
        upload_handlers = self.view.request._get_upload_handlers()
        try:
            django_parser = DjangoMultiPartParser(self.view.request.META, stream, upload_handlers)
            return django_parser.parse()
        except MultiPartParserError, exc:
            raise ErrorResponse(status.HTTP_400_BAD_REQUEST,
                                {'detail': 'multipart parse error - %s' % unicode(exc)})
开发者ID:CrowdSpot,项目名称:crowdspot-vagrant-box,代码行数:14,代码来源:parsers.py

示例7: _document_PUT

def _document_PUT(request, document_slug, document_locale):
    """Handle PUT requests as document write API"""

    # Try parsing one of the supported content types from the request
    try:
        content_type = request.META.get('CONTENT_TYPE', '')

        if content_type.startswith('application/json'):
            data = json.loads(request.body)

        elif content_type.startswith('multipart/form-data'):
            parser = MultiPartParser(request.META,
                                     StringIO(request.body),
                                     request.upload_handlers,
                                     request.encoding)
            data, files = parser.parse()

        elif content_type.startswith('text/html'):
            # TODO: Refactor this into wiki.content ?
            # First pass: Just assume the request body is an HTML fragment.
            html = request.body
            data = dict(content=html)

            # Second pass: Try parsing the body as a fuller HTML document,
            # and scrape out some of the interesting parts.
            try:
                doc = pq(html)
                head_title = doc.find('head title')
                if head_title.length > 0:
                    data['title'] = head_title.text()
                body_content = doc.find('body')
                if body_content.length > 0:
                    data['content'] = body_content.html()
            except:
                pass

        else:
            resp = HttpResponse()
            resp.status_code = 400
            resp.content = _("Unsupported content-type: %s") % content_type
            return resp

    except Exception, e:
        resp = HttpResponse()
        resp.status_code = 400
        resp.content = _("Request parsing error: %s") % e
        return resp
开发者ID:surajssd,项目名称:kuma,代码行数:47,代码来源:document.py

示例8: _parse_request_data

def _parse_request_data(request):
    # Try parsing one of the supported content types from the request
    try:
        content_type = request.META.get("CONTENT_TYPE", "")

        if content_type.startswith("application/json"):
            return (json.loads(request.body), None, None)

        elif content_type.startswith("multipart/form-data"):
            parser = MultiPartParser(request.META, StringIO(request.body), request.upload_handlers, request.encoding)
            data, files = parser.parse()
            return (data, files, None)

        else:
            return (None, None, _bad_request(_("Unsupported content-type: %s") % content_type))

    except Exception, e:
        return (None, None, _bad_request(_("Request parsing error: %s") % e))
开发者ID:SimPreetam,项目名称:badges.mozilla.org,代码行数:18,代码来源:views.py

示例9: parse

    def parse(self, stream, media_type=None, parser_context=None):
        """
        Returns a DataAndFiles object.

        `.data` will be a `QueryDict` containing all the form parameters.
        `.files` will be a `QueryDict` containing all the form files.
        """
        parser_context = parser_context or {}
        request = parser_context['request']
        meta = request.META
        upload_handlers = request.upload_handlers

        try:
            parser = DjangoMultiPartParser(meta, stream, upload_handlers)
            data, files = parser.parse()
            return DataAndFiles(data, files)
        except MultiPartParserError, exc:
            raise ParseError('Multipart form parse error - %s' % unicode(exc))
开发者ID:bennullgraham,项目名称:django-rest-framework,代码行数:18,代码来源:parsers.py

示例10: parse

    def parse(self, stream, media_type=None, parser_context=None):
        """
        Returns a DataAndFiles object.

        `.data` will be a `QueryDict` containing all the form parameters.
        `.files` will be a `QueryDict` containing all the form files.
        """
        parser_context = parser_context or {}
        request = parser_context['request']
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
        meta = request.META
        upload_handlers = request.upload_handlers

        try:
            parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding)
            data, files = parser.parse()
            return DataAndFiles(data, files)
        except MultiPartParserError as exc:
            raise ParseError('Multipart form parse error - %s' % six.u(exc))
开发者ID:0x64746b,项目名称:django-rest-framework,代码行数:19,代码来源:parsers.py

示例11: parse

    def parse(self, stream, media_type=None, parser_context=None):
        """
        Parses the incoming bytestream as a multipart encoded form,
        and returns a DataAndFiles object.

        `.data` will be a `QueryDict` containing all the form parameters.
        `.files` will be a `QueryDict` containing all the form files.
        """
        parser_context = parser_context or {}
        request = parser_context["request"]
        encoding = parser_context.get("encoding", settings.DEFAULT_CHARSET)
        meta = request.META.copy()
        meta["CONTENT_TYPE"] = media_type
        upload_handlers = request.upload_handlers

        try:
            parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding)
            data, files = parser.parse()
            return DataAndFiles(data, files)
        except MultiPartParserError as exc:
            raise ParseError("Multipart form parse error - %s" % str(exc))
开发者ID:shreeshreee,项目名称:taiga-back,代码行数:21,代码来源:parsers.py

示例12: parse_body

def parse_body(r, request):
    if request.method == 'POST' or request.method == 'PUT':
        # Parse out profiles/states if the POST dict is not empty
        if 'multipart/form-data' in request.META['CONTENT_TYPE']:
            if request.POST.dict().keys():
                r['params'].update(request.POST.dict())
                parser = MultiPartParser(request.META, StringIO.StringIO(request.raw_post_data),request.upload_handlers)
                post, files = parser.parse()
                r['files'] = files
        # If it is multipart/mixed, parse out all data
        elif 'multipart/mixed' in request.META['CONTENT_TYPE']: 
            parse_attachment(r, request)
        # Normal POST/PUT data
        else:
            if request.body:
                # profile uses the request body
                r['raw_body'] = request.body
                # Body will be some type of string, not necessarily JSON
                r['body'] = convert_to_dict(request.body)
            else:
                raise BadRequest("No body in request")
    return r
开发者ID:varunasingh,项目名称:UMCloudDj-Development,代码行数:22,代码来源:req_parse.py

示例13: process_request

 def process_request(self,req):
     """Interpret POST variables that indicate fake file uploads."""
     #  Bail out if any real files were uploaded
     if len(req.FILES) > 0:
         return None
     #  Find any post variables named like "fakefile_*".
     #  These contain the fake files that are to be uploaded.
     fakefiles = []
     for (k,v) in req.POST.iteritems():
         if k.startswith(self.field_name):
             if v == "": continue
             fakefiles.append((k[len(self.field_name):],self.file_spec[v]))
     if not fakefiles:
         return None
     #  Remove the fakefile keys from POST
     for f in fakefiles:
         del req.POST[self.field_name + f[0]]
     #  Construct a fake request body and META object
     fake_data = FakeFilesData(fakefiles)
     fake_meta = MergeDict(fake_data.META,req.META)
     #  Re-parse the fake data, triggering upload handlers etc.
     parser = MultiPartParser(fake_meta,fake_data,req.upload_handlers,req.encoding)
     (_, req._files) = parser.parse()
开发者ID:JimFarad,项目名称:liquid-galaxy.lg-cms,代码行数:23,代码来源:middleware.py

示例14: _document_PUT

def _document_PUT(request, document_slug, document_locale):
    """Handle PUT requests as document write API"""

    # Try parsing one of the supported content types from the request
    try:
        content_type = request.META.get('CONTENT_TYPE', '')

        if content_type.startswith('application/json'):
            data = json.loads(request.body)

        elif content_type.startswith('multipart/form-data'):
            parser = MultiPartParser(request.META,
                                     StringIO(request.body),
                                     request.upload_handlers,
                                     request.encoding)
            data, files = parser.parse()

        elif content_type.startswith('text/html'):
            # TODO: Refactor this into wiki.content ?
            # First pass: Just assume the request body is an HTML fragment.
            html = request.body
            data = dict(content=html)

            # Second pass: Try parsing the body as a fuller HTML document,
            # and scrape out some of the interesting parts.
            try:
                doc = pq(html)
                head_title = doc.find('head title')
                if head_title.length > 0:
                    data['title'] = head_title.text()
                body_content = doc.find('body')
                if body_content.length > 0:
                    data['content'] = body_content.html()
            except Exception:
                pass

        else:
            resp = HttpResponse()
            resp.status_code = 400
            resp.content = ugettext(
                "Unsupported content-type: %s") % content_type
            return resp

    except Exception as e:
        resp = HttpResponse()
        resp.status_code = 400
        resp.content = ugettext("Request parsing error: %s") % e
        return resp

    try:
        # Look for existing document to edit:
        doc = Document.objects.get(locale=document_locale,
                                   slug=document_slug)
        if not doc.allows_revision_by(request.user):
            raise PermissionDenied
        section_id = request.GET.get('section', None)
        is_new = False

        # Use ETags to detect mid-air edit collision
        # see: http://www.w3.org/1999/04/Editing/
        expected_etag = request.META.get('HTTP_IF_MATCH', False)
        if expected_etag:
            curr_etag = doc.calculate_etag(section_id)
            if curr_etag != expected_etag:
                resp = HttpResponse()
                resp.status_code = 412
                resp.content = ugettext('ETag precondition failed')
                return resp

    except Document.DoesNotExist:
        # No existing document, so this is an attempt to create a new one...
        if not Document.objects.allows_add_by(request.user, document_slug):
            raise PermissionDenied

        # TODO: There should be a model utility for creating a doc...

        # Let's see if this slug path implies a parent...
        slug_parts = split_slug(document_slug)
        if not slug_parts['parent']:
            # Apparently, this is a root page!
            parent_doc = None
        else:
            # There's a parent implied, so make sure we can find it.
            parent_doc = get_object_or_404(Document, locale=document_locale,
                                           slug=slug_parts['parent'])

        # Create and save the new document; we'll revise it immediately.
        doc = Document(slug=document_slug, locale=document_locale,
                       title=data.get('title', document_slug),
                       parent_topic=parent_doc)
        doc.save()
        section_id = None  # No section editing for new document!
        is_new = True

    new_rev = doc.revise(request.user, data, section_id)
    doc.schedule_rendering('max-age=0')

    request.authkey.log(is_new and 'created' or 'updated',
                        new_rev, data.get('summary', None))

#.........这里部分代码省略.........
开发者ID:digisu,项目名称:kuma,代码行数:101,代码来源:document.py

示例15:

from __future__ import unicode_literals
开发者ID:letouriste001,项目名称:SmartForest_2.0,代码行数:1,代码来源:request.py


注:本文中的django.http.multipartparser.MultiPartParser类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。