Skip to content

Commit

Permalink
Completed it
Browse files Browse the repository at this point in the history
  • Loading branch information
AkkilMG committed Oct 1, 2024
1 parent 46af2df commit 88af075
Show file tree
Hide file tree
Showing 11 changed files with 347 additions and 251 deletions.
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
# Cerificate
# Cerificate



```
------------------------------------------------------------------
Your code has been rated at 9.41/10 (previous run: 9.30/10, +0.11)
```
8 changes: 6 additions & 2 deletions config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@

from dotenv import load_dotenv
"""
This module handles the configuration settings for the Certify project.
It loads environment variables from a .env file and sets up email credentials
and template configurations.
"""
import os
from dotenv import load_dotenv

load_dotenv()

Expand Down
27 changes: 18 additions & 9 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,29 @@
# (c) 2022-2023, Akkil M G (https://github.com/HeimanPictures)
# License: GNU General Public License v3.0

"""
main.py
This module initializes the FastAPI application for the 'certify' service,
which generates and stores certificates for SOSC events.
"""

import uvicorn
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware

from config import *
import router.api_router as api_router
from router import api_router

app = FastAPI(
title="certify",
description="This is an application as a service to store certificate for SOSC Events.",
description=(
"This is an application as a service to generate and store "
"certificate for SOSC Events."
),
version="0.0.2",
contact={
"name": "Akkil M G",
"url": "http://github.com/HeimanPictures",
"url": "http://github.com/AkkilMG",
},
license_info={
"name": "GNU GENERAL PUBLIC License v3.0",
Expand All @@ -34,17 +41,19 @@
allow_headers=["*"],
)

app.get("/")
@app.get("/")
async def home():
return JSONResponse({ "success": True })
"""Return a JSON response indicating the server is running successfully."""
return JSONResponse({"success": True})

app.include_router(api_router.router, prefix="/api/v1")


if __name__ == "__main__":
try:
print('------------------- Initalizing Web Server -------------------')
print('------------------- Initializing Web Server -------------------')
print('----------------------- Service Started -----------------------')
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
except KeyboardInterrupt:
print('----------------------- Service Stopped -----------------------')
print('----------------------- Service Stopped -----------------------')

# No pointless strings should remain here
23 changes: 23 additions & 0 deletions quality.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Install required packages (make sure pip is installed)
pip install pylint black pytest pytest-cov

# If the reports directory does not exist, create it
if (!(Test-Path -Path "./reports")) {
New-Item -ItemType Directory -Path "./reports"
}

# Lint all Python files in the current directory and specific subfolders (utils and router)
pylint .\*.py .\utils\*.py .\router\*.py > ./reports/pylint_report.txt
Write-Host "Pylint report generated in reports/pylint_report.txt"

# Format all Python files in the current directory and specific subfolders (utils and router) with black (optional)
black .\*.py .\utils\*.py .\router\*.py
Write-Host "Code formatted with Black"

# Run tests with pytest (assuming your tests are in a 'tests' directory)
pytest tests > ./reports/pytest_report.txt
Write-Host "Pytest report generated in reports/pytest_report.txt"

# Check for code coverage (optional)
pytest --cov=. tests > ./reports/coverage_report.txt
Write-Host "Coverage report generated in reports/coverage_report.txt"
5 changes: 1 addition & 4 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,4 @@ uvicorn==0.20.0
# Mains
python-pptx==0.6.22
Spire.Presentation==8.9.0
Spire==0.4.2

python-pptx
fpdf
Spire==0.4.2
225 changes: 125 additions & 100 deletions router/api_router.py
Original file line number Diff line number Diff line change
@@ -1,142 +1,167 @@
# (c) 2022-2023, Akkil M G (https://github.com/HeimanPictures)
# License: GNU General Public License v3.0

"""
This module defines the API routes for certificate generation and template upload.
Routes:
/template: Handles the upload of a template file.
/generate: Generates a certificate based on a template and user information.
/generate-email: Generates an email and certificate based on a template and user details.
/generate-url: Generates a certificate based on a URL, name, and ID.
/generate-url-email: Generates an email and certificate based on a URL and user details.
"""

import requests
from fastapi import APIRouter, Request, UploadFile, File
from fastapi.responses import JSONResponse

from utils.genCert import genCertificate, genCertificateFromUrl
router = APIRouter()
from utils.gen_certificate import generate_certificate, generate_certificate_from_url

router = APIRouter()

@router.post("/template")
async def uploadTemplate(request: Request, file: UploadFile = File(...)):
async def upload_template(file: UploadFile = File(...)):
"""
Upload a template file (.pptx) to generate certificates.
params:
file: UploadFile
return:
success: bool
message: str
dl: str
Handles the upload of a template file and forwards it to an external service for processing.
Args:
file (UploadFile): The file to be uploaded.
Returns:
JSONResponse: A JSON response indicating the success or failure of the operation.
"""
try:
file_content = await file.read()
rs = requests.post("https://certify.izaries.workers.dev/certificate",
files={'file': ('certificate.pptx', file_content, 'application/vnd.openxmlformats-officedocument.presentationml.presentation')}
response = requests.post(
"https://certify.izaries.workers.dev/certificate",
files={'file': (
'certificate.pptx', file_content,
'application/vnd.openxmlformats-officedocument.presentationml.presentation'
)},
timeout=10 # Added timeout
).json()
if rs["success"]:
return JSONResponse({ "success": True, "dl": f"https://certify.izaries.workers.dev/download?id={rs['id']}&ext=pptx" })
else:
return JSONResponse({ "success": False, "message": rs["message"] })
if response["success"]:
return JSONResponse({
"success": True,
"dl": f"https://certify.izaries.workers.dev/download?id={response['id']}&ext=pptx"
})
return JSONResponse({"success": False, "message": response["message"]})
except requests.exceptions.RequestException as e:
return JSONResponse({"success": False, "message": f"Request Error: {e}"})
except ValueError as e:
return JSONResponse({"success": False, "message": f"JSON parsing error: {e}"})
except Exception as e:
return JSONResponse({ "success": False, "message": f"Error: {e}" })
return JSONResponse({"success": False, "message": f"Unexpected error: {e}"})


@router.post("/generate")
async def generateCertificate(request: Request, template: int, name: str, id: str):
async def generate_certificate_route(template: int, name: str, user_id: str):
"""
Generate a certificate using the uploaded template.
params:
template: int
name: str
id: str
return:
success: bool
message: str
dl: str
Generate a certificate based on the provided template and user information.
Args:
template (int): The template ID to be used for generating the certificate.
name (str): The name of the individual for whom the certificate is generated.
user_id (str): The ID of the individual.
Returns:
JSONResponse: A JSON response containing the success status and either the
download link or an error message.
"""
try:
value = { "name": name, "id": id }
result = genCertificate(template, value)
value = {"name": name, "id": user_id}
result = generate_certificate(template, value)
if result['success']:
return JSONResponse({ "success": True, 'dl': result['dl']})
else:
return JSONResponse({ "success": False, "message": result["message"]})
return JSONResponse({"success": True, 'dl': result['dl']})
return JSONResponse({"success": False, "message": result["message"]})
except ValueError as e:
return JSONResponse({"success": False, "message": f"Value error: {e}"})
except Exception as e:
return JSONResponse({ "success": False, "message": f"Error: {e}"})
return JSONResponse({"success": False, "message": f"Unexpected error: {e}"})


@router.post("/generate-email")
async def generateEmailNCertificate(request: Request, template: int, name: str, id: str, subject: str, body: str, email: str):
async def generate_email_and_certificate(
template: int, name: str, user_id: str, subject: str, body: str, email: str
):
"""
Generate a certificate using the uploaded template and send it to the email.
params:
template: int
name: str
id: str
subject: str
body: str
email: str
return:
success: bool
message: str
dl: str
Generates an email and certificate based on the provided template and user details.
Args:
template (int): The template ID to be used for generating the certificate.
name (str): The name of the recipient.
user_id (str): The ID of the recipient.
subject (str): The subject of the email.
body (str): The body content of the email.
email (str): The recipient's email address.
Returns:
JSONResponse: A JSON response indicating the success or failure of the operation.
"""
try:
value = { "name": name, "id": id, "body": body, "subject": subject }
result = genCertificate(template, value, email=email)
value = {"name": name, "id": user_id, "body": body, "subject": subject}
result = generate_certificate(template, value, email=email)
if result['success']:
return JSONResponse({ "success": True, 'dl': result['dl']})
else:
return JSONResponse({ "success": False, "message": result["message"]})
return JSONResponse({"success": True, 'dl': result['dl']})
return JSONResponse({"success": False, "message": result["message"]})
except ValueError as e:
return JSONResponse({"success": False, "message": f"Value error: {e}"})
except requests.exceptions.RequestException as e:
return JSONResponse({"success": False, "message": f"Request Error: {e}"})
except Exception as e:
return JSONResponse({ "success": False, "message": f"Error: {e}"})

"""
"""
return JSONResponse({"success": False, "message": f"Unexpected error: {e}"})

@router.post("/generate-url")
async def generate_certificate_from_url_route(url: str, name: str, user_id: str):
"""
Generates a certificate based on the provided URL, name, and ID.
Args:
url (str): The URL to fetch the certificate template.
name (str): The name to be included in the certificate.
user_id (str): The ID to be included in the certificate.
@router.post("/generate-url")
async def generateCertificate(request: Request, url: str, name: str, id: str):
"""
Generate a certificate using the uploaded template.
params:
template: int
name: str
id: str
return:
success: bool
message: str
dl: str
"""
# try:
value = { "name": name, "id": id }
result = genCertificateFromUrl(url, value)
Returns:
JSONResponse: A JSON response indicating the success or failure of the operation.
"""
try:
value = {"name": name, "id": user_id}
result = generate_certificate_from_url(url, value)
if result['success']:
return JSONResponse({ "success": True, 'dl': result['dl']})
else:
return JSONResponse({ "success": False, "message": result["message"]})
# except Exception as e:
# return JSONResponse({ "success": False, "message": f"Error: {e}"})

return JSONResponse({"success": True, 'dl': result['dl']})
return JSONResponse({"success": False, "message": result["message"]})
except ValueError as e:
return JSONResponse({"success": False, "message": f"Value error: {e}"})
except Exception as e:
return JSONResponse({"success": False, "message": f"Unexpected error: {e}"})


@router.post("/generate-url-email")
async def generateEmailNCertificate(request: Request, url: str, name: str, id: str, subject: str, body: str, email: str):
async def generate_email_and_certificate_from_url(
url: str, name: str, user_id: str, subject: str, body: str, email: str
):
"""
Generate a certificate using the uploaded template and send it to the email.
params:
template: int
name: str
id: str
subject: str
body: str
email: str
return:
success: bool
message: str
dl: str
Generates an email and certificate based on the provided URL and user details.
Args:
url (str): The URL to generate the certificate from.
name (str): The name of the recipient.
user_id (str): The ID of the recipient.
subject (str): The subject of the email.
body (str): The body of the email.
email (str): The email address to send the certificate to.
Returns:
JSONResponse: A JSON response indicating success or failure.
"""
try:
value = { "name": name, "id": id, "body": body, "subject": subject }
result = genCertificateFromUrl(url, value, email=email)
value = {"name": name, "id": user_id, "body": body, "subject": subject}
result = generate_certificate_from_url(url, value, email=email)
if result['success']:
return JSONResponse({ "success": True, 'dl': result['dl']})
else:
return JSONResponse({ "success": False, "message": result["message"]})
return JSONResponse({"success": True, 'dl': result['dl']})
return JSONResponse({"success": False, "message": result["message"]})
except ValueError as e:
return JSONResponse({"success": False, "message": f"Value error: {e}"})
except Exception as e:
return JSONResponse({ "success": False, "message": f"Error: {e}"})

return JSONResponse({"success": False, "message": f"Unexpected error: {e}"})
Binary file removed templates/test.pptx
Binary file not shown.
Loading

0 comments on commit 88af075

Please sign in to comment.