• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python response.Response类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: download_backup

def download_backup(request):
    encoded_filename = request.matchdict['backup_id']

    headers = []

    try:
        filename = base64.b64decode(encoded_filename).decode('utf-8')
    except TypeError:
        return HTTPNotFound()

    backups_dir = get_backups_dir()
    all_backups = [x for x in os.listdir(backups_dir) if os.path.isfile(os.path.join(backups_dir, x))]
    if filename not in all_backups:
        return HTTPNotFound()

    full_path = os.path.join(backups_dir, filename)
    if not os.path.isfile(full_path):
        return HTTPNotFound()

    headers = []
    content_length = os.path.getsize(full_path)
    headers.append(('Content-Length', str(content_length)))
    headers.append(('Content-Disposition', str('attachment; filename={0}'.format(filename))))

    response = Response(content_type='application/octet-stream')
    try:
        response.app_iter = open(full_path, 'rb')
    except IOError:
        return HTTPNotFound()

    response.headerlist += headers

    return response
开发者ID:sigsergv,项目名称:pyrone,代码行数:33,代码来源:admin.py


示例2: httpexception_view

def httpexception_view(exc, request):
    # This special case exists for the easter egg that appears on the 404
    # response page. We don't generally allow youtube embeds, but we make an
    # except for this one.
    if isinstance(exc, HTTPNotFound):
        request.find_service(name="csp").merge(
            {
                "frame-src": ["https://www.youtube-nocookie.com"],
                "script-src": ["https://www.youtube.com", "https://s.ytimg.com"],
            }
        )
    try:
        # Lightweight version of 404 page for `/simple/`
        if isinstance(exc, HTTPNotFound) and request.path.startswith("/simple/"):
            response = Response(body="404 Not Found", content_type="text/plain")
        else:
            response = render_to_response(
                "{}.html".format(exc.status_code), {}, request=request
            )
    except LookupError:
        # We don't have a customized template for this error, so we'll just let
        # the default happen instead.
        return exc

    # Copy over the important values from our HTTPException to our new response
    # object.
    response.status = exc.status
    response.headers.extend(
        (k, v) for k, v in exc.headers.items() if k not in response.headers
    )

    return response
开发者ID:craig5,项目名称:warehouse,代码行数:32,代码来源:views.py


示例3: process_upload

    def process_upload(self):
        """ Process a single upload.  Also see:
            https://github.com/valums/file-uploader/blob/master/server/readme.md

        :result: Status object with URL of the created item (on success) or
                 error message on failure.
        :rtype: dict
        """

        fs = self.request.POST["qqfile"]
        # We can fail hard, as somebody is trying to cheat on us if that fails.
        assert isinstance(fs, FieldStorage)

        try:
            factory = self.factory_by_name(self.request.POST["content_type"])
        except KeyError as e:
            result = {"success": False, "error": e.message}
        else:
            name = title_to_name(fs.filename, blacklist=self.context.keys())
            self.context[name] = node = factory.from_field_storage(fs)
            node.title = fs.filename

            result = {"success": True, "url": self.request.resource_url(node)}

        # FineUploader expects JSON with Content-Type 'text/plain'
        response = Response(json.dumps(result))
        response.content_type = "text/plain"

        return response
开发者ID:Kotti,项目名称:Kotti,代码行数:29,代码来源:upload.py


示例4: upload

def upload(request):
    if request.content_length/1000000 > 20:
        return error_response(400, 'Sorry, but the file must be under 20MB.')

    # Create photo object in database
    photo = Photo(datetime.today(), request.POST['file'].filename, request.client_addr, request.content_type, request.content_length)
    DBSession.add(photo)
    DBSession.flush()

    # Save uploaded file
    input_file = request.POST['file'].file
    input_file.seek(0)
    if not os.path.exists('data'):
        os.makedirs('data')
    if not os.path.exists('data/uploads'):
        os.makedirs('data/uploads')
    upload_path = os.path.join('data', 'uploads', str(photo.id))
    with open(upload_path, 'w') as f:
        shutil.copyfileobj(input_file, f)

    # Check the content type and rename as appropriate
    mime = magic.from_file(upload_path, mime=True)
    if mime not in ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/tiff', 'image/x-tiff']:
        resp = Response('Sorry, but we can only accept jpg, gif, or png files.')
        resp.status_code = 400
        resp.status_string = '400 Bad Request'
        return resp
    extension = {'image/jpeg': '.jpg', 'image/pjpeg': '.jpg',
                 'image/gif': '.gif', 'image/png': '.png',
                 'image/tiff': '.tiff', 'image/x-tiff': '.tiff'}[mime]
    os.rename(upload_path, upload_path + extension)
    photo.content_type = mime

    return Response('OK')
