i wrote this python file :
from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename
from PIL import Image, ImageDraw, ImageFont
import os
import shutil
from datetime import datetime
app = Flask(name)
@app.route('/export_certificate', methods=['POST'])
def cert_export():
if 'picture' not in request.files:
return jsonify({'message': 'No picture file in the request.'}), 400
code
Assistant
if 'id' and 'location' and 'text_color' and 'name' and 'grade' and 'course_name' not in request.form:
return jsonify({'message': 'something in request form is wrong'}), 400
'''
Get Data From Request
'''
file = request.files['picture']
userID = request.form['id']
userName = remove_blanks(request.form['name'])
location = request.form['location']
text_color = request.form['text_color']
grade = request.form['grade']
courseName = remove_blanks(request.form['course_name'])
'''///////////////////////////////////////////////////////////////////////////////////////////////////////////////'''
if file.filename == '':
return jsonify({'message': 'No picture selected for uploading.'}), 400
if file and 'id' and 'name' and 'location' and 'text_color' and 'grade' and 'course_name':
'''
Creating Part of Uploading and Generating Certificate
'''
picture_name = secure_filename(file.filename)
UPLOAD_FOLDER = './certificate'
if os.path.exists(UPLOAD_FOLDER):
shutil.rmtree(UPLOAD_FOLDER)
if not os.path.exists(UPLOAD_FOLDER):
os.mkdir(UPLOAD_FOLDER)
os.chdir(UPLOAD_FOLDER)
current_time = '_'.join(str(datetime.now()).split(' '))
new_directory = f'certificate_generated_for_userid_{userID}_and_username_{userName}_in_{current_time}'
os.mkdir(new_directory)
os.chdir(f'./{new_directory}')
file.save(picture_name)
new_directory2 = f'generated_certificate'
os.mkdir(new_directory2)
os.chdir(f'./{new_directory2}')
UPLOAD_FOLDER = os.getcwd()
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
'''////////////////////////////////////////////////////////////////////////////////////////////////////////////////'''
# Open the Base certificate image
img = Image.open(os.path.join(f'{UPLOAD_FOLDER}/..', picture_name)) # Replace with your base certificate image name
# Make the image drawable
d = ImageDraw.Draw(img)
# Save all the information we are going to use
# location = (1400, 1100) # Replace with the coordinates you noted. (X, Y)
# text_color = (18, 48, 134) # Replace with the color you want the text to be
print(os.getcwd())
font = ImageFont.truetype("../../../fonts/Atop-R99O3.ttf", 150) # Replace with a font of your chosing (or remove this if you dont want to use a font). Change the number to change font size
# Insert the text to the location, with the person's name as text and fill the text in the color of our choice (and use the selected font)
d.text(str_to_tuple(location), request.form['name'], fill=str_to_tuple(text_color), font=font)
#d.text((15,150), grade, fill=(255,0,0))
# Create a unique name for the file. Feel free to edit the format, this is an example
file_name = f'{UPLOAD_FOLDER}/Course_completion_certificate_of_the_{courseName}_course_for_{userID}:{userName}_in_{grade}_grade.png'
# Save the image
img.save(file_name)
os.chdir('../../..')
return jsonify({'message': 'successfully generated'})
def str_to_tuple(text: str) -> tuple:
text = text.replace('(', '')
text = text.replace(')', '')
text = text.replace(' ', '')
text = text.split(',')
for i in range(len(text)):
text[i] = int(text[i])
return tuple(text)
def remove_blanks(text: str) -> str:
text = text.replace(' ', '_')
return text
if name == 'main':
print(remove_blanks('lksajd asdljkas lkjdlaj'))
app.run(debug=True)
and this docker compose.yml file:
version: '3.8'
services:
web:
build: .
volumes:
- .:/app # Mount local directory for development
ports:
- "8000:5000"
volumes:
certificate: # Consider removing if not needed
when i run command "docker compose up" i see this messages in terminal:
[+] Building 79.5s (13/13) FINISHED docker:default
=> [web internal] load build definition from Dockerfile 1.0s
=> => transferring dockerfile: 344B 0.0s
=> [web] resolve image config for docker-image://docker.io/docker/dockerfile:1 0.8s
=> CACHED [web] docker-image://docker.io/docker/dockerfile:1@sha256:fe40cf4e92cd0c467be2cfc30657a680ae2398318afd50b0c80585784c604f28 0.0s
=> [web internal] load metadata for docker.io/library/python:3.10-alpine 2.2s
=> [web internal] load .dockerignore 0.9s
=> => transferring context: 2B 0.0s
=> [web 1/6] FROM docker.io/library/python:3.10-alpine@sha256:27b5136cf3c1b877dee1ef2be1f9956b196072fa71b5f8d3eef58b05086ffc75 11.9s
=> => resolve docker.io/library/python:3.10-alpine@sha256:27b5136cf3c1b877dee1ef2be1f9956b196072fa71b5f8d3eef58b05086ffc75 0.9s
=> => sha256:27b5136cf3c1b877dee1ef2be1f9956b196072fa71b5f8d3eef58b05086ffc75 10.30kB / 10.30kB 0.0s
=> => sha256:fe777da3ea4af6625dec5f53a99547c45a7d90bfd5ad1af348244569fb6d2d2b 1.93kB / 1.93kB 0.0s
=> => sha256:89b2167400ba4eedcc3d8839396e2a32b61eb3ccf956f78ff2ff9b4188c6b254 6.30kB / 6.30kB 0.0s
=> => sha256:1717f0165ffa072906ac73c9e4f5e3a3dbee324bfa2f234870f1530bf97b4a5b 461.80kB / 461.80kB 1.1s
=> => sha256:c6a83fedfae6ed8a4f5f7cbb6a7b6f1c1ec3d86fea8cb9e5ba2e5e6673fde9f6 3.62MB / 3.62MB 2.3s
=> => sha256:2781bbec29c7c89632af77b943bc6138e91539bc79069532581314b11a960a4a 12.22MB / 12.22MB 4.8s
=> => sha256:7e125cf812e71195178cdd9570559dcca866561707e7eef31e45c32ee963ef78 229B / 229B 2.2s
=> => extracting sha256:c6a83fedfae6ed8a4f5f7cbb6a7b6f1c1ec3d86fea8cb9e5ba2e5e6673fde9f6 0.3s
=> => sha256:e55a234a52774b0ff8d878af7eca2d196dd013cc749ae0fe114d178758269b1f 3.08MB / 3.08MB 3.8s
=> => extracting sha256:1717f0165ffa072906ac73c9e4f5e3a3dbee324bfa2f234870f1530bf97b4a5b 0.6s
=> => extracting sha256:2781bbec29c7c89632af77b943bc6138e91539bc79069532581314b11a960a4a 0.5s
=> => extracting sha256:7e125cf812e71195178cdd9570559dcca866561707e7eef31e45c32ee963ef78 0.1s
=> => extracting sha256:e55a234a52774b0ff8d878af7eca2d196dd013cc749ae0fe114d178758269b1f 0.7s
=> [web internal] load build context 1.4s
=> => transferring context: 36.43MB 0.3s
=> [web 2/6] WORKDIR /app 2.1s
=> [web 3/6] RUN apk add --no-cache gcc musl-dev linux-headers 34.4s
=> [web 4/6] COPY requirements.txt requirements.txt 0.9s
=> [web 5/6] RUN pip install -r requirements.txt 16.0s
=> [web 6/6] COPY . . 2.1s
=> [web] exporting to image 4.0s
=> => exporting layers 3.1s
=> => writing image sha256:67523bc0291402c1889e8efb3118c8b21c86d5d5c0720208a928d1c1c74aad2f 0.1s
=> => naming to docker.io/library/certificator-web 0.2s
[+] Running 2/2
✔ Network certificator_default Created 0.3s
✔ Container certificator-web-1 Created 1.5s
Attaching to web-1
web-1 | lksajd_asdljkas_lkjdlaj
web-1 | * Serving Flask app 'cert_app'
web-1 | * Debug mode: on
web-1 | WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
web-1 | * Running on http://127.0.0.1:5000
web-1 | Press CTRL+C to quit
web-1 | * Restarting with stat
web-1 | * Debugger is active!
web-1 | * Debugger PIN: 623-824-718
but when i send request with postman i get error like this :
Error: write EPIPE
Request Headers
User-Agent: PostmanRuntime/7.40.0
Accept: /
Postman-Token: 1daa1f7b-76d9-475a-9ae1-2177dda3df8f
Host: 127.0.0.1:8000
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
please fix this for me
There are a few issues with your code and Docker setup that are causing the error you're seeing:
Error Handling: In your cert_export function, you're not handling any potential errors that might occur when processing the request or generating the certificate. This can lead to unexpected behavior and errors.
File Path: In your cert_export function, you're using relative paths to access the certificate and font files. This can cause issues if the directory structure of your container is different from your local machine. It's better to use absolute paths or to mount the directory containing these files into the container.
Font Path: You're using a font file located at ../../../fonts/Atop-R99O3.ttf. This path is relative to the current working directory of your container's process, which is not guaranteed to be the same as the directory containing your Flask app. You should either use an absolute path or mount the directory containing this font file into the container.
Image Processing: When generating the certificate, you're opening the image file using Image.open. If this file does not exist or cannot be opened for some reason, this will raise an error. You should add some error handling to deal with this situation.
Flask App Run: When running the Flask app using app.run(debug=True), it's bound to http://127.0.0.1:5000. Since you're trying to access it through http://127.0.0.1:8000 in Postman, this won't work. You should either change the host of your Flask app to 0.0.0.0 or to the correct IP address of your container.
Here's an updated version of your code and Docker setup with these issues addressed:
cert_app.py:
python
from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename
from PIL import Image, ImageDraw, ImageFont
import os
import shutil
from datetime import datetime
app = Flask(__name__)
@app.route('/export_certificate', methods=['POST'])
def cert_export():
try:
if 'picture' not in request.files:
return jsonify({'message': 'No picture file in the request.'}), 400
if 'id' and 'location' and 'text_color' and 'name' and 'grade' and 'course_name' not in request.form:
return jsonify({'message': 'something in request form is wrong'}), 400
file = request.files['picture']
userID = request.form['id']
userName = remove_blanks(request.form['name'])
location = request.form['location']
text_color = request.form['text_color']
grade = request.form['grade']
courseName = remove_blanks(request.form['course_name'])
if file.filename == '':
return jsonify({'message': 'No picture selected for uploading.'}), 400
if file and 'id' and 'name' and 'location' and 'text_color' and 'grade' and 'course_name':
picture_name = secure_filename(file.filename)
UPLOAD_FOLDER = './certificate'
if os.path.exists(UPLOAD_FOLDER):
shutil.rmtree(UPLOAD_FOLDER)
if not os.path.exists(UPLOAD_FOLDER):
os.mkdir(UPLOAD_FOLDER)
current_time = '_'.join(str(datetime.now()).split(' '))
new_directory = f'certificate_generated_for_userid_{userID}_and_username_{userName}_in_{current_time}'
os.mkdir(new_directory)
os.chdir(f'{UPLOAD_FOLDER}/{new_directory}')
file.save(picture_name)
new_directory2 = f'generated_certificate'
os.mkdir(new_directory2)
os.chdir(f'{UPLOAD_FOLDER}/{new_directory}/{new_directory2}')
try:
img = Image.open(os.path.join(os.getcwd(), picture_name))
d = ImageDraw.Draw(img)
font = ImageFont.truetype("/app/fonts/Atop-R99O3.ttf", 150)
d.text(str_to_tuple(location), request.form['name'], fill=str_to_tuple(text_color), font=font)
file_name = f'{UPLOAD_FOLDER}/{new_directory}/{new_directory2}/generated_certificate.png'
img.save(file_name)
return jsonify({'message': 'successfully generated'})
except Exception as e:
return jsonify({'message': str(e)}), 500
except Exception as e:
return jsonify({'message': str(e)}), 500
def str_to_tuple(text: str) -> tuple:
text = text.replace('(', '')
text = text.replace(')', '')
text = text.replace(' ', '')
text = text.split(',')
for i in range(len(text)):
text[i] = int(text[i])
return tuple(text)
def remove_blanks(text: str) -> str:
text = text.replace(' ', '_')
return text
if __name__ == '__main__':
print(remove_blanks('lksajd asdljkas lkjdlaj'))
app.run(host='0.0.0.0', port=5000, debug=True)
Dockerfile:
dockerfile
# syntax=docker/dockerfile:1
FROM python:3.10-alpine
WORKDIR /app
ENV FLASK_APP=./src/cert_app.py
ENV FLASK_RUN_HOST=0.0.0.0
RUN apk add --no-cache gcc musl-dev linux-headers
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
RUN mkdir -p /app/fonts
COPY fonts /app/fonts/
EXPOSE 5000
CMD ["python", "src/cert_app.py"]