How to delete file in python inside docker container? - python

The code below is part of my code. In my local machine, everything is fine.However, I deploy my code and inside of docker container,it gives the error "result": "[Errno 13] Permission denied: path". What could be solution to delete in docker container also? I tried os.remove() also,It didn't work.
path = "/mypath/"
output = path + "myfile.pdf"
result_file = open(output, "w+b")
pisa_res = pisa.CreatePDF(
source_html,
dest = result_file)
result_file.close()
with open(output, "rb") as pdf_file:
encoded_string = base64.b64encode(pdf_file.read())
os.system(f"rm -rf {output}")

I don't know what is the problem with this file and how to delete it
but I would use io.BytesIO to create file in memory and then it doesn't create file on disk and it doesn't need to delete it
I don't have pisa to test it but it should be something like this
import io
result_file = io.BytesIO()
pisa_res = pisa.CreatePDF(
source_html,
dest=result_file)
result_file.seek(0) # move to the beginning of file to read it
encoded_string = base64.b64encode(result_file.read())
Module io is standard module so you don't have to install it.

Related

Update /.aws/config file on your local machine

I am trying to update the local aws/config file on my mac. I am not able to read or update any contents of the config file.
import configparser
import os
creds_dir = os.path.dirname("~/.aws/config")
config = configparser.RawConfigParser()
if not config.has_section("some"):
config.add_section("some")
# METHOD -1
config.set("some", 'aws_access_key_id', "access_key")
config.set("some", 'aws_secret_access_key', "secret_key")
config.set("some", 'aws_session_token', "token")
config.set("some", 'aws_security_token', "token")
config.write("~/.aws/config")
# METHOD -2
with open('~/.aws/credentials', 'a') as file_out:
file_out.write("[profile]")
file_out.write("aws_access_key_id = aaa")
file_out.write("aws_secret_access_key = bbb")
file_out.write("aws_session_token = cccc")
I am getting an error:
FileNotFoundError: [Errno 2] No such file or directory: '~/.aws/credentials'
I could open the file from my mac terminal and view it.
Change this to be:
creds_file = os.path.expanduser("~/.aws/config")
or
with open(os.path.expanduser("~/.aws/config"), 'a') as file_out:
The ~ expansion is part of the shell normally and so you need to expand it. expanduser returns a string that has the full path name to the file.

Creating view in browser functionality with python

I have been struggling with this problem for a while but can't seem to find a solution for it. The situation is that I need to open a file in browser and after the user closes the file the file is removed from their machine. All I have is the binary data for that file. If it matters, the binary data comes from Google Storage using the download_as_string method.
After doing some research I found that the tempfile module would suit my needs, but I can't get the tempfile to open in browser because the file only exists in memory and not on the disk. Any suggestions on how to solve this?
This is my code so far:
import tempfile
import webbrowser
# grabbing binary data earlier on
temp = tempfile.NamedTemporaryFile()
temp.name = "example.pdf"
temp.write(binary_data_obj)
temp.close()
webbrowser.open('file://' + os.path.realpath(temp.name))
When this is run, my computer gives me an error that says that the file cannot be opened since it is empty. I am on a Mac and am using Chrome if that is relevant.
You could try using a temporary directory instead:
import os
import tempfile
import webbrowser
# I used an existing pdf I had laying around as sample data
with open('c.pdf', 'rb') as fh:
data = fh.read()
# Gives a temporary directory you have write permissions to.
# The directory and files within will be deleted when the with context exits.
with tempfile.TemporaryDirectory() as temp_dir:
temp_file_path = os.path.join(temp_dir, 'example.pdf')
# write a normal file within the temp directory
with open(temp_file_path, 'wb+') as fh:
fh.write(data)
webbrowser.open('file://' + temp_file_path)
This worked for me on Mac OS.

Script can't save data to file

Based on *.blend file I have to write a script that gets informations about objects and saves them to json. This script can be opened in Blender, or running. The launch should save the json file with the data in the current directory.
So I created this:
import bpy
import json
objects = bpy.context.scene.objects
data = {}
for ob in objects:
item = {}
item['location'] = ob.location
if ob.name == 'Cube':
item['material_name'] = ob.active_material.name
data[ob.name] = item
elif ob.name == 'Camera':
item['camera_type'] = ob.data.type
data[ob.name] = item
elif ob.name == 'Lamp':
item['lamp_type'] = ob.data.type
data[ob.name] = item
with open('scene_objects.json', 'w') as json_file:
json.dump(data, json_file)
However, when I run the script in Blender, I received the following error:
PermissionError: [Errno 13] Permission denied: 'scene_objects.json'
I'm a beginner in using Blender so maybe it's impossible to write to file from Blender? However, if I can do it, I am asking for advice on how?
Your issue isn't with blender, the OS is preventing the creation (or writability) of the file based on file system permissions.
The line -
with open('scene_objects.json', 'w') as json_file:
will create a new file (or open existing) in the current working directory. When running blender that could be one of several options, depending on which OS you are using. It is also possible that starting blender from a GUI can leave you without a valid CWD, or a temporary dir that a user does not have permission to write to.
You can use os.chdir() to change the CWD to one that you know exists and that you can write to. You can also specify a full path instead of just a filename.

