Skip to content

Commit

Permalink
edit: add and update Exception Handler to be more safer.
Browse files Browse the repository at this point in the history
  • Loading branch information
KyoungsueKim committed Mar 8, 2024
1 parent b84fc68 commit 9f81764
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 33 deletions.
80 changes: 48 additions & 32 deletions verbose-waffle/core/printers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import os, subprocess
import time
from typing import Optional

import PyPDF2
import requests
import random
from fastapi.exceptions import HTTPException

import urllib3
from requests import Response

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


def get_page_cnt(id: str) -> int:
Expand All @@ -14,46 +22,54 @@ def get_page_cnt(id: str) -> int:


def __print_to_file(id: str):
# Create Virtual Printer
subprocess.check_call(f'lpadmin -p {id} -v file:///root/{id}.prn -E -m CNRCUPSIRADV45453ZK.ppd'.split(' '))
processing_time: int = 0
try:
# Create Virtual Printer
subprocess.check_call(f'lpadmin -p {id} -v file:///root/{id}.prn -E -m CNRCUPSIRADV45453ZK.ppd'.split(' '))

# Print pdf file via the virtual printer
subprocess.check_call(f'lpr -P {id} -o ColorModel=KGray temp/{id}.pdf'.split(' '))
# Print pdf file via the virtual printer
subprocess.check_call(f'lpr -P {id} -o ColorModel=KGray temp/{id}.pdf'.split(' '))

# Wait until the job is done
while (True):
if "idle".encode('utf-8') in subprocess.check_output(f'lpstat -p {id}'.split(' '), timeout=180):
break
time.sleep(1)
# Wait until the job is done
while (True):
if "idle".encode('utf-8') in subprocess.check_output(f'lpstat -p {id}'.split(' '), timeout=180):
break
time.sleep(1)
processing_time += 1

# Delete printer after fileDevice print.
subprocess.check_call(f'lpadmin -x {id}'.split(' '))
# Delete printer after fileDevice print.
subprocess.check_call(f'lpadmin -x {id}'.split(' '))
print(f"[DEBUG] PDF file {id}.pdf is processed with {processing_time} seconds.")

return f"/root/{id}.prn" if os.path.isfile(f"/root/{id}.prn") else None
return f"/root/{id}.prn" if os.path.isfile(f"/root/{id}.prn") else None
except Exception as e:
raise HTTPException(status_code=500,
detail=f"Failed converting pdf files to PRN binary files. Detail: {e}")


def send_print_data(id: str):
if __print_to_file(id) is not None:
file_name = f"{id}.prn"
server = 'http://218.145.52.6:8080/spbs/upload_bin'
header = {'Content-Type': 'application/X-binary; charset=utf-8',
'User-Agent': None,
'Content-Disposition': f"attachment; filename={file_name}",
'Expect': "100-continue"}
data = open(f'/root/{file_name}', 'rb')
response = requests.post(url=server,
headers=header,
data=data)

return response

else:
return None
try:
if __print_to_file(id) is not None:
file_name = f"{id}.prn"
server = 'https://218.145.52.21:65443/spbs/upload_bin'
header = {'Content-Type': 'application/X-binary; charset=utf-8',
'User-Agent': None,
'Content-Disposition': f"attachment; filename={file_name}",
'Expect': "100-continue"}
data = open(f'/root/{file_name}', 'rb')
response: Response = requests.post(url=server,
headers=header,
data=data,
verify=False)
return response
except Exception as e:
raise HTTPException(status_code=500,
detail=f"Failed posting PRN binary data into the origin server. Response: {Optional[response].json()}. Exception: {e}")


def send_register_doc(id: str, doc_name: str, phone_number: str, cnt: int, isA3: bool = False):
file_name = f"{id}.prn"
server = 'http://u-printon.canon-bs.co.kr:62301/nologin/regist_doc/'
server = 'http://u-printon.kr.canon:62301/nologin/regist_doc/'
header = {'Content-Type': 'application/json; charset=utf-8',
'User-Agent': None,
'Content-Disposition': f"attachment; filename={file_name}",
Expand All @@ -79,8 +95,8 @@ def send_register_doc(id: str, doc_name: str, phone_number: str, cnt: int, isA3:
}
response = requests.post(url=server,
headers=header,
json=json)

json=json,
verify=False)
return response


Expand All @@ -92,4 +108,4 @@ def delete_print_data(id: str):
os.remove(f'/root/{file_name}')
os.remove(f'temp/{id}.pdf')

return
return
2 changes: 1 addition & 1 deletion verbose-waffle/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ async def receive_file(phone_number: str = Form(...), file: UploadFile = File(..
delete_print_data(uuid)

print(
f"[Print Job]: {file.filename}, page_count: {page_count}, phone_number: {phone_number}, data_result: {data_result}, register_result: {register_result}")
f"[Print Job]: {file.filename}, page_count: {page_count}, phone_number: {phone_number}, data_result: {data_result.json()}, register_result: {register_result.json()}")
return {"phone_number": phone_number, "file_name": file.filename}


Expand Down

0 comments on commit 9f81764

Please sign in to comment.