コード例 #1
0
def get_environment(request):
    '''Returns an Gnome Environment object in JSON.'''
    content_requested = request.matchdict.get('obj_id')
    resp = Response(content_type='arraybuffer')
    route = content_requested[1] if len(content_requested) > 1 else None
    if (len(content_requested) > 1):
        if route == 'grid':
            resp.body = get_grid(request)
            resp.headers.add('content-encoding', 'deflate')
            return cors_response(request, resp)
        if route == 'vectors':
            resp.body, dshape = get_vector_data(request)
            resp.headers.add('content-encoding', 'deflate')
            resp.headers.add('Access-Control-Expose-Headers', 'shape')
            resp.headers.add('shape', str(dshape))
            return cors_response(request, resp)
        if route == 'nodes':
            resp.body = get_nodes(request)
            resp.headers.add('content-encoding', 'deflate')
            return cors_response(request, resp)
        if route == 'centers':
            resp.body = get_centers(request)
            resp.headers.add('content-encoding', 'deflate')
            return cors_response(request, resp)
        if route == 'metadata':
            return get_metadata(request)
    else:
        return get_object(request, implemented_types)
コード例 #2
0
ファイル: main.py プロジェクト: seanbudd/tfwnogif
def get_gif(request):
    resp = Response(content_type='application/json')
    if 'guid' not in request.params:
        resp.body = {'error': 'no id'}
        return resp
    guid = request.params['guid']
    if guid not in DATABASE:
        resp.body = {'error': 'bad id'}
        return resp
    resp = Response(content_type='image/gif')
    resp.body = DATABASE[request.params['guid']]
    return resp
コード例 #3
0
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
コード例 #4
0
ファイル: views.py プロジェクト: rangsutu88/Tktr
 def timeleft_view(self):
     if not self.request.root.properties[PROP_KEYS.QUEUE_ENABLED]:
         return 1
     response = Response("text/plain")
     queue = Queue(self.request)
     response.body = str(queue.purchase_time_left())
     return response
コード例 #5
0
  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
コード例 #6
0
ファイル: viewsGrading.py プロジェクト: TuringTux/muesli
 def createResponse(self):
     response = Response(content_type='application/vnd.ms-excel')
     with NamedTemporaryFile() as tmp:
         self.w.save(tmp.name)
         tmp.seek(0)
         response.body = tmp.read()
     return response
コード例 #7
0
ファイル: views.py プロジェクト: cedrikv/static_map_generator
 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
コード例 #8
0
 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
コード例 #9
0
ファイル: views.py プロジェクト: cyplp/wtm
def image(request):

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

    rep = Response()
    rep.body = binascii.a2b_base64(image['_source']['data'])
    return rep
コード例 #10
0
ファイル: views.py プロジェクト: adroullier/nive
 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    
コード例 #11
0
ファイル: views.py プロジェクト: reebalazs/fastbreak
    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
コード例 #12
0
ファイル: serve.py プロジェクト: andrecp/pyramid_weblayer
 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
コード例 #13
0
ファイル: viewsLecture.py プロジェクト: tynsh/muesli
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
コード例 #14
0
ファイル: pyramid.py プロジェクト: pombredanne/ddbmock
def pyramid_router(request):
    # extract action
    target = request.headers.get('x-amz-target')
    action = target.split('.', 2)[1] if target is not None else ""

    post = request.json

    # do the job
    try:
        body = router(action, post)
        status = '200 OK'
    except DDBError as e:
        body = e.to_dict()
        status = '{} {}'.format(e.status, e.status_str)

    # prepare output
    response = Response()
    response.body = json.dumps(body)
    response.status = status
    response.content_type = 'application/x-amz-json-1.0'
    response.headers['x-amzn-RequestId'] = post[
        'request_id']  # added by router

    # done
    return response
コード例 #15
0
ファイル: views.py プロジェクト: cedrikv/static_map_generator
 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
