def test_headers_type(self): r = HttpResponse() # The following tests explicitly test types in addition to values # because in Python 2 u'foo' == b'foo'. # ASCII unicode or bytes values are converted to native strings. r['key'] = 'test' self.assertEqual(r['key'], str('test')) self.assertIsInstance(r['key'], str) r['key'] = 'test'.encode('ascii') self.assertEqual(r['key'], str('test')) self.assertIsInstance(r['key'], str) self.assertIn(b'test', r.serialize_headers()) # Latin-1 unicode or bytes values are also converted to native strings. r['key'] = 'café' self.assertEqual(r['key'], force_str('café', 'latin-1')) self.assertIsInstance(r['key'], str) r['key'] = 'café'.encode('latin-1') self.assertEqual(r['key'], force_str('café', 'latin-1')) self.assertIsInstance(r['key'], str) self.assertIn('café'.encode('latin-1'), r.serialize_headers()) # Other unicode values are MIME-encoded (there's no way to pass them as bytes). r['key'] = '†' self.assertEqual(r['key'], str('=?utf-8?b?4oCg?=')) self.assertIsInstance(r['key'], str) self.assertIn(b'=?utf-8?b?4oCg?=', r.serialize_headers()) # The response also converts unicode or bytes keys to strings, but requires # them to contain ASCII r = HttpResponse() del r['Content-Type'] r['foo'] = 'bar' headers = list(r.items()) self.assertEqual(len(headers), 1) self.assertEqual(headers[0], ('foo', 'bar')) self.assertIsInstance(headers[0][0], str) r = HttpResponse() del r['Content-Type'] r[b'foo'] = 'bar' headers = list(r.items()) self.assertEqual(len(headers), 1) self.assertEqual(headers[0], ('foo', 'bar')) self.assertIsInstance(headers[0][0], str) r = HttpResponse() with self.assertRaises(UnicodeError): r.__setitem__('føø', 'bar') with self.assertRaises(UnicodeError): r.__setitem__('føø'.encode('utf-8'), 'bar')
def test_headers_type(self): r = HttpResponse() # The following tests explicitly test types in addition to values # because in Python 2 u'foo' == b'foo'. # ASCII unicode or bytes values are converted to native strings. r['key'] = 'test' self.assertEqual(r['key'], str('test')) self.assertIsInstance(r['key'], str) r['key'] = 'test'.encode('ascii') self.assertEqual(r['key'], str('test')) self.assertIsInstance(r['key'], str) self.assertIn(b'test', r.serialize_headers()) # Latin-1 unicode or bytes values are also converted to native strings. r['key'] = 'café' self.assertEqual(r['key'], force_str('café', 'latin-1')) self.assertIsInstance(r['key'], str) r['key'] = 'café'.encode('latin-1') self.assertEqual(r['key'], force_str('café', 'latin-1')) self.assertIsInstance(r['key'], str) self.assertIn('café'.encode('latin-1'), r.serialize_headers()) # Other unicode values are MIME-encoded (there's no way to pass them as bytes). r['key'] = '†' self.assertEqual(r['key'], str('=?utf-8?b?4oCg?=')) self.assertIsInstance(r['key'], str) self.assertIn(b'=?utf-8?b?4oCg?=', r.serialize_headers()) # The response also converts unicode or bytes keys to strings, but requires # them to contain ASCII r = HttpResponse() del r['Content-Type'] r['foo'] = 'bar' l = list(r.items()) self.assertEqual(len(l), 1) self.assertEqual(l[0], ('foo', 'bar')) self.assertIsInstance(l[0][0], str) r = HttpResponse() del r['Content-Type'] r[b'foo'] = 'bar' l = list(r.items()) self.assertEqual(len(l), 1) self.assertEqual(l[0], ('foo', 'bar')) self.assertIsInstance(l[0][0], str) r = HttpResponse() with self.assertRaises(UnicodeError): r.__setitem__('føø', 'bar') with self.assertRaises(UnicodeError): r.__setitem__('føø'.encode('utf-8'), 'bar')
def test_headers_type(self): r = HttpResponse() # The following tests explicitly test types in addition to values # because in Python 2 u'foo' == b'foo'. # ASCII unicode or bytes values are converted to native strings. r["key"] = "test" self.assertEqual(r["key"], str("test")) self.assertIsInstance(r["key"], str) r["key"] = "test".encode("ascii") self.assertEqual(r["key"], str("test")) self.assertIsInstance(r["key"], str) self.assertIn(b"test", r.serialize_headers()) # Latin-1 unicode or bytes values are also converted to native strings. r["key"] = "café" self.assertEqual(r["key"], force_str("café", "latin-1")) self.assertIsInstance(r["key"], str) r["key"] = "café".encode("latin-1") self.assertEqual(r["key"], force_str("café", "latin-1")) self.assertIsInstance(r["key"], str) self.assertIn("café".encode("latin-1"), r.serialize_headers()) # Other unicode values are MIME-encoded (there's no way to pass them as bytes). r["key"] = "†" self.assertEqual(r["key"], str("=?utf-8?b?4oCg?=")) self.assertIsInstance(r["key"], str) self.assertIn(b"=?utf-8?b?4oCg?=", r.serialize_headers()) # The response also converts unicode or bytes keys to strings, but requires # them to contain ASCII r = HttpResponse() del r["Content-Type"] r["foo"] = "bar" l = list(r.items()) self.assertEqual(len(l), 1) self.assertEqual(l[0], ("foo", "bar")) self.assertIsInstance(l[0][0], str) r = HttpResponse() del r["Content-Type"] r[b"foo"] = "bar" l = list(r.items()) self.assertEqual(len(l), 1) self.assertEqual(l[0], ("foo", "bar")) self.assertIsInstance(l[0][0], str) r = HttpResponse() with self.assertRaises(UnicodeError): r.__setitem__("føø", "bar") with self.assertRaises(UnicodeError): r.__setitem__("føø".encode("utf-8"), "bar")
def test_unicode_headers(self): r = HttpResponse() # If we insert a unicode value it will be converted to an ascii r['value'] = 'test value' self.assertTrue(isinstance(r['value'], str)) # An error is raised when a unicode object with non-ascii is assigned. self.assertRaises(UnicodeEncodeError, r.__setitem__, 'value', 't\xebst value') # An error is raised when a unicode object with non-ASCII format is # passed as initial mimetype or content_type. self.assertRaises(UnicodeEncodeError, HttpResponse, content_type='t\xebst value') # HttpResponse headers must be convertible to ASCII. self.assertRaises(UnicodeEncodeError, HttpResponse, content_type='t\xebst value') # The response also converts unicode keys to strings.) r['test'] = 'testing key' l = list(r.items()) l.sort() self.assertEqual(l[1], ('test', 'testing key')) # It will also raise errors for keys with non-ascii data. self.assertRaises(UnicodeEncodeError, r.__setitem__, 't\xebst key', 'value')
def write_django_response_as_tornado_response( self, response: HttpResponse) -> None: # This takes a Django HttpResponse and copies its HTTP status # code, headers, cookies, and content onto this # tornado.web.RequestHandler (which is how Tornado prepares a # response to write). # Copy the HTTP status code. self.set_status(response.status_code) # Copy the HTTP headers (iterating through a Django # HttpResponse is the way to access its headers as key/value pairs) for h in response.items(): self.set_header(h[0], h[1]) # Copy any cookies if not hasattr(self, "_new_cookies"): self._new_cookies = [] # type: List[http.cookie.SimpleCookie[str]] self._new_cookies.append(response.cookies) # Copy the response content self.write(response.content) # Close the connection. self.finish()
async def write_django_response_as_tornado_response( self, response: HttpResponse) -> None: # This takes a Django HttpResponse and copies its HTTP status # code, headers, cookies, and content onto this # tornado.web.RequestHandler (which is how Tornado prepares a # response to write). # Copy the HTTP status code. self.set_status(response.status_code) # Copy the HTTP headers (iterating through a Django # HttpResponse is the way to access its headers as key/value pairs) for h in response.items(): self.set_header(h[0], h[1]) # Copy any cookies if not hasattr(self, "_new_cookies"): self._new_cookies: List[http.cookie.SimpleCookie[str]] = [] self._new_cookies.append(response.cookies) # Copy the response content self.write(response.content) # Close the connection. try: await self.finish() except StreamClosedError: # While writing the response, we might realize that the # user already closed the connection; that is fine. pass
def letscreate3(mydata): if mydata: data = mydata else: data = { 'today': datetime.now(timezone.utc), 'amount': 39.99, 'customer_name': 'Cooper Mann', 'order_id': 1233434, } pdf = render_to_pdf('template.html', data) # print("FOR PDF = ") # for key, value in pdf.items(): # print("KEY=" + str(key)) # print("VALUE = " + str(value)) # print("\n") if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "MyInvoice_%s.pdf" % ("125") content = "attachment; filename='%s'" % (filename) response['Content-Length'] = len(response.content) print("AFTER DOWNLOAD") # download = request.GET.get("download") # if download: # # print("AFTER DOWNLOAD") # response['Content-Length'] = len(response.content) # content = "attachment; filename='%s'" % (filename) # # response.content.decode('utf-8').strip() response['Content-Disposition'] = content last_meeting_roo = MeetingRoom.objects.last() new_qs = Invoice( invoice_number=data['invoice_number'], meeting_room=data['id'], ) where = new_qs.invoice_file.save(filename, File(BytesIO(response.content))) # new_qs.save() print("WHERE = " + str(where)) my_new_file_obj = (filename, File(BytesIO(response.content))) # return my_new_file_obj print("NEW QS = " + str(new_qs)) for key, value in response.items(): print("KEY=" + str(key)) print("VALUE = " + str(value)) print("\n") # print(*response) pdf.close() # response.close() # return response # return my_new_file_obj return str(new_qs.invoice_file.url) return HttpResponse("Not found") print("OUTSIDE IF PDF")
def test_headers_type(self): r = HttpResponse() # ASCII strings or bytes values are converted to strings. r['key'] = 'test' self.assertEqual(r['key'], 'test') r['key'] = b'test' self.assertEqual(r['key'], 'test') self.assertIn(b'test', r.serialize_headers()) # Non-ASCII values are serialized to Latin-1. r['key'] = 'café' self.assertIn('café'.encode('latin-1'), r.serialize_headers()) # Other Unicode values are MIME-encoded (there's no way to pass them as # bytes). r['key'] = '†' self.assertEqual(r['key'], '=?utf-8?b?4oCg?=') self.assertIn(b'=?utf-8?b?4oCg?=', r.serialize_headers()) # The response also converts string or bytes keys to strings, but requires # them to contain ASCII r = HttpResponse() del r['Content-Type'] r['foo'] = 'bar' headers = list(r.items()) self.assertEqual(len(headers), 1) self.assertEqual(headers[0], ('foo', 'bar')) r = HttpResponse() del r['Content-Type'] r[b'foo'] = 'bar' headers = list(r.items()) self.assertEqual(len(headers), 1) self.assertEqual(headers[0], ('foo', 'bar')) self.assertIsInstance(headers[0][0], str) r = HttpResponse() with self.assertRaises(UnicodeError): r.__setitem__('føø', 'bar') with self.assertRaises(UnicodeError): r.__setitem__('føø'.encode(), 'bar')
def test_headers_type(self): r = HttpResponse() # ASCII strings or bytes values are converted to strings. r['key'] = 'test' self.assertEqual(r['key'], 'test') r['key'] = 'test'.encode('ascii') self.assertEqual(r['key'], 'test') self.assertIn(b'test', r.serialize_headers()) # Non-ASCII values are serialized to Latin-1. r['key'] = 'café' self.assertIn('café'.encode('latin-1'), r.serialize_headers()) # Other unicode values are MIME-encoded (there's no way to pass them as bytes). r['key'] = '†' self.assertEqual(r['key'], '=?utf-8?b?4oCg?=') self.assertIn(b'=?utf-8?b?4oCg?=', r.serialize_headers()) # The response also converts string or bytes keys to strings, but requires # them to contain ASCII r = HttpResponse() del r['Content-Type'] r['foo'] = 'bar' headers = list(r.items()) self.assertEqual(len(headers), 1) self.assertEqual(headers[0], ('foo', 'bar')) r = HttpResponse() del r['Content-Type'] r[b'foo'] = 'bar' headers = list(r.items()) self.assertEqual(len(headers), 1) self.assertEqual(headers[0], ('foo', 'bar')) self.assertIsInstance(headers[0][0], str) r = HttpResponse() with self.assertRaises(UnicodeError): r.__setitem__('føø', 'bar') with self.assertRaises(UnicodeError): r.__setitem__('føø'.encode(), 'bar')
def test_unicode_headers(self): r = HttpResponse() # If we insert a unicode value it will be converted to an ascii r['value'] = u'test value' self.failUnless(isinstance(r['value'], str)) # An error is raised When a unicode object with non-ascii is assigned. self.assertRaises(UnicodeEncodeError, r.__setitem__, 'value', u't\xebst value') # The response also converts unicode keys to strings.) r[u'test'] = 'testing key' l = list(r.items()) l.sort() self.assertEqual(l[1], ('test', 'testing key')) # It will also raise errors for keys with non-ascii data. self.assertRaises(UnicodeEncodeError, r.__setitem__, u't\xebst key', 'value')
def letscreate2(mydata): if mydata: data = mydata else: data = { 'today': datetime.now(timezone.utc), 'amount': 39.99, 'customer_name': 'Cooper Mann', 'order_id': 1233434, } pdf = render_to_pdf('template.html', data) print("FOR PDF = ") for key, value in pdf.items(): print("KEY=" + str(key)) print("VALUE = " + str(value)) print("\n") # return HttpResponse(pdf, content_type='application/pdf') # print("PDF_CONTENT = " + str(pdf.content)) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "MyInvoice_%s.pdf" % ("125") content = "attachment; filename='%s'" % (filename) response['Content-Length'] = len(response.content) # download = request.GET.get("download") # if download: # # print("AFTER DOWNLOAD") # response['Content-Length'] = len(response.content) # content = "attachment; filename='%s'" % (filename) # # response.content.decode('utf-8').strip() response['Content-Disposition'] = content for key, value in response.items(): print("KEY=" + str(key)) print("VALUE = " + str(value)) print("\n") # print(*response) pdf.close() # response.close() return response return HttpResponse("Not found") print("OUTSIDE IF PDF")
def response_headers(request): rep = HttpResponse(content_type='application/json') headers = {k: v for k, v in rep.items()} headers['Content-Length'] = '' if request.META['QUERY_STRING']: query_string_list = [ qs.split('=', 1) for qs in unquote(request.META['QUERY_STRING']).split('&') ] for k, v in query_string_list: rep[k] = v if k not in headers: headers[k] = v else: if isinstance(headers[k], list): headers[k].append(v) else: headers[k] = [headers[k], v] length = len(json.dumps(headers, **JSON_FORMAT)) headers['Content-Length'] = str(length + len(str(length))) rep['Content-Length'] = headers['Content-Length'] rep.content = json.dumps(headers, **JSON_FORMAT) return rep
def _get_headers_from_response(self, response: HttpResponse) -> dict: return {header: value for header, value in response.items()}
def process_response(self, request, response): # if this was a successful websocket-events request, then hijack the response if getattr(request, 'wscontext', None) and response.status_code == 200 and len( response.content) == 0: wscontext = request.wscontext # meta to remove? meta_remove = set() for k, v in wscontext.orig_meta.iteritems(): found = False for nk, nv in wscontext.meta: if nk.lower() == k: found = True break if not found: meta_remove.add(k) # meta to set? meta_set = dict() for k, v in wscontext.meta.iteritems(): lname = k.lower() need_set = True for ok, ov in wscontext.orig_meta: if lname == ok and v == ov: need_set = False break if need_set: meta_set[lname] = v events = list() if wscontext.accepted: events.append(WebSocketEvent('OPEN')) events.extend(wscontext.out_events) if wscontext.closed: events.append( WebSocketEvent('CLOSE', pack('>H', wscontext.out_close_code))) response = HttpResponse( encode_websocket_events(events), content_type='application/websocket-events') if wscontext.accepted: response['Sec-WebSocket-Extensions'] = 'grip' for k in meta_remove: response['Set-Meta-' + k] = '' for k, v in meta_set.iteritems(): response['Set-Meta-' + k] = v else: grip_info = None if hasattr(request, 'grip_info'): grip_info = request.grip_info elif hasattr(response, 'grip_info'): # old django-grip versions required passing an HttpResponse to the # set_hold_* methods, so fall back to that for backwards compat grip_info = response.grip_info if grip_info: if not request.grip_proxied and getattr( settings, 'GRIP_PROXY_REQUIRED', False): return HttpResponse('Not Implemented\n', status=501) channels = grip_info['channels'] # apply prefix to channels if needed prefix = _get_prefix() if prefix: for c in channels: c.name = prefix + c.name # code 304 only allows certain headers. if the webserver # strictly enforces this, then we won't be able to use # Grip- headers to talk to the proxy. work around this by # using body instructions instead. if response.status_code == 304: headers = list() for k, v in response.items(): headers.append([k, v]) iresponse = Response(code=response.status_code, reason=getattr( response, 'reason_phrase', None), headers=headers, body=response.content) body = create_hold(grip_info['hold'], channels, iresponse, timeout=grip_info.get('timeout')) response = HttpResponse( body + '\n', content_type='application/grip-instruct') else: response['Grip-Hold'] = grip_info['hold'] response['Grip-Channel'] = create_grip_channel_header( channels) if 'timeout' in grip_info: response['Grip-Timeout'] = str(grip_info['timeout']) return response