Encrypting many PDFs by python using PyPDF2

I am trying to make a python program which loops through all files in a folder, selects those which have extension '.pdf', and encrypt them with restricted permissions. I am using this version of PyPDF2 library:
https://github.com/vchatterji/PyPDF2. (A modification of the original PyPDF2 which also allows to set permissions). I have tested it with a single pdf file and it works fine. I want that the original pdf file should be deleted and the encrypted one should remain with the same name.
Here is my code:
import os
import PyPDF2
directory = './'
for filename in os.listdir(directory):
if filename.endswith(".pdf"):
pdfFile = open(filename, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFile)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
pdfFile.close()
os.remove(filename)
pdfWriter.encrypt('', 'ispat', perm_mask=-3904)
resultPdf = open(filename, 'wb')
pdfWriter.write(resultPdf)
resultPdf.close()
continue
else:
continue
It gives the following error:
C:\Users\manul\Desktop\ghh>python encrypter.py
Traceback (most recent call last):
File "encrypter.py", line 9, in <module>
pdfReader = PyPDF2.PdfFileReader(pdfFile)
File "C:\Users\manul\AppData\Local\Programs\Python\Python37\lib\site-packages\PyPDF2\pdf.py", line 1153, in __init__
self.read(stream)
File "C:\Users\manul\AppData\Local\Programs\Python\Python37\lib\site-packages\PyPDF2\pdf.py", line 1758, in read
stream.seek(-1, 2)
OSError: [Errno 22] Invalid argument
I have some PDFs stored in 'ghh' folder on Desktop. Any help is greatly appreciated.
Using pdfReader = PyPDF2.PdfFileReader(filename) will make the reader work, but this specific error is caused by your files being empty. You can check the file sizes with os.path.getsize(filename). Your files were probably wiped because the script deletes the original file, then creates a new file with open(filepath, "wb"), and then it terminates incorrectly due to an error that occurs with pdfWriter.write(resultPdf), leaving an empty file with the original file name.
Passing a file name instead of a file object to PdfFileReader as mentioned resolves the error that occurs with pdfWriter (I don't know why), but you'll need to replace any empty files in your directory with copies of the original pdfs to get rid of the OSError.

Python: Crossplatform code to download a valid .zip file

I have a requirement to download and unzip a file from a website. Here is the code I'm using:
#!/usr/bin/python
#geoipFolder = r'/my/folder/path/ ' #Mac/Linux folder path
geoipFolder = r'D:\my\folder\path\ ' #Windows folder path
geoipFolder = geoipFolder[:-1] #workaround for Windows escaping trailing quote
geoipName = 'GeoIPCountryWhois'
geoipURL = 'http://geolite.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip'
import urllib2
response = urllib2.urlopen(geoipURL)
f = open('%s.zip' % (geoipFolder+geoipName),"w")
f.write(repr(response.read()))
f.close()
import zipfile
zip = zipfile.ZipFile(r'%s.zip' % (geoipFolder+geoipName))
zip.extractall(r'%s' % geoipFolder)
This code works on Mac and Linux boxes, but not on Windows. There, the .zip file is written, but the script throws this error:
zipfile.BadZipfile: File is not a zip file
I can't unzip the file using Windows Explorer either. It says that:
The compressed (zipped) folder is empty.
However the file on disk is 6MB large.
Thoughts on what I'm doing wrong on Windows?
Thanks
Your zipfile is corrupt on windows because you're opening the file in write/text mode (line-terminator conversion trashes binary data):
f = open('%s.zip' % (geoipFolder+geoipName),"w")
You have to open in write/binary mode like this:
f = open('%s.zip' % (geoipFolder+geoipName),"wb")
(will still work on Linux of course)
To sum it up, a more pythonic way of doing it, using a with block (and remove repr):
with open('{}{}.zip'.format(geoipFolder,geoipName),"wb") as f:
f.write(response.read())
EDIT: no need to write a file to disk, you can use io.BytesIO, since the ZipFile object accepts a file handle as first parameter.
import io
import zipfile
with open('{}{}.zip'.format(geoipFolder,geoipName),"wb") as f:
outbuf = io.BytesIO(f.read())
zip = zipfile.ZipFile(outbuf) # pass the fake-file handle: no disk write, no temp file
zip.extractall(r'%s' % geoipFolder)

Categories

Resources