コード例 #16
0
def get_vector_data(request):
    log_prefix = 'req({0}): get_grid():'.format(id(request))
    log.info('>>' + log_prefix)

    session_lock = acquire_session_lock(request)
    log.info('  {} session lock acquired (sess:{}, thr_id: {})'
             .format(log_prefix, id(session_lock), current_thread().ident))
    try:
        obj_id = request.matchdict.get('obj_id')[0]
        obj = get_session_object(obj_id, request)

        if obj is not None:
            log.info('{} found mover of type: {}'
                     .format(log_prefix, obj.__class__))
            vec_data = get_velocities(obj)

            resp = Response(content_type='arraybuffer')

            resp.body, dshape = (zlib.compress(vec_data.tobytes()),
                                 vec_data.shape)

            resp.headers.add('content-encoding', 'deflate')
            resp.headers.add('Access-Control-Expose-Headers', 'shape')
            resp.headers.add('shape', str(dshape))

            return resp
        else:
            exc = cors_exception(request, HTTPNotFound)
            raise exc
    finally:
        session_lock.release()
        log.info('  {} session lock released (sess:{}, thr_id: {})'
                 .format(log_prefix, id(session_lock), current_thread().ident))

    log.info('<<' + log_prefix)
コード例 #17
0
ファイル: rdf.py プロジェクト: lab9k/atramhasis
 def rdf_conceptscheme_export_turtle(self):
     graph = utils.rdf_conceptscheme_dumper(self.provider)
     response = Response(content_type='text/turtle')
     response.body = graph.serialize(format='turtle')
     response.content_disposition = 'attachment; filename="%s.ttl"' % (str(
         self.scheme_id), )
     return response
コード例 #18
0
ファイル: rdf.py プロジェクト: lab9k/atramhasis
 def rdf_conceptscheme_export(self):
     graph = utils.rdf_conceptscheme_dumper(self.provider)
     response = Response(content_type='application/rdf+xml')
     response.body = graph.serialize(format='xml')
     response.content_disposition = 'attachment; filename="%s.rdf"' % (str(
         self.scheme_id), )
     return response
コード例 #19
0
def generate_xlsx_response(data, filename):
    resp = Response()
    resp.body = data
    resp.headerlist.append(('Access-Control-Allow-Origin', '*'))
    resp.content_type = 'application/vnd.ms-excel; charset=utf-8-sig'
    resp.content_disposition = 'attachment; filename=%s' % filename
    return resp
コード例 #20
0
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
コード例 #21
0
ファイル: helpers.py プロジェクト: YahooArchive/imLost-server
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
コード例 #22
0
 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
コード例 #23
0
ファイル: viewsLecture.py プロジェクト: dotlambda/muesli
	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
コード例 #24
0
    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
コード例 #25
0
ファイル: file.py プロジェクト: Doik/Kotti
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
コード例 #26
0
 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
コード例 #27
0
ファイル: viewsExam.py プロジェクト: dotlambda/muesli
 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
コード例 #28
0
 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
コード例 #29
0
def get_release(request):
    '''Returns an Gnome Release object in JSON.'''
    content_requested = request.matchdict.get('obj_id')
    resp = Response(content_type='arraybuffer', content_encoding='deflate')
    route = content_requested[1] if len(content_requested) > 1 else None
    if (len(content_requested) > 1):
        if route == 'start_positions':
            resp.body = get_start_positions(request)
            return cors_response(request, resp)
        if route == 'polygons':
            resp.body, num_lengths = get_polygons(request)
            resp.headers.add('Access-Control-Expose-Headers', 'num_lengths')
            resp.headers.add('num_lengths', str(num_lengths))
            return cors_response(request, resp)
        if route == 'metadata':
            return get_metadata(request)
    else:
        return get_object(request, implemented_types)
コード例 #30
0
ファイル: file.py プロジェクト: navi7/Kotti
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
コード例 #31
0
ファイル: test_renderers.py プロジェクト: AlanMachado/pyramid
 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')
コード例 #32
0
 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')
コード例 #33
0
ファイル: auth.py プロジェクト: rjduffner/SMLocationTrends
def auth(request):
    # Key and Token
    api_key = request.POST.get('api_key')
    access_token = request.POST.get('access_token')

    response = Response(content_type='application/json')
    response.set_cookie('api_key', api_key, max_age=31536000)
    response.set_cookie('access_token', access_token, max_age=31536000)
    response.body = json.dumps({'hello': 'world'})
    return response