开发者ID:reberhardt7,项目名称:hcc-photo-upload,代码行数:34,代码来源:views.py


示例5: test_process_response_nonhtml

 def test_process_response_nonhtml(self):
     response = Response()
     response.content_type = 'text/plain'
     request = Request.blank('/')
     toolbar = self._makeOne(request, [DummyPanel])
     toolbar.process_response(response)
     self.assertTrue(response.processed)
开发者ID:driax,项目名称:pyramid_debugtoolbar,代码行数:7,代码来源:test_toolbar.py


示例6: pvc1_show_imageh5

def pvc1_show_imageh5(request):
    # Loads JPEG images from hdf5 file
    h5_image_file = 'pvc1/pvc1_movie_frames.h5'
    movie_id = int(request.matchdict['movie_id'])
    segment_id = int(request.matchdict['segment_id'])
    frame = int(request.matchdict['frame'])
    image_dir = 'movie%03u_%03u.images' % (movie_id, segment_id)
    image_name = 'movie%03u_%03u_%03u.jpeg' % (movie_id, segment_id, frame)
    path = image_dir + '/' + image_name
    response = Response(content_type='image/jpeg')
    h5f = h5py.File(h5_image_file, 'r')
    try:
        ds = h5f[path]
    except KeyError: 
        # missing file, generate an image to return
        img = Image.new("RGB", (320, 220,), "#cccccc"  )
        draw = ImageDraw.Draw(img)
        draw.text((15, 60), image_name + ' missing', fill='#000')
        f = cStringIO.StringIO()
        img.save(f, "jpeg")
        f.seek(0)
        response.app_iter = f
    else:
        dsv = ds.value
        response.app_iter = dsv
    h5f.close()
    return response
开发者ID:MarvinT,项目名称:CRCNS-Data-Sharing-Project,代码行数:27,代码来源:app.py


示例7: swf_file

def swf_file(request):
    sbid = request.matchdict['sbid']
    req_part = request.matchdict['part']

    monograph = Monograph.get(request.db, sbid)
    if req_part == monograph.isbn:
        try:
            pdf_file = request.db.fetch_attachment(monograph._id, monograph.pdf_file['filename'])
        except (couchdbkit.ResourceNotFound, AttributeError):
            raise exceptions.NotFound()
    else:
        parts = get_book_parts(monograph._id, request)
        try:
            selected_part = parts[int(req_part)]
        except (IndexError, ValueError):
            raise exceptions.NotFound()

        part = Part.get(request.db, selected_part['part_sbid'])
        try:
            pdf_file = request.db.fetch_attachment(part._id, part.pdf_file['filename'])
        except (couchdbkit.ResourceNotFound, AttributeError):
            raise exceptions.NotFound()

    swf_file = functions.convert_pdf2swf(pdf_file)

    response = Response(content_type='application/x-shockwave-flash', expires=datetime_rfc822(365))
    response.app_iter = swf_file
    try:
        response.etag = str(hash(swf_file))
    except TypeError:
        #cannot generate a hash for the object, return it without the ETag
        pass

    return response
开发者ID:gustavofonseca,项目名称:scielobooks-bir,代码行数:34,代码来源:views.py


示例8: serve

 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,代码行数:25,代码来源:serve.py


示例9: post

    def post(self):
        rows = self.session.query('cid', 'cname', 'uid', 'uname', 'date', 'time').from_statement("""
        SELECT c.id as cid, c.name as cname, u.id as uid, u.name as uname, date_trunc('month', t.date) as date, SUM(t.time) as time
        FROM time_entry t, project p, client c, "user" u
        WHERE t.project_id = p.id AND
              p.client_id = c.id AND
              t.user_id = u.id AND
              t.deleted = false
        GROUP BY c.id, c.name, u.id, u.name, date_trunc('month', t.date)
        ORDER BY date_trunc('month', t.date)
        """).all()

        monthly = h.groupby(rows, lambda row: (row[2], row[-2]), lambda row: row[5])

        rows = [(
            row[1],
            row[3],
            row[5],
            row[4].strftime('%Y-%m-%d'),
            sum(monthly[row[2], row[-2]]),
        ) for row in rows]


        stream = self._to_excel(rows)

        response = Response(
            content_type='application/vnd.ms-excel',
            app_iter=stream,
        )
        response.headers['Cache-Control'] = 'no-cache'
        response.content_disposition = 'attachment; filename="report-%s.xls"' % datetime.datetime.now().strftime('%d-%m-%Y--%H-%M-%S')

        return response
开发者ID:adamgr,项目名称:intranet,代码行数:33,代码来源:client.py


示例10: export

