0

I have passed watermarked pdf to encrypt() function. From encrypt() function, I want to pass the pdf to another function called emel() which is sending the email to receiver.

Watermarked coding:

@app.route('/upload_file', methods=['POST'])
def upload_file():

pdf_file = request.files['file']
watermark = "watermark.pdf"
merged_file = "merged.pdf"

input_pdf = PyPDF2.PdfFileReader(pdf_file)

watermark_file = open(watermark,'rb')
watermark_pdf = PyPDF2.PdfFileReader(watermark_file)

pdf_page = input_pdf.getPage(0)

watermark_page = watermark_pdf.getPage(0)

pdf_page.mergePage(watermark_page)

output = PyPDF2.PdfFileWriter()

output.addPage(pdf_page)

merged_file = open(merged_file,'wb')
output.write(merged_file)

merged_file.close()
watermark_file.close()
pdf_file.close()

return redirect(url_for("encrypt", file="merged.pdf"))

encrypt() function:

@app.route("/<file>")
def encrypt(file):

key = Fernet.generate_key()

file1 = open('key.key', 'wb')
file1.write(key)
file1.close()

file2 = open('key.key', 'rb')
key = file2.read()
file2.close()

# with open ('mykey.key', 'wb') as mykey:
#     mykey.write(key)  

# with open('mykey.key', 'rb') as mykey:
#     key = mykey.read()

# print(key)

with open(str(file), 'rb') as original_file:
    original = original_file.read()

f = Fernet(key)
encrypted = f.encrypt(original)

with open('test1.pdf', 'wb') as encrypted_file:
    encrypted_file.write(encrypted)

f = Fernet(key)

with open('test1.pdf', 'rb') as encrypted_file:
    encrypted = encrypted_file.read()

decrypted = f.decrypt(encrypted)

with open('test2.pdf', 'wb') as decrypted_file:
    decrypted_file.write(decrypted)

return redirect(url_for("emel", final_file=decrypted_file))

Ive managed to successfully transfer the pdf from upload_file() to encrypt(). Now i want to transfer from encrypt() to emel().

emel():

@app.route("/<final_file>")
def emel(final_file):

email_user = "email@gmail.com"
email_send = "email@gmail.com"
subject = 'Python!'

msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject

body = 'Hi there, sending this email from Python!'
msg.attach(MIMEText(body, 'plain'))

filename = final_file
attachment = open(filename,'rb')

part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= "+filename)

msg.attach(part)

text = msg.as_string()

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email_user, "password")

server.sendmail(email_user, email_send, text)
server.quit()

return "Success send email"

traceback:

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 2088, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 2073, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 2070, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 1515, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 1513, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 1499, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "C:\Users\User\Desktop\abc\test.py", line 103, in encrypt
    with open(str(file), 'rb') as original_file:
OSError: [Errno 22] Invalid argument: "<_io.BufferedWriter name='test2.pdf'>"

Please help. Thank you

Edit. Found the solution