コード例 #34
0
ファイル: portrait.py プロジェクト: zworkb/cone.ugm
def portrait_image(model, request):
    """XXX: needs polishing. Return configured default portrait if not set
    on user.
    """
    response = Response()
    settings = general_settings(model)
    response.body = model.attrs[settings.attrs.users_portrait_attr]
    response.headers['Content-Type'] = 'image/jpeg'
    response.headers['Cache-Control'] = 'max-age=0'
    return response
コード例 #35
0
def portrait_image(model, request):
    """XXX: needs polishing. Return configured default portrait if not set
    on user.
    """
    response = Response()
    cfg = ugm_general(model)
    response.body = model.attrs[cfg.attrs['users_portrait_attr']]
    response.headers['Content-Type'] = 'image/jpeg'
    response.headers['Cache-Control'] = 'max-age=0'
    return response
コード例 #36
0
ファイル: file.py プロジェクト: WenkeZhou/Kotti
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
コード例 #37
0
ファイル: viewsGrading.py プロジェクト: TuringTux/muesli
 def __call__(self):
     output = io.BytesIO()
     fig = self.generate_histogram()
     fig.savefig(output, format='png', dpi=50, bbox_inches='tight')
     pyplot.close(fig)
     response = Response()
     response.content_type = 'image/png'
     response.body = output.getvalue()
     output.close()
     return response
コード例 #38
0
ファイル: view.py プロジェクト: Py-AMS/pyams-file
def FileView(request):  # pylint: disable=invalid-name
    """Default file view"""
    context = request.context

    # set content type
    content_type = context.content_type
    if isinstance(content_type, bytes):
        content_type = content_type.decode('utf-8')

    # check for last modification date
    response = Response(content_type=content_type)
    zdc = IZopeDublinCore(context, None)
    if zdc is not None:
        modified = zdc.modified
        if modified is not None:
            if_modified_since = request.if_modified_since
            # pylint: disable=no-member
            if if_modified_since and \
                    (int(modified.timestamp()) <= int(if_modified_since.timestamp())):
                return Response(content_type=content_type, status=NOT_MODIFIED)
            response.last_modified = modified

    body_file = context.get_blob(mode='c')

    if request.params.get('dl') is not None:
        filename = context.filename or 'noname.txt'
        response.content_disposition = 'attachment; filename="{0}"'.format(
            translate_string(filename, force_lower=False))

    # check for range request
    if request.range is not None:
        try:
            body = body_file.read()
            body_length = len(body)
            range_start = request.range.start or 0
            if 'Firefox' in request.user_agent:  # avoid partial range for Firefox videos
                range_end = body_length
            else:
                range_end = request.range.end or min(
                    body_length, range_start + MAX_RANGE_LENGTH)
            ranged_body = body[range_start:range_end]
            response.status = PARTIAL_CONTENT
            response.headers[
                'Content-Range'] = 'bytes {first}-{last}/{len}'.format(
                    first=range_start,
                    last=range_start + len(ranged_body) - 1,
                    len=body_length)
            response.body = ranged_body
        finally:
            body_file.close()
    else:
        response.body_file = body_file

    return response
コード例 #39
0
ファイル: views.py プロジェクト: uralbash/pyramid_elfinder
def connector(request):
    # init connector and pass options
    root = request.registry.settings['pyramid_elfinder_root']
    options = {
        'root': os.path.abspath(root),
        'URL': request.registry.settings['pyramid_elfinder_url']
    }
    elf = elfinder.connector(options)

    # 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):
                        # pack dict(filename: filedescriptor)
                        upFiles[up.filename.encode('utf-8')] = up.file
                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 Exception:
        pass
    result.headers = header
    result.charset = 'utf8'

    if response is not None and status == 200:
        # send file
        if 'file' in response and hasattr(response['file'], 'read'):
            result.body = response['file'].read()
            response['file'].close()
        # output json
        else:
            result.text = json.dumps(response)
    return result
コード例 #40
0
def connector(request):
    # init connector and pass options
    root = request.registry.settings['pyramid_elfinder_root']
    options = {
        'root': os.path.abspath(root),
        'URL': request.registry.settings['pyramid_elfinder_url']
    }
    elf = elfinder.connector(options)

    # 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):
                        # pack dict(filename: filedescriptor)
                        upFiles[up.filename.encode('utf-8')] = up.file
                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 Exception:
        pass
    result.headers = header
    result.charset = 'utf8'

    if response is not None and status == 200:
        # send file
        if 'file' in response and hasattr(response['file'], 'read'):
            result.body = response['file'].read()
            response['file'].close()
        # output json
        else:
            result.text = json.dumps(response)
    return result