def export(request):
    dbsession = DBSession()
    root = dbsession.query(MyModel).filter(MyModel.name==u'root').first()
    auth = _get_basicauth_credentials(request)

    data = parseData(folderbase=REDIRECTIONS_PATH)

    entorns = [dict(id=int(a),entorn=data['entorns'][a]) for a in data['entorns'].keys()]
    instances = [data['instancies'][a] for a in data['instancies'].keys()]

    json_data_list = []
    for ins in instances:
        if len(ins['urls'])>0:
            url = ins['urls'][0]['gwurl'].replace('https','http')
        json_data = dict(url=url,
                         zeoport=ins['zeoport'],
                         debugport=ins['debugport'],
                         mountpoint=ins['mountpoint'],
                         plonesite=ins['plonesite'],
                         title=ins['title'],
                         entorn=ins['entorn'],
                         )
        json_data_list.append(json_data)

    response = Response(json.dumps(json_data_list))
    response.content_type = 'application/json'
    return response
开发者ID:UPCnet,项目名称:genweb.manager,代码行数:27,代码来源:views.py


示例11: response

    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,代码行数:29,代码来源:wrapper.py


示例12: dump_entries_to_excel

def dump_entries_to_excel(entries, group_by, bigger_than):
    wbk = xlwt.Workbook()
    sheet = wbk.add_sheet("Hours")

    heading_xf = xlwt.easyxf("font: bold on; align: wrap on, vert centre, horiz center")
    headings = ("Client", "Project", "Ticket id", "Employee", "Description", "Date", "Time")
    headings_width = (x * 256 for x in (20, 30, 10, 40, 100, 12, 10))
    for colx, value in enumerate(headings):
        sheet.write(0, colx, value, heading_xf)
    for i, width in enumerate(headings_width):
        sheet.col(i).width = width

    sheet.set_panes_frozen(True)
    sheet.set_horz_split_pos(1)
    sheet.set_remove_splits(True)

    rows, asum = ExcelRow.from_ordered_data(entries, group_by, bigger_than)
    for j, row in enumerate(rows):
        row = row.pprint_row()
        for i, cell in enumerate(row):
            sheet.write(j + 1, i, *cell)

    file_path = "/tmp/tmp.xls"
    wbk.save(file_path)

    file = open(file_path, "rb")
    response = Response(content_type="application/vnd.ms-excel", app_iter=file)
    response.headers["Cache-Control"] = "no-cache"
    response.content_disposition = 'attachment; filename="report-%s.xls"' % datetime.datetime.now().strftime(
        "%d-%m-%Y--%H-%M-%S"
    )

    return file, response
开发者ID:kalek,项目名称:intranet,代码行数:33,代码来源:times.py


示例13: plot

def plot(request):
    """
    http://stackoverflow.com/a/5515994/185820
    """

    import cStringIO
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_agg import FigureCanvasAgg

    x, y = 4, 4
    qs = parse_qs(request.query_string)
    if 'x' in qs:
        x = int(qs['x'][0])
    if 'y' in qs:
        y = int(qs['y'][0])
    fig = Figure(figsize=[x, y])
    ax = fig.add_axes([.1, .1, .8, .8])
    ax.scatter([1, 2], [3, 4])
    canvas = FigureCanvasAgg(fig)

    # write image data to a string buffer and get the PNG image bytes
    buf = cStringIO.StringIO()
    canvas.print_png(buf)
    data = buf.getvalue()

    # write image bytes back to the browser
    response = Response(data)
    response.content_type = 'image/png'
    response.content_length = len(data)
    return response
开发者ID:,项目名称:,代码行数:30,代码来源:


示例14: failed_conversion

def failed_conversion(exc, request):
    # If the view has two formal arguments, the first is the context.
    # The context is always available as ``request.context`` too.
    filetype = exc.args[0] if exc.args else ""
    response =  Response('Failed conversion: file of type %s could not be converted. A common cause is a table of contents or other automated index. Remove this from your file, save, and try again.' %filetype)
    response.status_int = 500
    return response
开发者ID:langsci,项目名称:conversion,代码行数:7,代码来源:views.py


示例15: MergeFile

