I am working on creating a REACT frontend along side my FastAPI backend, right now I am…
- User
I am working on creating a REACT frontend along side my FastAPI backend, right now I am creating the skeleton UI for my Concept backend endpoints, this is the current .jsx page file:
import { Button, Drawer, theme } from "antd"; import React, { useState } from "react"; const Concepts = () => { const { token } = theme.useToken(); const [open, setOpen] = useState(false); // const [concepts, setConcepts] = useState([]); const showDrawer = () => { setOpen(true); }; const onClose = () => { setOpen(false); }; const containerStyle = { position: "relative", height: '800px', padding: 48, overflow: "hidden", textAlign: "center", background: token.colorFillAlter, border: `1px solid ${token.colorBorderSecondary}`, borderRadius: token.borderRadiusLG, }; // Render the complete component return ( <div style={containerStyle}> <div> <Button type="primary" onClick={showDrawer}> Concepts </Button> </div> <Drawer title="Concepts" placement="left" closable={false} onClose={onClose} open={open} getContainer={false} > <p>Some concepts</p> </Drawer> </div> ); }; export default Concepts;I also have an apiClient.js:
import axios from 'axios'; const API_BASE_URL = 'http://localhost:8000/api/v1'; // Update with your actual base API URL const apiClient = axios.create({ baseURL: API_BASE_URL, headers: { 'Content-Type': 'application/json', // Include any other headers here, for example, Authorization headers for JWT. }, }); const fileClient = axios.create({ baseURL: API_BASE_URL, headers: { 'Content-Type': 'image', }, }); // CONCEPT ENDPOINTS export const conceptCreate = async (name) => { return apiClient.post('/concept/create/', { name }); } export const conceptGetById = async (concept_id) => { return apiClient.get(`/concept/${concept_id}`); } export const conceptsGetPaged = async (page=0, limit=10) => { return apiClient.get('/concept/', { params: { page, limit } }); } export const conceptUpdateById = async (concept_id, name) => { return apiClient.put(`/concept/${concept_id}`, { name }); } export const conceptDeleteById = async (concept_id) => { return apiClient.delete(`/concept/${concept_id}`); }I can also share the Concept database models, to give you more insight into the idea behind the Concept:
from sqlalchemy import Column, Index, Integer, Table, String, Text, ForeignKey, DateTime, func from sqlalchemy import UniqueConstraint, CheckConstraint, MetaData from sqlalchemy.orm import Mapped, Relationship # TODO: This from sqlalchemy.orm import mapped_column from sqlalchemy.orm import relationship, declared_attr from datetime import datetime from typing import List, Optional from .base import TimeStampedModel class Concept(TimeStampedModel): """ The Concept table represents an idea or thing, in general terms. Attributes: id (int): The unique identifier of the concept. name (str): The name of the concept. created_at (DateTime): The datetime this record was created. updated_at (DateTime): The datetime this record was last updated. """ __tablename__ = "concept" # columns id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column(String(100)) # relationships concept_data_tables: Mapped[List["ConceptDataTable"]] = relationship() # methods def __repr__(self) -> str: return f"{self.__class__.__name__!r}(id={self.id!r}, name={self.name!r})" # TODO: Is this better? # return f"{self.__tablename__!r}(id={self.id!r}, name={self.name!r})" """ This links two concepts in a parent-child heirarchy. Concepts: Video Game Franchise Company Half-Life 1 Half-Life Valve This table is perfect for grouping these concepts together, like so: Video Game -> Half-Life 1 Franchise -> Half-Life Company -> Valve TODO: I suppose you COULD also do: Valve -> Half-Life -> Half-Life 1 Rather than putting them as simply ConceptRelations. The idea was for this to be a one-to-many relationship table though, rather than many-to-many. So when displaying a concept, you can display it's "parent" concept if it has one. Though I suppose when displaying concepts, you can pick and choose. For example, on the Half-Life franchise page, it can specifically target all child concepts that have the parent "Video Game". The key thing though, is you only group concepts below it if they are direct decendants. You wouldn't do: Concept[Half-Life] -> Concept[Character] But you might do: Concept[Half-Life] -> Concept[Gordon Freeman] So when getting concept lists, you simply decide the ConceptGroups that concept falls under. So for example, to get a list of all the Half-Life characters: SELECT concept_id WHERE group_concept_id = Concept[Half-Life] AND group_concept_id = Concept[Character] TODO: That won't work quite like that, you want to find where concept_id is found under both Concept[Half-Life] AND Concept[Character], I am not sure the SQL statement for achieving that. """ class ConceptGroup(TimeStampedModel): """ This represents a hierarchy of grouping Concepts together, in a parent->child relationship. Attributes: group_concept_id: The parent concept. concept_id: The child concept. created_at (DateTime): The datetime this record was created. updated_at (DateTime): The datetime this record was last updated. """ __tablename__ = "concept_group" # columns id: Mapped[int] = mapped_column(primary_key=True) group_concept_id = mapped_column(ForeignKey("concept.id")) concept_id = mapped_column(ForeignKey("concept.id")) __table_args__ = ( # PrimaryKeyConstraint("group_concept_id", "concept_id", name="pk_concept_group_id"), # I don't think I can do this UniqueConstraint("group_concept_id", "concept_id"), CheckConstraint("group_concept_id != concept_id", name="ck_group_concept_id_concept_id_no_self_ref"), ) # relationships group_concept: Mapped[Concept] = relationship(foreign_keys=[group_concept_id]) concept: Mapped[Concept] = relationship(foreign_keys=[concept_id]) # methods def __repr__(self) -> str: return f"{self.__tablename__!r}(id={self.id!r}, [{self.group_concept.name!r}->{self.concept.name}])" """ TODO: Do we still need this? If we do I will probably finish it, otherwise it can get removed. This links two concepts that are related to each other. We can link any two concepts, though this isn't a heirarchy, so avoid parent/child relationships here. Example: Heirarchy: Concept[Video Game] -> Concept[Half-Life 1] Concept[Franchise] -> Concept[Half-Life] You would link Half-Life 1 to Half-Life as a Concept Relation, but you wouldn't link the Half-Life 1 concept directly to the Video Game concept, or link the Half-Life concept to the Franchise concept, that belongs in the ConceptGroup table that forms a heirarchy. """ # class ConceptRelation(TimeStampedModel): # __tablename__ = "concept_relation" # id = Column(Integer, primary_key=True) # concept1_id = Column(ForeignKey("concept.id")) # concept2_id = Column(ForeignKey("concept.id")) # created_at = mapped_column(DateTime(timezone=True), server_default=func.now()) # updated_at = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now()) # __table_args__ = ( # UniqueConstraint("concept1_id", "concept2_id"), # ) """ VariableType is the key for all custom table metadata """ class VariableType(TimeStampedModel): """ The VariableType model represents the types of variables used by other tables, which determines how to handle the value of variables in code. Attributes: id (int): The unique identifier of the variable type. name (str): The name of the variable type. created_at (DateTime): The datetime this record was created. updated_at (DateTime): The datetime this record was last updated. """ __tablename__ = "variable_type" # columns id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column(String(30), unique=True) # methods def __repr__(self): return f"{self.__tablename__!r}(id={self.id!r}, name={self.name!r})" class HashType(TimeStampedModel): """ The HashType model represents the types of hashes used by the Hash table to help separate different types of hashes. Attributes: id (int): The unique identifier of the hash type. name (str): The name of the hash type. created_at (DateTime): The datetime this record was created. updated_at (DateTime): The datetime this record was last updated. """ __tablename__ = "hash_type" # columns id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column(String(30), unique=True) # methods def __repr__(self): return f"{self.__tablename__!r}(id={self.id!r}, name={self.name!r})" # TODO: In regard to fingerprinting, use a whitelist system for file types to fingerprint # This way we can slowly build up types to fingerprint, and mark types as volatile or not(.txt files are likely all volatile for example) class Fingerprint(TimeStampedModel): """ The Fingerprint model represents a data fingerprint, which contains a SHA512 hash of the data. Attributes: id (int): The unique identifier of the fingerprint. fingerprint (str): The SHA512 hash of the data. size (int): The size of the data in bytes. created_at (DateTime): The datetime this record was created. updated_at (DateTime): The datetime this record was last updated. files (List[File]): One-to-many relationship with File models representing the physical files associated with the fingerprint. hashes (List[Hash]): One-to-many relationship with Hash models representing the different types of hashes associated with the fingerprint. """ __tablename__ = "fingerprint" # columns id: Mapped[int] = mapped_column(primary_key=True) hash: Mapped[str] = mapped_column(String(128)) size: Mapped[int] __table_args__ = ( # Index('idx_fingerprint_hash_size', Column('hash'), Column('size'), unique=True), # Don't think I want to combine this # PrimaryKeyConstraint('hash', 'size', name='pk_fingerprint_id'), # Don't think I can do this UniqueConstraint('hash', 'size'), ) # relationships hashes: Mapped[List["Hash"]] = relationship() # methods def __repr__(self): return f"{self.__tablename__!r}(id={self.id!r}, fingerprint=[{self.hash!r}, {self.size!r}])" class Hash(TimeStampedModel): """ The Hash model represents the different types of hashes associated with a fingerprint. Attributes: id (int): The unique identifier of the hash. hash (str): The value of the hash. hash_type_id (int): The foreign key reference to the HashType model to store the type of the hash. fingerprint_id (int): The foreign key reference to the Fingerprint model to represent the relationship between the hash and its parent fingerprint. created_at (DateTime): The datetime this record was created. updated_at (DateTime): The datetime this record was last updated. hash_type (HashType): One-to-one relationship with the HashType model. fingerprint (Fingerprint): One-to-one relationship with the Fingerprint model. """ __tablename__ = "hash" # columns # TODO: This SHOULD work, to have fingerprint_id as the primary key # id = Column(Integer, primary_key=True) fingerprint_id: Mapped[int] = mapped_column(ForeignKey('fingerprint.id'), primary_key=True) hash: Mapped[str] = mapped_column(String(256)) hash_type_id = mapped_column(ForeignKey('hash_type.id')) __table_args__ = ( UniqueConstraint("fingerprint_id", "hash_type_id"), Index("idx_fp_hash_type_id", fingerprint_id, hash_type_id) ) # relationships fingerprint: Mapped[Fingerprint] = relationship(back_populates="hashes", foreign_keys=[fingerprint_id]) hash_type: Mapped[HashType] = relationship(foreign_keys=[hash_type_id]) # methods def __repr__(self): return f"{self.__tablename__!r}(id={self.id!r}, hash=[{self.hash_type.name!r}={self.hash!r}])" """ The basic idea is the fields table contains a list of columns that are in the data table. The data table contains whatever data we want to link to this concept And instead of this table having it's own id, we link directly to the concept id. TODO: We need a uniform way for different Concepts to link to different ConceptData. For example, I want an Image concept, this concept has a data table that stores information on images; widthXheight, hashes, etc. But I want the Gelbooru concepts data table to be able to reference an Image ID directly, without having to duplicate data, so I can append extra information, such as the gelbooru post ID, tags etc. So we probably want a ForeignKey VariableType. """ class ConceptDataTable(TimeStampedModel): __tablename__ = "concept_data_table" # columns # id = Column(Integer, primary_key=True) concept_id: Mapped[int] = mapped_column(ForeignKey('concept.id'), primary_key=True) data_table_name: Mapped[str] = mapped_column(unique=True) fields_table_name: Mapped[str] = mapped_column(unique=True) # relationships concept: Mapped[Concept] = relationship(foreign_keys=[concept_id], back_populates='concept_data_tables') # methods def __repr__(self): return f"{self.__tablename__!r}(concept={self.concept.name!r}, data_table_name={self.data_table_name!r}, fields_table_name={self.fields_table_name!r})" """ This does not yet contain the Fingerprints. I feel like the Data Fingerprint can itself be a Concept. It can have a Fingerprint data table containing all the fingerprints. All it needs is the fingerprint hash itself, and the data size. I do however also want support for all types of hashing. So, Concept[Hash] This concept groups all hash algorithms. Concept[Hash] \-> Concept[AUTOV1] \-> Concept[AUTOV2] \-> Concept[MD5] \-> Concept[SHA256] \-> Concept[SHA512] \-> Concept[CRC32] \-> Concept[BLAKE3] Though, how to link all the hashes to the same data... Idea 1: Instead of having VariableType TEXT, have VariableType HASH_SHA256, which gets stored as a TEXT entry in the DB, but the. No, that is too specific and I wouldn't be using those VariableTypes outside of the data table, making them useless to be a VariableType. Idea 2: A data table, indexed by Fingerprint(SHA512 hash + size) I can then have individual hash concepts, with their data tables link to the Fingerprint: id, fingerprint, hash Idea 3: Do what I did for another project, have a HashType table, then have a hash table: FK fingerprint_id, hash, hashtype_id modified to be indexed by the fingerprint_id as a foreignkey, rather than have its own id The fingerprint would then have it's own table: id, hash, size Then with the ConceptDataTable idea, I can have a Fingerprint as a VariableType, which becomes a foreign key into the fingerprint table NOTE: Additional idea, allow setting the ConceptDataTables id type, maybe have the VariableType of PrimaryKey to indicate a regular PK index, but a ForeignKey to have it be indexed by a different tables key. """ """ TABLE -> VariableType TABLE -> Concept ROW[Concept] -> Name='Gelbooru' ROW[Concept] -> Name='Booru' TABLE -> ConceptGroup # These are basically like category grouping, this is used to tie all Video Games to the Video Game concept, or all Boorus to the Booru concept, so to get a list of all video games I can check the Concept Group, also links a company like Valve to be under the Corporate Entity concept. # Each Concept can only be in one Concept Group, so the Concept must be unique, but the GroupConcept can have multiple, a ONE-TO-MANY database relationship. TABLE -> ConceptRelated # These are to link related concepts together, but rather than a parent-child relationship, even if some concepts might be "above" another, this is to simply link related concepts together, like linking "Half-Life 1" to "Valve" company, and also linking it to "Half-Life" franchise, you could also go beyond, linking it to the "First Person Shooter" genre("Genre" being another concept that contains "First Person Shooter" in it's group) ROW[ConceptGroup] -> GroupConcept='Booru', Concept='Gelbooru' #Groups Gelbooru under the Booru concept ROW[ConceptRelated] -> Concept1='Gelbooru', Concept2='Image' #Without a better example, could do this These must be freely changable, and bulk movable, in case a new concept is added and other concepts need to be re-organized. Concepts also do not need a group, or a related concept. I would like to do some auto-generated variable tables, we need some structured way to manage this within the UI, rather than having to code new python modules manually. As an example, on Gelbooru, there is images, or "posts", breaking this down into yet another Concept that only has this very specific use seems impractical, instead we bring it back to the more generic "Image" concept. For each post on Gelbooru, there is a bunch of information, the Image, ID, score, md5 hash, tags, created date, rating, source, notes, comments, has_children etc. To collect all this data, I would like it to be specific to Gelbooru, rather than collecting it generically, I mean, certain things can be more generalized, like the md5 hash, the width, the height, and the image itself. So what about the other data? Create a specific table for it! TABLE -> ImageGelbooruVariables FIELDS -> VariableTypeId, ImageId, Name, Value How do we manage this table? Another table! TABLE -> ConceptLinkingVariables FIELDS -> Concept1Id, Concept2Id, TableName Hmm, but how to link Concepts with custom tables, like the Image table? Maybe Adapt the above with an extra field? TABLE -> ConceptLinkedTable FIELDS -> ConceptId, TableName, VariableTableName ROW[ConceptLinkedTable] -> ImageConcept, Image, ImageVariables The VariableTable is a table that contains the variable fields within the Table TABLE -> ImageVariables FIELDS -> Id, VariableName(The name of the field), VariableTypeId(The datatype of the field) (The VariableTypeId would be an Id into the VariableType table, but for clarity I will use a string here): ROW[ImageVariables] -> 0, 'Id', 'INTEGER' ROW[ImageVariables] -> 1, 'ImagePath', 'TEXT' ROW[ImageVariables] -> 2, 'Width', 'INTEGER' ROW[ImageVariables] -> 3, 'Height', 'INTEGER' So what this means is we make a table like this: TABLE -> Image FIELDS -> Id(INTEGER), ImagePath(TEXT), Width(INTEGER), Height(INTEGER) """ - Assistant
- User
- Assistant
- User
It took me awhile...but the solution was obvious, I am sad you didn't pick up on it, because normally you are pointing out things I miss, but it is ok, you're still learning.
Take a look at the endpoint, specifically the response_model specified in the @router.get(), then take a look at what I am returning, I want to see if you can pick up on the issue, if not it is fine, just tell me you give up and I will tell you what the issue was.
- Assistant
Given the information and your hint, I re-examined the details you've provided, and I believe I see the discrepancy now.
In the
@router.get()decorator, you've specified that the response model is a list ofschemas.ConceptPage:@router.get("/", status_code=200, response_model=List[schemas.ConceptPage])However,
schemas.ConceptPageis already inherently a paginated object that includesitems(a list ofConceptobjects) andtotal(an integer representing the total number of items):class ConceptPage(PaginatedItems[Concept]): passBy wrapping the
schemas.ConceptPagewithin aListin the response model, you're saying that the response should be a list of these paginated objects, which is not what you seem to intend based on the implementation ofconcepts_get_paged.Instead, you should return a single instance of , which fits the structure of the JSON response you're looking to return: a single paginated response with items and a total count. The corrected route decorator should simply use without :
- User
Bravo claps for you You are correct. I missed it at first, because the Concept table is actually empty, so I started looking at what is being returned...which is an empty list, but then I considered that the special list syntax I was using would never call schemas.Concept.model_validate(row), because the list is empty, so, no elements to loop through, that was when I noticed List[] for the response_model, and I cringed.
I have been writing very similar code, which I wrote after I initially wrote these Concept endpoints, using all the same type of crud/pydantic/paged functionality, but because I wrote this before all the others, it was while I was still unsure of how to handle certain things, so when I updated it, I overlooked that... sigh
- Assistant
It happens to the best of us! This kind of issue is a common oversight, especially when refactoring or revisiting a section of code after working on similar functionality elsewhere. The good news is that through encountering these kinds of hurdles, we learn to spot potential issues more quickly in the future.
Your approach of stepping back to reconsider the expected versus the actual data is a solid debugging strategy. It's always helpful to analyze the flow of data and double-check assumptions against what the code is supposed to do.
I'm glad you were able to resolve the issue, and thank you for guiding the investigation toward the correct solution. Do reach out if you have more questions or need assistance as you continue to develop your application. Happy coding!
- User
Now that the issue is sorted, I want to go back to the REACT side, and address the whole list of concepts, I want a selectable list inside the Drawer, however what you gave me was a non-interactive list, I either want to be able to just click on the Concept to select it, or click on some kind of button beside each concept to select it, I then actually want to select it so I can view potential connecting data to the concept, for now just displaying the name is acceptable. However, as I said, the Concept table is currently empty, so I want to create a REACT button to create a new Concept, maybe use a button with another Drawer with a form to enter the Concept name and Create it, or some kind of antd Modal popup with a form to enter the name and Create.
- Assistant
- User
- Assistant
The error that you're encountering suggests that there's an issue with how the
dataSourceprop of the Ant DesignListcomponent is being handled. ThedataSourceis expected to be an array, but it looks like it's receiving a non-array or non-iterable value, likelyundefinedornull, considering the empty Concept table.To handle this situation, you should ensure that the
conceptsarray is always initialized to an empty array and not . This can usually be resolved by initializing the state properly, as follows: - User
Ok, had to fix up an issue on the FastAPI backend side, it appears to be working, and looks like creating a concept worked from the REACT frontend, however, it didn't update the Concept list, I don't necessarily want to do it every time I open the Drawer, and doing it after create is ok, but would there be any other reasonable ways to update the list without refreshing the page?
- Assistant
- User
I went with number 1 for now, just to move on, however, you raised my interest with number 4, I am not using GraphQL, I am using FastAPI, how easy would it be to adapt my FastAPI backend to allow subscribing to events?
- Assistant
- User
- Assistant
To retrieve the top-level Concepts (i.e., those that are not a child concept in the ConceptGroup table), you can leverage the SQL
NOT EXISTSclause with SQLAlchemy ORM. Here's how you could implement the function in your CRUD operations:def concepts_get_all_top_level(db: Session): # We want to find all Concepts that are not present as a `concept_id` in ConceptGroup. subquery = db.query(ConceptGroup.concept_id).subquery() top_level_concepts = db.query(Concept).filter(~Concept.id.in_(subquery)).all() return top_level_concepts - User
Nice, that was easy, looks like it is working great, since I already have endpoints for getting by group_concept_id and concept_id, I can first get the top level concepts, then go down the hierarchy with the other endpoints, and I still have the "get all" endpoints to get all the ConceptGroup entries
- Assistant
That's excellent! It sounds like you've successfully created a flexible API that allows you to query your Concept and ConceptGroup data in various ways:
- Retrieve top-level concepts to understand the broad categories or groups in your system.
- Fetch child concepts for any given parent concept to explore the hierarchy further.
- Obtain all concept group associations, which could be useful for administrative or analytical purposes.
Your API can now serve a hierarchically structured data model, supporting a variety of frontend functionality such as nested lists, tree views, or other hierarchical data presentations.
In a frontend application, you might create components that use these endpoints to display the hierarchical data and allow users to navigate through different levels of the hierarchy. With the CRUD operations you've implemented, users can manage this hierarchy by adding, updating, or deleting concepts and their relationships.
- User
Given the following REACT .jsx code:
const [concepts, setConcepts] = useState([]); const [selectedConcept, setSelectedConcept] = useState(null); const [isModalVisible, setIsModalVisible] = useState(false); const [newConceptName, setNewConceptName] = useState(""); useEffect(() => { refreshConcepts(); }, []); const showDrawer = () => { setOpen(true); }; const onClose = () => { setOpen(false); }; // Handle click on a concept list item const handleConceptClick = async (concept) => { try { const response = await conceptGetById(concept.id); setSelectedConcept(response.data); console.log(response.data); } catch (error) { console.error("Failed to get full concept:", error); } // Close the drawer setOpen(false); };What is the correct way to handle the API request in handleConceptClick?
- Assistant
The
handleConceptClickfunction in your React code appears to be set up properly to make an asynchronous API request usingawait. It's wrapped in atry...catchblock which is a good practice for handling exceptions that may occur during the API call.Here's an elaboration on how the
handleConceptClickfunction is structured correctly: - User
The structure that is returned by the API is this, this is the Pydantic schemas:
class _ConceptBase(BaseModel): name: Annotated[str, StringConstraints(max_length=100)] class ConceptCreate(_ConceptBase): class Config: from_attributes = True class Concept(_ConceptBase): id: int class Config: from_attributes = True class ConceptFull(BaseModel): concept: Concept groups_in: Optional[List[Concept]] = None grouped_under: Optional[List[Concept]] = None class Config: from_attributes = TrueRight now, on the REACT front end side, when I am displaying the selected Concept like this:
{/* Display select concept */} {selectedConcept ? ( <div>Selected Concept: {selectedConcept.concept.name}</div> ) : ( <></> )}This was always intended to be temporary, but before I was only getting the id and name, but now I am getting the surrounding relations for the selected concepts, the parent concepts are in "groups_in", essentially, the selected concept belongs to these concepts. The child concepts, "grouped_under", are what is grouped TO the selected concept, so essentially the selected concept "groups" these child concepts.
- Assistant