コード例 #41
0
    def __call__(self):
        request = self.request
        user = request.user

        # NOTE if an error returns before input is fully read apache will throw a fit

        if not user:
            request.body_file.read()  # read input for apache
            return make_401_error("Authentication Required")

        if "clbcupdate" not in user.cic.ExternalAPIs:
            request.body_file.read()  # read input for apache
            return make_401_error("Insufficient Permissions")

        content_type = request.content_type
        if content_type != "text/xml":
            request.body_file.read()  # read input for apache
            return make_internal_server_error("Unexpected Content-Type")

        encoding = request.charset or "latin1"

        try:
            encoding = codecs.lookup(encoding)
        except LookupError:
            request.body_file.read()  # read input for apache
            return make_internal_server_error("Unexpected Encoding")

        # NOTE if an error returns before here and input is not fully read, apache will throw a fit

        intree = ET.parse(request.body_file,
                          ET.XMLParser(encoding=encoding.name))
        inroot = intree.getroot()

        outxmlroot = ET.Element("VendorTransactionResponses",
                                SessionID=inroot.get("SessionID"))

        try:
            with request.connmgr.get_connection("admin") as conn:
                conn.autocommit = False
                # next sql statement will create the transaction and exit the with
                # statement either rolls it back or commits it based on whether
                # there was an exception

                process_transactions(conn, inroot, outxmlroot, user.Mod)

        except HTTPInternalServerError as e:
            return e

        # Transaction committed and connection closed

        res = Response(content_type="text/xml", charset=encoding.name)
        res.body = ET.tostring(outxmlroot, encoding=encoding.name)

        return res
コード例 #42
0
ファイル: __init__.py プロジェクト: eucalyptus-ja/eucaconsole
def file_download(request):
    session = request.session
    if session.get('file_cache'):
        (filename, mime_type, contents) = session['file_cache']
        # Clean the session information regrading the new keypair
        del session['file_cache']
        response = Response(content_type=mime_type)
        response.body = str(contents)
        response.content_disposition = 'attachment; filename="{name}"'.format(name=filename)
        return response
    # this isn't handled on on client anyway, so we can return pretty much anything
    return Response(body='BaseView:file not found', status=500)
コード例 #43
0
ファイル: file.py プロジェクト: Jickelsen/Arche
def file_data_response(context, request, disposition = 'inline'):
    res = Response(
        headerlist=[
            ('Content-Disposition', '%s;filename="%s"' % (
                disposition, context.filename.encode('ascii', 'ignore'))),
            ('Content-Type', str(context.mimetype)),
            ]
        )
    #Should this be fault tolerant in some way?
    with IBlobs(context)['file'].blob.open() as f:
        res.body = f.read()
    return res
コード例 #44
0
ファイル: viewsTutorial.py プロジェクト: tynsh/muesli
	def __call__(self):
		image = PIL.Image.new('RGB', (self.width,self.height),(255,255,255))
		draw = PIL.ImageDraw.Draw(image)
		draw.rectangle([(0,0),(float(self.width)*self.max_count/self.max_count,10)], fill=self.color2)
		draw.rectangle([(0,0),(float(self.width)*self.count/self.max_count,10)], fill=self.color1)
		output = StringIO.StringIO()
		image.save(output, format='PNG')
		response = Response()
		response.content_type = 'image/png'
		response.cache_control = 'max-age=86400'
		response.body = output.getvalue()
		output.close()
		return response
コード例 #45
0
def file_download(request):
    session = request.session
    if session.get('file_cache'):
        (filename, mime_type, contents) = session['file_cache']
        # Clean the session information regrading the new keypair
        del session['file_cache']
        response = Response(content_type=mime_type)
        response.body = str(contents)
        response.content_disposition = 'attachment; filename="{name}"'.format(
            name=filename)
        return response
    # this isn't handled on on client anyway, so we can return pretty much anything
    return Response(body='BaseView:file not found', status=500)
