Skip to content

Commit

Permalink
Added vcf to csv functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
shivamgutgutia committed Sep 2, 2024
1 parent 94dd494 commit bfd01c9
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 2 deletions.
3 changes: 2 additions & 1 deletion controllers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
from .ping import ping
from .headers import headers
from .vcf import vcf
from .template import template
from .template import template
from .vcf2csv import vcf2csv
74 changes: 74 additions & 0 deletions controllers/vcf2csv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
from flask import request, Response
import vobject
import csv
import io


def vcf2csv():
if "file" not in request.files or not request.files["file"]:
return "No file uploaded", 400
file = request.files["file"]
if not file.filename.lower().endswith(".vcf"):
return "Invalid file type. Only VCF files are allowed", 400

vcfFile = vobject.readComponents(file.read().decode("utf-8"))
csvFile = io.StringIO()
writer = csv.writer(csvFile)
writer.writerow(
[
"Prefix",
"First Name",
"Middle Name",
"Last Name",
"Suffix",
"Phone Number",
"Email Address",
"Gender",
]
)
for entry in vcfFile:

# name
prefix, firstName, middleName, lastName, suffix = (
entry.n.value.prefix or None,
entry.n.value.given or None,
entry.n.value.additional or None,
entry.n.value.family or None,
entry.n.value.suffix or None,
)

# Extract phone numbers
phone = (
"/".join([tel.value for tel in entry.tel_list])
if hasattr(entry, "tel")
else None
)

# Extract emails
email = (
"/".join([email.value for email in entry.email_list])
if hasattr(entry, "email")
else None
)

# Extract gender (if available)
genderMap={
"M":"Male",
"F":"Female",
"U":"Unknown",
"O":"Other",
"N":"None",
None:""
}
gender = genderMap.get(entry.gender.value if hasattr(entry, "gender") else None,"")

writer.writerow(
[prefix, firstName, middleName, lastName, suffix, phone, email, gender]
)

csvFile.seek(0)
return Response(
csvFile,
mimetype='text/csv',
headers={"Content-Disposition": "attachment;filename=contacts.csv"}
)
3 changes: 2 additions & 1 deletion routers/routers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@
router.add_url_rule('/ping', 'ping', ping,methods=["GET"])
router.add_url_rule("/api/headers","headers",headers,methods=["POST"])
router.add_url_rule("/api/vcf","vcf",vcf,methods=["POST"])
router.add_url_rule("/api/template","template",template,methods=["GET"])
router.add_url_rule("/api/template","template",template,methods=["GET"])
router.add_url_rule("/api/vcf2csv", "vcf2csv", vcf2csv, methods=["POST"])

0 comments on commit bfd01c9

Please sign in to comment.