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


Python Response.body方法代码示例

本文整理汇总了Python中pyramid.response.Response.body方法的典型用法代码示例。如果您正苦于以下问题:Python Response.body方法的具体用法?Python Response.body怎么用?Python Response.body使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyramid.response.Response的用法示例。


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

示例1: connector

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import body [as 别名]
def connector(request):
    # init connector and pass options
    elf = elFinder.connector(_opts)

    # fetch only needed GET/POST parameters
    httpRequest = {}
    form=request.params
    for field in elf.httpAllowedParameters:
        if field in form:
            # Russian file names hack
            if field == 'name':
                httpRequest[field] = form.getone(field).encode('utf-8')

            elif field == 'targets[]':
                httpRequest[field] = form.getall(field)

            # handle CGI upload
            elif field == 'upload[]':
                upFiles = {}
                cgiUploadFiles = form.getall(field)
                for up in cgiUploadFiles:
                    if isinstance(up, FieldStorage):
                        upFiles[up.filename.encode('utf-8')] = up.file # pack dict(filename: filedescriptor)
                httpRequest[field] = upFiles
            else:
                httpRequest[field] = form.getone(field)

    # run connector with parameters
    status, header, response = elf.run(httpRequest)

    # get connector output and print it out

    result=Response(status=status)
    try:
        del header['Connection']
    except:
        pass
    result.headers=header

    if not response is None and status == 200:
        # send file
        if 'file' in response and isinstance(response['file'], file):
            result.body=response['file'].read()
            response['file'].close()

        # output json
        else:
            result.body=json.dumps(response)
    return result
开发者ID:aleksandr-rakov,项目名称:elfinder-pyramid,代码行数:51,代码来源:connector.py

示例2: response

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import body [as 别名]
    def response(self, request, error):
        """
            Render an API Response

            Create a Response object, similar to the JSONP renderer
            [TODO: re-factor in to the JSONP renderer]
            Return the Response object with the appropriate error code
        """

        jsonp_render = request.registry._jsonp_render

        default = jsonp_render._make_default(request)
        val = self.serializer(self.envelope(success=False, error=error.error),
                              default=default,
                              **jsonp_render.kw)
        callback = request.GET.get(jsonp_render.param_name)
        response = Response("", status=200)  # API Error code is always 200

        if callback is None:
            ct = 'application/json'
            response.status = error.code
            response.body = val
        else:
            ct = 'application/javascript'
            response.text = '%s(%s)' % (callback, val)

        if response.content_type == response.default_content_type:
            response.content_type = ct
        return response
开发者ID:mattjeffery,项目名称:hairy-octo-bear,代码行数:31,代码来源:wrapper.py

示例3: exportYaml_details

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import body [as 别名]
def exportYaml_details(request):
    lectures = request.db.query(models.Lecture)
    if not "show_all" in request.GET:
        lectures = lectures.filter(models.Lecture.is_visible == True)
    out = []
    for lecture in lectures.all():
        lecture_dict = {}
        lecture_dict["tutorials"] = []
        for tutorial in lecture.tutorials:
            vtutor = "tutor: " + tutorial.tutor.name() if tutorial.tutor != None else "tutor: "
            vemail = "email: " + tutorial.tutor.email if tutorial.tutor != None else "email: "
            vplace = "place: " + tutorial.place
            vtime = "time: " + tutorial.time.__html__()
            vcomment = "comment: " + tutorial.comment
            tutorialItem = (
                vtutor.replace("'", ""),
                vemail,
                vplace.replace("'", ""),
                vtime.replace("'", ""),
                vcomment.replace("'", ""),
            )
            lecture_dict["tutorials"].append(tutorialItem)
        lecture_dict["name"] = lecture.name
        lecture_dict["lecturer"] = lecture.lecturer
        lecture_dict["student_count"] = lecture.lecture_students.count()
        lecture_dict["term"] = lecture.term.__html__()
        out.append(lecture_dict)
        response = Response(content_type="application/x-yaml")
    response.body = yaml.safe_dump(out, allow_unicode=True, default_flow_style=False)
    return response
开发者ID:tynsh,项目名称:muesli,代码行数:32,代码来源:viewsLecture.py

示例4: image

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import body [as 别名]
def image(request):

    image = es.get('wtm/images/'+request.matchdict['imgID'])

    rep = Response()
    rep.body = binascii.a2b_base64(image['_source']['data'])
    return rep
开发者ID:cyplp,项目名称:wtm,代码行数:9,代码来源:views.py

示例5: serve

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import body [as 别名]
 def serve(spec):
     """Resolve the asset ``spec`` to a file path and return a static
       file response that serves it. If the file isn't found, return
       a 404.
     """
     
     # Resolve the spec to a url.
     url = request.static_url(spec)
     if url.startswith('//'):
         url = 'https:' + url
     
     # Download the url.
     r = requests.get(url)
     if r.status_code != requests.codes.ok:
         msg = not_found_msg if r.status_code == 404 else err_message
         return not_found(explanation=msg)
     
     # Return the file response.
     filename = spec.split('/')[-1]
     disposition = 'attachment; filename="{0}"'.format(filename)
     mime_type = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
     response = Response(content_type=mime_type)
     response.headers['Content-Disposition'] = disposition
     response.body = r.content
     return response
开发者ID:andrecp,项目名称:pyramid_weblayer,代码行数:27,代码来源:serve.py