def MergeFile(req):
    def DecreaseLarger(arr, n):
        for i in xrange(len(arr)):
            if arr[i] > n:
                arr[i] -= 1

    fname = GetQueryFileName(req.GET)
    links = Reference.FileLinks(fname)
    try:
        n = int(req.GET["n"])
    except:
        return HTTPBadRequest_Param("n")
    try:
        o = int(req.GET["o"])
    except:
        return HTTPBadRequest_Param("o")
    for j in links:
        if n in j.Depends:
            j.Depends.remove(n)
            if not o in j.Depends:
                j.Depends = sorted(j.Depends + [o])
        DecreaseLarger(j.Depends, n)
    for i in xrange(n, len(links) - 1):
        f = fname + "_" + str(i + 1)
        if os.path.exists(f):
            os.rename(f, fname + "_" + str(i))
    if o > n:
        o -= 1
    del links.Links[n]
    links.Write(fname)
    resp = Response('{"removed":[' + str(n) + '],"select":' + str(o) + ',"files":[' + ",".join(['{"name":"' + os.path.split(l.Name)[1] + '","type":' + str(l.Type) + ',"deps":[' + ",".join([test(d < 65535, str(d), "-1") for d in l.Depends]) + ']}' for l in links]) + ']}\r\n', request=req)
    resp.cache_expires(0)
    return resp
开发者ID:jmchilton,项目名称:protvis,代码行数:33,代码来源:__init__.py


示例16: response_wrapper

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,代码行数:7,代码来源:helpers.py


示例17: __call__

	def __call__(self):
		request = self.request
		user = request.user

		if not user:
			return make_401_error(u'Access Denied')

		if 'airsexport' not in user.cic.ExternalAPIs:
			return make_401_error(u'Insufficient Permissions')

		model_state = modelstate.ModelState(request)
		model_state.schema = AIRSExportOptionsSchema()
		model_state.form.method = None

		if not model_state.validate():
			if model_state.is_error('DST'):
				msg = u"Invalid Distribution"
			elif model_state.is_error("version"):
				msg = u"Invalid Version"
			else:
				msg = u"An unknown error occurred."

				log.error('AIRS Export Errors: %s: %s', msg, model_state.form.errors)
			return make_internal_server_error(msg)

		res = Response(content_type='application/zip', charset=None)
		res.app_iter, res.length = _zip_stream(request, model_state)

		res.headers['Content-Disposition'] = 'attachment;filename=Export.zip'
		return res
开发者ID:OpenCIOC,项目名称:onlineresources,代码行数:30,代码来源:airs.py


示例18: buildResponse

 def buildResponse(self, payload=None):
     """
     """
     data = payload == None and self.data or payload
     response = Response(data, status_int=self.status_code)
     response.content_type = self.response_content_type
     return response
开发者ID:albertcasado,项目名称:max,代码行数:7,代码来源:ResourceHandlers.py


示例19: pdf_file

def pdf_file(request):
    sbid = request.matchdict['sbid']
    req_part = request.matchdict['part'].split('-')

    monograph = Monograph.get(request.db, sbid)
    if len(req_part) == 2 and req_part[1] == monograph.isbn:
        try:
            pdf_file = request.db.fetch_attachment(monograph._id, monograph.pdf_file['filename'], stream=True)
        except (couchdbkit.ResourceNotFound, AttributeError):
            raise exceptions.NotFound()
    else:
        parts = get_book_parts(monograph._id, request)
        try:
            selected_part = parts[int(req_part[2])]
        except (IndexError, ValueError):
            raise exceptions.NotFound()

        part = Part.get(request.db, selected_part['part_sbid'])
        try:
            pdf_file = request.db.fetch_attachment(part._id, part.pdf_file['filename'], stream=True)
        except (couchdbkit.ResourceNotFound, AttributeError):
            raise exceptions.NotFound()

    response = Response(content_type='application/pdf', expires=datetime_rfc822(365))
    response.app_iter = pdf_file
    try:
        response.etag = str(hash(pdf_file))
    except TypeError:
        #cannot generate a hash for the object, return it without the ETag
        pass

    return response
开发者ID:gustavofonseca,项目名称:scielobooks-bir,代码行数:32,代码来源:views.py


示例20: dynamic_item_img

def dynamic_item_img(request):
	item = Item.from_id(request.matchdict['item_id'])
	response = Response(content_type='image/jpeg')
	class Hack():
		def __init__(self, img):
			self.img = img
			self.idx = 0
		def getattr(self, item):
			print("item {}".format(item))
			raise AttributeError
		def __getattr(self, item):
			print("item {}".format(item))
			raise AttributeError
		def read(self, block_size = None):
			if self.idx >= len(self.img):
				return ''
			if block_size is None:
				self.idx = len(self.img)
				return self.img
			if self.idx + block_size > len(self.img):
				r = self.img[self.idx:]
				self.idx = len(self.img)
				return r
			else:
				r = self.img[self.idx:block_size]
				self.idx += block_size
				return r
		def close(self):
			pass
	h = Hack(item.img.img)
	response.app_iter = FileIter(h)
	return response
开发者ID:higherkuo,项目名称:chez-betty,代码行数:32,代码来源:views_dynamic.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python template.Template类代码示例发布时间:2022-05-27
下一篇:
Python response.FileResponse类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap