I'm trying to implement unit tests for my django rest framework project. I send protobuf files.
My code is:
def test_post(self):
files_dir = os.path.join(settings.BASE_DIR, 'api/test_files')
path = files_dir + '/test1_test2.bin'
myfile = open(path,'rb')
self.guest_client.post(
'/config?content-disposition=%20attachment%3Bfilename%3D%22test1_test2.bin%22',
data={'file': myfile, },
content_type='application/octet-stream'
)
And nothing happens. Where did I do wrong?
Related
good people,
I'm trying to implement a file download functionality. And the code is pretty straightforward:
#api.get("/summary/", response=HttpResponse)
def report_summary(
request: NinjaRequest, start_date: str, end_date: str
) -> HttpResponse:
...
response = HttpResponse(
output, # output is the file
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
response["Content-Disposition"] = f"attachment; filename={fname}" # fname is the name of the file
return response
But it gives me an error saying during bootup:
RuntimeError: no validator found for <class 'django.http.response.HttpResponse'>, see `arbitrary_types_allowed` in Config
I don't want to set arbitrary_types_allowed.
Now how can I resolve this issue?
According to: https://github.com/vitalik/django-ninja/issues/424#issuecomment-1099930539
remove this part
, response=HttpResponse)
And it actually worked
I have a restful endpoint which my rest api could make a get request to it and the file is a zip file. In this zip file, there're 2 files. I only want to read the content in 1 file from this zip archives. I was able to do a test and it likes my code stuck on line file=zipfile.ZipFile(io.BytesIO(response_object.content)).
class ZipFileResponseHandler:
def __init__(self,**args):
self.csv_file_to_index = args['csv_file_to_index']
def __call__(self, response_object, raw_response_output, response_type, req_args, endpoint):
file = zipfile.ZipFile(io.BytesIO(response_object.content))
for name in file.namelist():
if re.match(name, self.csv_file_to_index):
data =file.read(name)
print_xml_stream(repr(data))
So i found the solution to my own answer. Because I use python 2.7 the corresponding method that use to handle the response_object is StringIO not BytesIO. So the line:
file = zipfile.ZipFile(io.BytesIO(response_object.content))
should be
file = zipfile.ZipFile(StringIO.StringIO(response_object.content))
I am trying to automate the running of and downloading nessus scans using python. I have been using the nessrest api for python, and am able to successfully run a scan, but am not being successfully download the report in nessus format.
Any ideas how I can do this? I have been using the module scan_download, but that actually executes before my scan even finishes.
Thanks for the help in advance!
Just looking back at this question, heres an example of using Nessrest API to pull down CSV report exports from you nessus host,
#!/usr/bin/python2.7
import sys
import os
import io
from nessrest import ness6rest
file_format = 'csv' # options: nessus, csv, db, html
dbpasswd = ''
scan = ness6rest.Scanner(url="https://nessus:8834", login="admin", password="P#ssword123", insecure=True)
scan.action(action='scans', method='get')
folders = scan.res['folders']
scans = scan.res['scans']
if scan:
scan.action(action='scans', method='get')
folders = scan.res['folders']
scans = scan.res['scans']
for f in folders:
if not os.path.exists(f['name']):
if not f['type'] == 'trash':
os.mkdir(f['name'])
for s in scans:
scan.scan_name = s['name']
scan.scan_id = s['id']
folder_name = next(f['name'] for f in folders if f['id'] == s['folder_id'])
folder_type = next(f['type'] for f in folders if f['id'] == s['folder_id'])
# skip trash items
if folder_type == 'trash':
continue
if s['status'] == 'completed':
file_name = '%s_%s.%s' % (scan.scan_name, scan.scan_id, file_format)
file_name = file_name.replace('\\','_')
file_name = file_name.replace('/','_')
file_name = file_name.strip()
relative_path_name = folder_name + '/' + file_name
# PDF not yet supported
# python API wrapper nessrest returns the PDF as a string object instead of a byte object, making writing and correctly encoding the file a chore...
# other formats can be written out in text mode
file_modes = 'wb'
# DB is binary mode
#if args.format == "db":
# file_modes = 'wb'
with io.open(relative_path_name, file_modes) as fp:
if file_format != "db":
fp.write(scan.download_scan(export_format=file_format))
else:
fp.write(scan.download_scan(export_format=file_format, dbpasswd=dbpasswd))
can see more examples here,
https://github.com/tenable/nessrest/tree/master/scripts
I want to download files into a desired location in chrome using python selenium.however,i am not getting any idea.our framework uses mozwebqa.
how do i change the properties to download files to my desired location.
Just a sample code
#pytest.fixture()
def preparation (self, request, mozwebqa):
openyaml = open("desired txt file")
testdata = yaml.load(openyaml)
openyaml.close()
self.sample = testdata['abc']
def test_sampletest(self, mozwebqa, preparation):
homepage = basePage(mozwebqa).homepage()
homepage.login()
please help, where to set the preference for downloading files to my desired location.
Use below code :-
chromeOptions = webdriver.ChromeOptions()
prefs = {"download.default_directory" : "/some/path"}
chromeOptions.add_experimental_option("prefs",prefs)
chromedriver = "path/to/chromedriver.exe"
driver = webdriver.Chrome(executable_path=chromedriver, chrome_options=chromeOptions)
Source: https://sites.google.com/a/chromium.org/chromedriver/capabilities
I am using Python 2.7 and using google plus public API to get activity data in a file. I am encountering issues to maintain the json encoding in my file. Double quotes are coming as u'' in my file. Below is my code:
from apiclient import discovery
API_KEY = 'MY API KEY'
service = discovery.build("plus", "v1", developerKey=API_KEY)
activities_resource = service.activities()
request = activities_resource.search(query='India versus South Africa', maxResults=1, orderBy='best',)
while request!= None:
activities_document = request.execute()
if 'items' in activities_document:
with open("output.json", mode='a') as file:
data = str(activities_document['items'])
file.write(data +"\n\n")
request = service.activities().list_next(request, activities_document)
Output:
[{u'kind': u'plus#activity', u'provider': {u'title': u'Google+'}, u'titl.......
I am expecting [{"kind": "plus#activity", .....
I am running my code on windows and I have tried both on DOS and pycharm IDE. I have also run the code on ubuntu machine but same output. Please let me know what I am doing wrong.
The json module is used for generating JSON. Use it.