コード例 #46
0
def get_metrics(request):
    """Pyramid view that return the metrics"""

    if prom.IS_MULTIPROC:
        registry = CollectorRegistry()
        MultiProcessCollector(registry)
    else:
        registry = REGISTRY

    request.response.content_type = CONTENT_TYPE_LATEST
    resp = Response(content_type=CONTENT_TYPE_LATEST, )
    resp.body = generate_latest(registry)
    return resp
コード例 #47
0
ファイル: views.py プロジェクト: ericof/websauna
    def listing(self):
        """Listing core."""

        table = self.table
        columns = table.get_columns()
        query = self.get_query()
        query = self.order_query(query)

        file_title = slugify(self.context.title)
        encoding = "utf-8"

        response = Response()
        response.headers["Content-Type"] = "text/csv; charset={}".format(
            encoding)
        response.headers["Content-Disposition"] = \
        "attachment;filename={}.{}.csv".format(file_title, encoding)

        buf = StringIO()
        writer = csv.writer(buf)
        buffered_rows = self.buffered_rows
        view = self
        request = self.request

        def generate_csv_data():

            # Write headers
            writer.writerow([c.id for c in columns])

            # Write each listing item
            for idx, model_instance in enumerate(query):

                # Extract column values for this row
                values = [c.get_value(view, model_instance) for c in columns]

                writer.writerow(values)
                # if idx % buffered_rows == 0:
                #    yield buf.getvalue().encode(encoding)
                #    buf.truncate(0)  # But in Python 3, truncate() does not move
                #    buf.seek(0)  # the file pointer, so we seek(0) explicitly.

            # yield buf.getvalue().encode(encoding)

            # Abort the transaction, otherwise it might not be closed by underlying machinery
            # (at least tests hang)
            # TODO: Confirm this behavior with pyramid_tm 2.0 when it's out
            # request.tm.abort()

        # TODO: This use to be response.app_iter, but apparently it doesn't place nicely with pyramid_tm
        generate_csv_data()
        response.body = buf.getvalue().encode(encoding)
        return response
コード例 #48
0
ファイル: pyramid.py プロジェクト: Bernie/spyne
    def __call__(self, request):
        retval = Response()

        def start_response(status, headers):
            status, reason = status.split(' ', 1)

            retval.status_int = int(status)
            for header, value in headers:
                retval.headers[header] = value

        response = WsgiApplication.__call__(self, request, start_response)
        retval.body = "".join(response)

        return retval
コード例 #49
0
ファイル: __init__.py プロジェクト: mangroovie/spyne
    def __call__(self, request):
        pyramid_response = Response()
        def start_response(status, headers):
            status, reason = status.split(' ', 1)

            pyramid_response.status_int = int(status)
            pyramid_response.headers["Cache-Control"] = "no-cache, must-revalidate"
            pyramid_response.headers["Expires"] = "Sat, 26 Jul 1997 05:00:00 GMT"
            for header, value in headers:
                pyramid_response.headers[header] = value

        response = WsgiApplication.__call__(self, request, start_response)
        pyramid_response.body = "\n".join(response)
        return pyramid_response
コード例 #50
0
ファイル: views.py プロジェクト: MESAProductSolutions/rta3web
 def make_response(filename):
     import mimetypes
     print "filename"
     print filename.filename
     f = open(filename.filename, 'rb')
     type, encoding = mimetypes.guess_type(filename.filename)
     content_disposition_filename = f.name.encode('ascii', 'replace').split('/')
     content_disposition_filename = content_disposition_filename[-1]
     res = Response(content_type=type or 'application/octet-stream',
                     content_disposition='attachment; filename="%s"'
                     %content_disposition_filename.replace('"','\\')
                 )
     res.body = f.read()
     f.close()
     return res
コード例 #51
0
def download(model, request):
    check_submitter_access(model, request)
    a_type = model.attrs['attachment_type']
    payload = model.attrs['payload']
    response = Response()
    if a_type == 'text':
        response.text = html_2_text(payload)
        response.headers['Content-Type'] = 'text/plain'
        response.headers['Content-Disposition'] = \
            'attachment;filename={0}.txt'.format(model.name)
    elif a_type == 'file':
        payload = pickle.loads(payload)
        file_data = payload['file']
        file_data.seek(0)
        response.body = file_data.read()
        response.headers['Content-Type'] = payload['mimetype']
        response.headers['Content-Disposition'] = \
            'attachment;filename={0}'.format(
                payload['filename'].encode('utf-8'))
    elif a_type == 'image':
        payload = pickle.loads(payload)
        scale = request.params.get('scale')
        filename = payload['filename']
        if scale:
            image_data = payload['scales'][scale]
            filename = '{0}_{1}.{2}'.format(
                filename[:filename.rfind('.')], scale,
                filename[filename.rfind('.') + 1:])
        else:
            image_data = payload['image']
        image_data.seek(0)
        response.body = image_data.read()
        response.headers['Content-Type'] = payload['mimetype']
        response.headers['Content-Disposition'] = \
            'attachment;filename={0}'.format(filename)
    return response