示例6: download_roster

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import body [as 别名]
    def download_roster(self):
        fieldnames = [
            'last_name', 'first_name', 'grade', 'school', 'experience',
            'tourneys', 'emails', 'guardian1_name', 'guardian1_emails']
        output = StringIO()
        writer = DictWriter(output, fieldnames=fieldnames)
        headers = dict((n, n) for n in fieldnames)
        writer.writerow(headers)
        for player in self.context.players():

            g1 = player.guardians()[0]
            g1_last_name = g1.last_name
            g1_first_name = g1.first_name
            g1_title = g1.title
            g1_emails = ','.join(g1.emails)

            writer.writerow(dict(
                last_name=player.last_name,
                first_name=player.first_name,
                grade=player.props['grade'],
                school=player.props['school'],
                experience=player.props['years_experience'],
                tourneys='/'.join(player.tourneys()),
                emails=', '.join(player.emails),
                guardian1_name=g1_title,
                guardian1_emails=g1_emails
            ))

        fn = self.context.__name__ + '-roster.csv'
        res = Response(content_type='text/csv', )
        res.content_disposition = 'attachment;filename=%s' % fn
        res.body = output.getvalue()

        return res
开发者ID:reebalazs,项目名称:fastbreak,代码行数:36,代码来源:views.py

示例7: response_wrapper

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import body [as 别名]
def response_wrapper(status_code, message, result=None):
    resp = Response(status_code=status_code, content_type='application/json')
    data = {'status_code':status_code, 'message':message}
    if result is not None:
        data['result'] = result
    resp.body = json.dumps(data)
    return resp
开发者ID:yahoo,项目名称:imLost-server,代码行数:9,代码来源:helpers.py

示例8: SendFile

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import body [as 别名]
 def SendFile(self, file):
     """
     Creates the response and sends the file back. Uses the FileIterator.
     
     #!date format
     """
     if not file:
         return HTTPNotFound()
     last_mod = file.mtime()
     if not last_mod:
         last_mod = self.context.meta.pool_change
     r = Response(content_type=str(GetMimeTypeExtension(file.extension)), conditional_response=True)
     iterator = file.iterator()
     if iterator:
         r.app_iter = iterator
     else:
         try:
             r.body = file.read()
         except FileNotFound:
             raise NotFound
     r.content_length = file.size
     r.last_modified = last_mod
     r.etag = '%s-%s' % (last_mod, hash(file.path))
     r.cache_expires(self.fileExpires)
     return r    
开发者ID:adroullier,项目名称:nive,代码行数:27,代码来源:views.py

示例9: create_response

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import body [as 别名]
  def create_response(self, request, game_name):

    resp = Response()
    x = xss.XssCleaner()

    js = 'gecoParams = { '
    js += ', '.join(['{}:"{}"'.format(key,x.strip(value)) for key, value in self.map_post.iteritems()])
    js +=' };'

    #load index.html as string
    path = 'games/'+game_name+'/index.html'

    with open(path, "r") as file:
      str = file.read()

    search_str = "<!--GECO_SCRIPT_START-->"
    replace_str = search_str + "\n<script>\n"+ js + "\n</script>"

    final_str = str.replace(search_str, replace_str)

    print final_str
    resp.body = final_str

    #return response
    return resp
开发者ID:RafaelMachadoPinto,项目名称:andy_project,代码行数:27,代码来源:requestTranslator.py

示例10: createResponse

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import body [as 别名]
	def createResponse(self):
		output = StringIO.StringIO()
		self.w.save(output)
		response = Response(content_type='application/vnd.ms-exel')
		response.body = output.getvalue()
		output.close()
		return response
开发者ID:dotlambda,项目名称:muesli,代码行数:9,代码来源:viewsLecture.py

示例11: maps_by_post

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import body [as 别名]
 def maps_by_post(self):
     params = self._get_params()
     config = self.validate_config(params)
     res = Response(content_type='image/png')
     res.status = '200 OK'
     res.body = Generator.generateStream(config)
     return res
开发者ID:cedrikv,项目名称:static_map_generator,代码行数:9,代码来源:views.py

示例12: createResponse

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import body [as 别名]
 def createResponse(self):
     output = StringIO.StringIO()
     self.fig.savefig(output, format="png", dpi=50, bbox_inches="tight")
     pyplot.close(self.fig)
     response = Response()
     response.content_type = "image/png"
     response.body = output.getvalue()
     output.close()
     return response
开发者ID:dotlambda,项目名称:muesli,代码行数:11,代码来源:viewsExam.py

示例13: html

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import body [as 别名]
 def html(self, content):
     """Return HTTP response with given content"""
     response = getattr(self.request, 'response', None)
     if response is None:
         response = Response(body=content)
     else:
         response = self.request.response
         response.body = content
     return response
开发者ID:2070616d,项目名称:TP3,代码行数:11,代码来源:pyramid_strategy.py

示例14: test__make_response_result_is_None_existing_body_not_molested

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import body [as 别名]
 def test__make_response_result_is_None_existing_body_not_molested(self):
     from pyramid.response import Response
     request = testing.DummyRequest()
     response = Response()
     response.body = b'abc'
     request.response = response
     helper = self._makeOne('loo.foo')
     response = helper._make_response(None, request)
     self.assertEqual(response.body, b'abc')
开发者ID:AlanMachado,项目名称:pyramid,代码行数:11,代码来源:test_renderers.py

示例15: inline_view

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import body [as 别名]
def inline_view(context, request, disposition="inline"):
    res = Response(
        headerlist=[
            ("Content-Disposition", '%s;filename="%s"' % (disposition, context.filename.encode("ascii", "ignore"))),
            ("Content-Type", str(context.mimetype)),
        ]
    )
    res.body = context.data
    return res
开发者ID:navi7,项目名称:Kotti,代码行数:11,代码来源:file.py


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