def test_can_use_a_context(self): # Setup response_1 = HttpResponse(content_type='application/pdf') response_2 = HttpResponse(content_type='application/pdf') # Run & check generate_pdf('pdf.html', file_object=response_1) generate_pdf('pdf.html', file_object=response_2, context={'title': 'test'}) self.assertTrue(response_2.tell() > response_1.tell())
def test_file_interface(self): r = HttpResponse() r.write(b"hello") self.assertEqual(r.tell(), 5) r.write("привет") self.assertEqual(r.tell(), 17) r = HttpResponse(['abc']) self.assertRaises(Exception, r.write, 'def')
def test_file_interface(self): r = HttpResponse() r.write(b"hello") self.assertEqual(r.tell(), 5) r.write("привет") self.assertEqual(r.tell(), 17) r = HttpResponse(['abc']) r.write('def') self.assertEqual(r.tell(), 6) self.assertEqual(r.content, b'abcdef')
def test_file_interface(self): r = HttpResponse() r.write(b"hello") self.assertEqual(r.tell(), 5) r.write("привет") self.assertEqual(r.tell(), 17) r = HttpResponse(["abc"]) r.write("def") self.assertEqual(r.tell(), 6) self.assertEqual(r.content, b"abcdef")
def export_keepass(creds, password): db = Database() groups = {} for c in creds: # Create the group if we havent yet if c.group.name not in groups.keys(): groups[c.group.name] = db.create_group(title=c.group.name) kpg = groups[c.group.name] # Add tags list to the end of the description tags = "\n\nTags: " for t in c.tags.all(): tags += "[" tags += t.name tags += "] " desc = unicode(c.description) + tags # Create the entry e = kpg.create_entry(title=c.title, username=c.username, password=c.password, url=c.url, notes=desc) if c.attachment: e.binary_desc = c.attachment_name e.binary = c.attachment.read() # Send the response response = HttpResponse(content_type="application/x-keepass") db.save(response, password=password) response["Content-Disposition"] = "attachment; filename=RatticExport.kdb" response["Content-Length"] = response.tell() return response
def export_keepass(creds, password): db = Database() groups = {} for c in creds: # Create the group if we havent yet if c.group.name not in groups.keys(): groups[c.group.name] = db.create_group(title=c.group.name) kpg = groups[c.group.name] # Add tags list to the end of the description tags = '\n\nTags: ' for t in c.tags.all(): tags += '[' tags += t.name tags += '] ' desc = str(c.description) + tags # Create the entry kpg.create_entry( title=c.title, username=c.username, password=c.password, url=c.url, notes=desc, ) # Send the response response = HttpResponse(mimetype='application/x-keepass') db.save(response, password=password) response['Content-Disposition'] = 'attachment; filename=RatticExport.kdb' response['Content-Length'] = response.tell() return response
def test_can_generate_a_pdf_into_a_http_response(self): # Setup response = HttpResponse(content_type='application/pdf') # Run & check generate_pdf('public/journal/article_pdf_coverpage.html', file_object=response) self.assertTrue(isinstance(response.content, bytes)) self.assertTrue(response.tell())
def export_csv(request): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=transactions.csv.zip' zip_file = zipfile.ZipFile( response, "w", zipfile.ZIP_DEFLATED) csv_file = StringIO.StringIO() dialect = csv.excel() dialect.quotechar = '"' dialect.delimiter = ',' csv_writer = csv.writer(csv_file, dialect=dialect) for transaction in Transaction.objects.order_by("date"): # generate chunk csv_writer.writerow([transaction.date, transaction.pirate_account.account.iban, transaction.amount, transaction.beneficiary.current_banking_account.iban if transaction.beneficiary.current_banking_account else "", transaction.BIC, transaction.beneficiary.lastname+" "+transaction.beneficiary.firstname, "%s %s %s"%(transaction.beneficiary.street, transaction.beneficiary.postal_code, transaction.beneficiary.city), transaction.code, transaction.statement.encode("utf-8")]) zip_file.writestr("transactions.csv",csv_file.getvalue()) csv_file.close() zip_file.close() # generate the file response['Content-Length'] = response.tell() return response
def export_members(request): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=transactions.csv.zip' zip_file = zipfile.ZipFile( response, "w", zipfile.ZIP_DEFLATED) csv_file = StringIO.StringIO() dialect = csv.excel() dialect.quotechar = '"' dialect.delimiter = ',' csv_writer = csv.writer(csv_file, dialect=dialect) for person in Person.objects.order_by("postal_code"): # generate chunk csv_writer.writerow([person.firstname.encode("utf-8"), person.lastname.encode("utf-8"), person.email_address, person.street.encode("utf-8"), person.postal_code, person.city.encode("utf-8"), person.telephone, person.language, person.notas.encode("utf-8"), person.last_payment_date]) zip_file.writestr("transactions.csv",csv_file.getvalue()) csv_file.close() zip_file.close() # generate the file response['Content-Length'] = response.tell() return response
def test_file_interface(self): r = HttpResponse() r.write(b"hello") self.assertEqual(r.tell(), 5) r.write("привет") self.assertEqual(r.tell(), 17) r = HttpResponse(["abc"]) r.write("def") self.assertEqual(r.tell(), 6) self.assertEqual(r.content, b"abcdef") # with Content-Encoding header r = HttpResponse() r.headers["Content-Encoding"] = "winning" r.write(b"abc") r.write(b"def") self.assertEqual(r.content, b"abcdef")
def _get_bytes_written(response: HttpResponse) -> int: """ Attempts to get the bytes written, accounting for `StreamingHttpResponse` which will not be able to tell it's position. """ try: return response.tell() except OSError: return 0
def test_file_interface(self): r = HttpResponse() r.write(b"hello") self.assertEqual(r.tell(), 5) r.write("привет") self.assertEqual(r.tell(), 17) r = HttpResponse(['abc']) r.write('def') self.assertEqual(r.tell(), 6) self.assertEqual(r.content, b'abcdef') # with Content-Encoding header r = HttpResponse() r['Content-Encoding'] = 'winning' r.write(b'abc') r.write(b'def') self.assertEqual(r.content, b'abcdef')
def test_file_interface(self): r = HttpResponse() r.write(b"hello") self.assertEqual(r.tell(), 5) r.write("привет") self.assertEqual(r.tell(), 17) r = HttpResponse(["abc"]) r.write("def") self.assertEqual(r.tell(), 6) self.assertEqual(r.content, b"abcdef") # with Content-Encoding header r = HttpResponse() r["Content-Encoding"] = "winning" r.write(b"abc") r.write(b"def") self.assertEqual(r.content, b"abcdef")
def test_can_generate_a_pdf_into_a_http_response(self): # Setup issue = IssueFactory.create(journal=self.journal) article = ArticleFactory.create(issue=issue) response = HttpResponse(content_type='application/pdf') # Run & check generate_pdf( 'public/journal/article_pdf_coverpage.html', file_object=response, context={ 'article': article, 'issue': issue, 'journal': issue.journal}) self.assertTrue(isinstance(response.content, bytes)) self.assertTrue(response.tell())
def ssh_key_fingerprint(request, cred_id): # Get the credential cred = get_object_or_404(Cred, pk=cred_id) # Make sure there is an ssh_key if cred.ssh_key is None: raise Http404 fingerprint = cred.ssh_key_fingerprint() response = HttpResponse() response.write(fingerprint) response['Content-Length'] = response.tell() return response
def get_response(request): """Return information about HttpResponse object.""" a_dict = {} m_dict = {} context = {} response = HttpResponse() # Attributes: response.content = "some content" a_dict["content"] = response.content a_dict["charset"] = response.charset a_dict["status_code"] = response.status_code a_dict["reason_phrese"] = response.reason_phrase a_dict["streaming"] = response.streaming a_dict["closed"] = response.closed # Methods: m_dict["__setitem__(header, value)"] = response.__setitem__("test", "Test") m_dict["__getitem__(header)"] = response.__getitem__("test") m_dict["__delitem__(header)"] = response.__delitem__("test") m_dict["has_header(header)"] = response.has_header("test") m_dict["setdefault(headre, value)"] = response.setdefault("t", "test") m_dict["set_cookie(key, value='', max_age=None,\ expres=None, path='/', domain=None,\ secure=False, httponly=False,\ samesite=None)"] = response.set_cookie("some", "foo") m_dict["set_signed_cookie(key, value='', max_age=None,\ expres=None, path='/', domain=None,\ secure=False, httponly=False,\ samesite=None)"] = response.set_signed_cookie("foo", "foo") m_dict["delete_cookie(key, path='/', domain=None)"] =\ response.delete_cookie("foo") m_dict["close()"] = response.close() m_dict["write(content)"] = response.write("<p>CONTENT</p>") m_dict["flush()"] = response.flush() m_dict["tell()"] = response.tell() m_dict["getvalue()"] = response.getvalue() m_dict["readable()"] = response.readable() m_dict["seekable()"] = response.seekable() m_dict["writable()"] = response.writable() m_dict["writelines(lines)"] = response.writelines([" one", " two", " three"]) m_dict["lines"] = response.getvalue() context["a_dict"] = a_dict context["m_dict"] = m_dict return render(request, "response_object/response.html", context)
def export_zip(zip_path, name, delete_after=False): # Be sure that the name includes the extension .zip if not name.lower().endswith(".zip"): name += ".zip" response = HttpResponse(content_type="application/zip") response["Content-Disposition"] = 'attachment; filename="{name}"'.format(name=name) with open(zip_path, "rb") as zip_: response.write(zip_.read()) response["Content-Length"] = response.tell() if delete_after: try: os.remove(zip_path) except Exception as e: logging.exception("Error when trying to delete the file {}".format(zip_path), e) return response
def test_can_generate_a_pdf_into_a_http_response(self): # Setup issue = IssueFactory.create(journal=self.journal) article = ArticleFactory.create(issue=issue) response = HttpResponse(content_type='application/pdf') # Run & check generate_pdf('public/journal/article_pdf_coverpage.html', file_object=response, context={ 'article': article, 'issue': issue, 'journal': issue.journal }) self.assertTrue(isinstance(response.content, bytes)) self.assertTrue(response.tell())
def export_zip(zip_path, name, delete_after=False): # Be sure that the name includes the extension .zip if not name.lower().endswith('.zip'): name += '.zip' response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="{name}"'.format( name=name) with open(zip_path, 'rb') as zip_: response.write(zip_.read()) response["Content-Length"] = response.tell() if delete_after: try: os.remove(zip_path) except Exception as e: logging.exception( "Error when trying to delete the file {}".format(zip_path), e) return response
def functionality(req): """Getting the fingerprint itself""" # Get the credential cred = get_object_or_404(Cred, pk=cred_id) if not settings.LOGINLESS_SSH_FINGERPRINTS: # Check user has perms if not cred.is_visible_by(request.user): raise Http404 # Make sure there is an ssh_key if cred.ssh_key is None: raise Http404 fingerprint = cred.ssh_key_fingerprint() response = HttpResponse() response.write(fingerprint) response['Content-Length'] = response.tell() return response
def downloadattachment(request, cred_id, typ="attachment"): # Get the credential cred = get_object_or_404(Cred, pk=cred_id) # Check user has perms if not cred.is_visible_by(request.user): raise Http404 # Make sure there is an attachment if getattr(cred, typ) is None: raise Http404 # Write the audit log, as a password view CredAudit(audittype=CredAudit.CREDPASSVIEW, cred=cred, user=request.user).save() # Send the result back in a way that prevents the browser from executing it, # forces a download, and names it the same as when it was uploaded. response = HttpResponse(mimetype='application/octet-stream') response.write(getattr(cred, typ).read()) response['Content-Disposition'] = 'attachment; filename="%s"' % getattr(cred, "%s_name" % typ) response['Content-Length'] = response.tell() return response
def export_keepass(creds, password, filename='RatticExport.kdb'): db = Database() groups = {} for c in creds: # Create the group if we havent yet if c.group.name not in groups.keys(): groups[c.group.name] = db.create_group(title=c.group.name) kpg = groups[c.group.name] # Add tags list to the end of the description tags = '\n\nTags: ' for t in c.tags.all(): tags += '[' tags += t.name tags += '] ' desc = unicode(c.description) + tags # Create the entry e = kpg.create_entry( title=c.title, username=c.username, password=c.password, url=c.url, notes=desc, ) if c.attachment: e.binary_desc = c.attachment_name e.binary = c.attachment.read() # Send the response response = HttpResponse(content_type='application/x-keepass') db.save(response, password=password) response['Content-Disposition'] = 'attachment; filename=' + filename response['Content-Length'] = response.tell() return response