コード例 #52
0
ファイル: ca_certificate.py プロジェクト: aptise/peter_sslers
 def focus_raw(self):
     dbCaCertificate = self._focus()
     if self.request.matchdict['format'] == 'pem':
         self.request.response.content_type = 'application/x-pem-file'
         return dbCaCertificate.cert_pem
     elif self.request.matchdict['format'] == 'pem.txt':
         return dbCaCertificate.cert_pem
     elif self.request.matchdict['format'] in ('cer', 'crt', 'der'):
         as_der = lib.cert_utils.convert_pem_to_der(pem_data=dbCaCertificate.cert_pem)
         response = Response()
         if self.request.matchdict['format'] in ('crt', 'der'):
             response.content_type = 'application/x-x509-ca-cert'
         elif self.request.matchdict['format'] in ('cer', ):
             response.content_type = 'application/pkix-cert'
         response.body = as_der
         return response
     return 'chain.?'
コード例 #53
0
ファイル: __init__.py プロジェクト: aliceh/eucaconsole
def file_download(request):
    if not(BaseView.is_csrf_valid_static(request)):
        return JSONResponse(status=400, message="missing CSRF token")
    session = request.session
    if session.get('file_cache'):
        (filename, mime_type, contents) = session['file_cache']
        # Clean the session information regrading the new keypair
        del session['file_cache']
        response = Response(content_type=mime_type)
        response.body = str(contents)
        response.content_disposition = 'attachment; filename="{name}"'.format(name=filename)
        response.cache_control = 'no-store'
        response.pragma = 'no-cache'
        return response
    # no file found ...
    # this isn't handled on on client anyway, so we can return pretty much anything
    return Response(body='BaseView:file not found', status=500)
コード例 #54
0
ファイル: viewsLecture.py プロジェクト: dotlambda/muesli
def exportYaml(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 = {}
		tutors = set([tutorial.tutor for tutorial in lecture.tutorials])
		lecture_dict['tutors'] = [tutor.name() for tutor in tutors if tutor!= None]
		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
コード例 #55
0
ファイル: pyramid.py プロジェクト: lshift/ddbmock
def pyramid_router(request):
    # extract action
    target = request.headers.get('x-amz-target')
    action = target.split('.', 2)[1] if target is not None else ""

    post = request.json

    # do the job
    try:
        auth = request.headers["Authorization"]
        if not auth.startswith("AWS4-HMAC-SHA256"):
            raise MissingAuthenticationTokenException
        auth = auth[len("AWS4-HMAC-SHA256 "):]
        auth = auth.split(", ")
        auth = dict([x.split("=",2) for x in auth])
        access_key = auth["Credential"].split("/")[0]
        if access_key not in config.keys():
            req_logger.error("Access denied for %s", access_key)
            raise AccessDeniedException, "Can't find %s in users" % access_key
        user = config_for_user(access_key)
        sleep(user["DELAY_OPERATIONS"])
        fail_every = user["FAIL_EVERY_N"]
        if fail_every != None:
            if fail_every + 1 == user[FAIL_KEY]: # hit the fail time
                reset_fail(access_key)
                raise InternalServerError("The server encountered an internal error trying to fulfill the request")

        body = router(action, post, user)
        status = '200 OK'
    except DDBError as e:
        body = e.to_dict()
        status = '{} {}'.format(e.status, e.status_str)
        user = None

    # prepare output
    response = Response()
    response.body = json.dumps(body)
    response.status = status
    response.content_type = 'application/x-amz-json-1.0'
    if post.has_key("request_id"): # might not be present if user auth failed
        response.headers['x-amzn-RequestId'] = post['request_id']  # added by router

    # done
    return response