本文整理汇总了Python中pyramid.response.Response类的典型用法代码示例。如果您正苦于以下问题:Python Response类的具体用法?Python Response怎么用?Python Response使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Response类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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
示例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')
示例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)
示例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
示例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
示例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
示例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
示例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
示例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
示例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
示例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
示例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
示例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