From f181dbf3adf8578d2a69ca31a6d8aece6f6d8ffd Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Tue, 3 Sep 2024 10:25:25 -0500 Subject: Save a species to the database. --- uploader/species/models.py | 42 ++++++++++++++++++++++++++++++++++++++++++ uploader/species/views.py | 2 +- 2 files changed, 43 insertions(+), 1 deletion(-) (limited to 'uploader/species') diff --git a/uploader/species/models.py b/uploader/species/models.py index 98337a3..bde38ce 100644 --- a/uploader/species/models.py +++ b/uploader/species/models.py @@ -1,4 +1,6 @@ """Database functions for species.""" +from typing import Optional + import MySQLdb as mdb from MySQLdb.cursors import DictCursor @@ -20,3 +22,43 @@ def species_by_id(conn: mdb.Connection, speciesid) -> dict: "FullName FROM Species WHERE SpeciesId=%s", (speciesid,)) return cursor.fetchone() + + +def save_species(conn: mdb.Connection, + common_name: str, + scientific_name: str, + taxon_id: Optional[str] = None) -> int: + """ + Save a new species to the database. + + Parameters + ---------- + conn: A connection to the MariaDB database. + taxon_id: The taxonomy identifier for the new species. + common_name: The species' common name. + scientific_name; The species' scientific name. + """ + genus, species = scientific_name.split(" ") + species = { + "common_name": common_name, + "common_name_lower": common_name.lower(), + "menu_name": f"{common_name} ({genus[0]}. {species.lower()})", + "scientific_name": scientific_name, + "taxon_id": taxon_id + } + with conn.cursor() as cursor: + cursor.execute( + "INSERT INTO Species(" + "SpeciesName, Name, MenuName, FullName, TaxonomyId" + ") VALUES (" + "%(common_name)s, %(common_name_lower)s, %(menu_name)s, " + "%(scientific_name)s, %(taxon_id)s" + ")", + species) + species_id = cursor.lastrowid + cursor.execute("UPDATE Species SET SpeciesId=%s WHERE Id=%s", + (species_id, species_id)) + return { + **species, + "species_id": species_id + } diff --git a/uploader/species/views.py b/uploader/species/views.py index 3a76494..4372504 100644 --- a/uploader/species/views.py +++ b/uploader/species/views.py @@ -48,7 +48,7 @@ def create_species(): with (database_connection(app.config["SQL_URI"]) as conn, conn.cursor() as cursor): error = False - taxon_id = request.form.get("taxon_id", "").strip() or None + taxon_id = request.form.get("species_taxonomy_id", "").strip() or None common_name = request.form.get("common_name", "").strip() if not bool(common_name): -- cgit v1.2.3