should be /upload_file/<file> not just <file>

  • well to me it seems that it is either the mode: `'rb'` that should be changed or You have to see what `file` is, for example print it out, this seemed related but also talked only about file path: https://stackoverflow.com/questions/25584124/oserror-errno-22-invalid-argument-when-use-open-in-python – Matiiss Jul 18 '21 at 23:14
  • @Matiiss in encrypt() function, i think should i change at `decrypted_file` in `final_file=decrypted_file`. – Aiman Syafiq Jul 19 '21 at 04:35
  • @Matiiss but i cant seem to find what i should change it into – Aiman Syafiq Jul 19 '21 at 07:50
  • did You print what is `file` before using the context manager? like place a `print(file)` at the start of Your function and tell me what it is – Matiiss Jul 19 '21 at 09:56
  • @Matiiss im sorry i dont get it. for as long as i know, `file` is in pdf format. i just did what you ask me to do and i get the same error. File `"C:\Users\User\Desktop\abc\test.py", line 105, in encrypt with open(str(file), 'rb') as original_file: OSError: [Errno 22] Invalid argument: "<_io.BufferedWriter name='test2.pdf'>"` – Aiman Syafiq Jul 19 '21 at 10:56
  • ok, so if You did what I ask then You should know what `file` is, right? so could You tell me what is `file`, what does that variable represent? – Matiiss Jul 19 '21 at 10:59
  • @Matiiss i think i understand. you want to know what does `file` represent right? `file` represent `"merged.pdf"` from `upload_file()`. the file that have been watermarked – Aiman Syafiq Jul 19 '21 at 11:06
  • do You have a file named `"merged.pdf"` in the same directory as Your `routes` file? because if You try opening it like You, it looks for the file in the same directory as the script – Matiiss Jul 19 '21 at 11:13
  • yes, it is in the same directory – Aiman Syafiq Jul 19 '21 at 11:21
  • ok, finally I understood what the error message was saying, basically it was saying that `str(file)` is `"<_io.BufferedWriter name='test2.pdf'>"`, that is why I asked You to print out what is `file` because from this error it seems like this is True: `file == "<_io.BufferedWriter name='test2.pdf'>"` when it should be `file = 'merged.pdf'` – Matiiss Jul 19 '21 at 11:40
  • @Matiiss ive declared it at `upload_file()` function : `redirect(url_for("encrypt", file="merged.pdf"))`. i use `test2.pdf` in another function. should i declared a new `file='merged.pdf'` in `encrypt()`. im sorry that i am clueless now – Aiman Syafiq Jul 19 '21 at 12:46
  • I know that You declared it but apparently when it comes to `print(str(file))` it should print out this: `<_io.BufferedWriter name='test2.pdf'>` – Matiiss Jul 19 '21 at 12:57
  • @Matiiss I run print(file) and it print out this `127.0.0.1 - - [19/Jul/2021 21:04:16] "GET /merged.pdf HTTP/1.1" 302 - <_io.BufferedWriter name='test2.pdf'>` – Aiman Syafiq Jul 19 '21 at 13:05
  • do You see how that is an issue now? clearly there is no such path, it is also a bit weird that You got that as `file`, maybe specify that it is a string like this: `` – Matiiss Jul 19 '21 at 13:13
  • @Matiiss im sorry i dont get it. Where should i change the coding? – Aiman Syafiq Jul 19 '21 at 13:20
  • in the encrypt route where You have `/` add this: `/` – Matiiss Jul 19 '21 at 13:31
  • @Matiiss Ive changed it to `/`. unfortunately i still get the same error. ` File "C:\Users\User\Desktop\abc\test.py", line 104, in encrypt with open(str(file), 'rb') as original_file: OSError: [Errno 22] Invalid argument: "<_io.BufferedWriter name='test2.pdf'>"` – Aiman Syafiq Jul 19 '21 at 13:45
  • ok, I will try to explain the error then, maybe You get some ideas. basically it is saying that You have provided an argument ("<_io.BufferedWriter name='test2.pdf'>") to the function `open()` but this argument is invalid (which makes sense since that string is not a file to be opened/not a file name/invalid file name), what You could try tho is try `with open(file.name, 'rn') as original_file:` so that You can extract that name variable from there, maybe that works – Matiiss Jul 19 '21 at 13:48
  • @Matiiss im very sorry i asked a lot of question. i tried `with open(file.name, 'rb') as original_file:`. now, i got a new error `File "C:\Users\User\Desktop\abc\test.py", line 104, in encrypt with open(file.name, 'rb') as original_file: AttributeError: 'str' object has no attribute 'name'` – Aiman Syafiq Jul 19 '21 at 14:17
  • Oh, kinda my mistake, remove that `string:` part from here: `/` so it looks like so: `/` maybe that then works – Matiiss Jul 19 '21 at 14:40
  • @Matiiss i still get the same error. its like this, if i changed `return redirect(url_for("emel", final_file=decrypted_file))` to something like `return "Success"` in `encrypt()`, i can get the return `"Success"`. in `encrypt()` function, my final product should be `test2.pdf` itself. i want to pass `test2.pdf` to `emel()` function – Aiman Syafiq Jul 19 '21 at 14:55
  • actually I just thougth about sth, both of those routes are almost identical except for their variable names, which may cause other issues tho probably not if You use `url_for`, I honestly don't even know what is the issue anymore, so I can't help too much, I just recently started flask so I still gotta learn stuff but... yeah, well good luck – Matiiss Jul 19 '21 at 15:00
  • @Matiiss ive found the solution. i just change the route from `/` into `/`. it works. thank you for taking your time helping me – Aiman Syafiq Jul 20 '21 at 07:20
  • did You mistype or is it actually meant to be: `/` and not `/upload_file/`, either how, nice that You found the solution. actually now looking at that makes sense since You had all routes basically identical and flask wouldn't be able to identify which route You want but then again is that an issue if You use `url_for` and just call the function? anyhow, if You don't mind, then I would suggest that You write an answer and post it here so that people in the future would know what to do in a similar situation, either how, have a nice day – Matiiss Jul 20 '21 at 09:42
  • @Matiiss sorry my bad. `/upload_file/` is the correct answer – Aiman Syafiq Jul 20 '21 at 16:31

0 Answers0