Introduced TagCategory, bugfixes

Fixed several bugs from previous commits (Bad distribution of changes across multiple commits).
Introduced striping of string fields before send back as replies in main.py.
Implemented POST and DELETE calls for /artnet/metadata/category
Implemented tests for the new calls.
master
Peery 3 years ago
parent 25c18651e4
commit 9fe017a6e3

@ -39,12 +39,15 @@ class Presence(BaseModel):
orm_mode = True
class ArtnoID(BaseModel):
hash: Optional[str]
path: Optional[str]
title: Optional[str] = None
link: Optional[str] = None
presences: Optional[List[Presence]]
class TagCategorynoID(BaseModel):
name: str
class Config:
orm_mode = True
class TagCategory(TagCategorynoID):
category_id: int
class Config:
orm_mode = True

@ -4,7 +4,8 @@ import uvicorn
from typing import List, Tuple
from database.database import Database
from database.models import Art, ArtnoID, Presence, ArtistNoId
from database.database import DBPresence, DBArt2Presence
from database.models import Art, ArtnoID, Presence, ArtistNoId, TagnoID, TagCategory, TagCategorynoID
app = FastAPI()
db = Database()
@ -23,7 +24,7 @@ async def art(id: int = None, hash: str = None, tag_id: int = None):
elif tag_id is not None:
result = db.get_tag_art(tag_id)
if id is None and hash is None and tag_id is None: # TODO fix against listing enormous amounts of art (because all could be large)
if id is None and hash is None and tag_id is None: # TODO fix against listing enormous amounts of art (because "all" could be large)
result = db.get_art_list()
if result is not None:
@ -111,6 +112,17 @@ async def presence(name: str = None, domain: str = None, artist_id: int = None,
#raise HTTPException(status_code=406, detail="You must query with at least one parameter!")
if result is not None:
if isinstance(result, list):
for i in range(len(result)):
if isinstance(result[i], DBPresence):
result[i].name = result[i].name.strip()
result[i].domain = result[i].domain.strip()
elif isinstance(result[i], DBArt2Presence):
result[i].presence_name = result[i].presence_name.strip()
result[i].presence_domain = result[i].presence_domain.strip()
else:
result.name = result.name.strip()
result.domain = result.domain.strip()
return result
raise HTTPException(status_code=404, detail="Presence was not found!")
@ -199,6 +211,11 @@ async def topic(name: str = None, id: int = None, artist_id: int = None):
result = db.get_artist_topics(artist_id)
if result is not None:
if isinstance(result, list):
for i in range(len(result)):
result[i].name = result[i].name.strip()
else:
result.name = result.name.strip()
return result
raise HTTPException(status_code=404, detail="Topic was not found!")
@ -226,10 +243,20 @@ async def tag(id: int = None, name: str = None, fuzzy: bool = False, category: i
result = db.get_category_tags(category)
if result is not None:
if isinstance(result, list):
for i in range(len(result)):
result[i].name = result[i].name.strip()
else:
result.name = result.name.strip()
return result
raise HTTPException(status_code=404, detail="Tag was not found!")
@app.post("/artnet/metadata/tag")
async def tag(tag: TagnoID, id: int = None):
print(f"Received POST on /artnet/metadata/tag (id={id}) body: tag={tag}")
@app.get("/artnet/metadata/category")
async def category(name: str = None, id: int = None):
name = unquote(name) if name is not None else None
@ -245,9 +272,36 @@ async def category(name: str = None, id: int = None):
result = db.get_category_by_name(name)
if result is not None:
result.name = result.name.strip()
return result
raise HTTPException(status_code=404, detail="Category not found!")
@app.post("/artnet/metadata/category")
async def category(category: TagCategorynoID, id: int = None):
print(f"Received GET on /artnet/metadata/category (id={id}, body: {category})")
if id is None: # create new name
try:
new_id = db.create_category_by_model(category).category_id
return {"id": new_id}
except ValueError as e:
raise HTTPException(status_code=422, detail=str(e))
else:
updated_category = TagCategory(category_id=id, name=category.name)
db.update_category_by_model(updated_category)
return True
@app.delete("/artnet/metadata/category")
def category(id: int):
print(f"Received DELETE on /artnet/metadata/category (id={id})")
try:
db.delete_category_by_id(category_id=id)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8000)

@ -0,0 +1,133 @@
import requests
from urllib.parse import quote
import json
from typing import List, Tuple
test_tag_category_entries = [{"name": "category_name1", "id": None},
{"name": "category_name2", "id": None},
{"name": "category_name3", "id": None}]
def list_tag_categories(url: str, port: int):
"""
Return a list of all tag categories
:param url:
:param port:
:return:
"""
r = requests.get(f"http://{url}:{port}/artnet/metadata/category")
if r.status_code != 200:
raise Exception("Failed querying for tag category!")
categories = json.loads(r.text)
return categories
def get_category_by_ID(url: str, port: int, category_id: id):
r = requests.get(f"http://{url}:{port}/artnet/metadata/category?id={category_id}")
if r.status_code != 200:
raise Exception("Failed querying for tag category!")
return json.loads(r.text)
def create_tag_categories(url: str, port: int):
"""
Create many tag categories for testing purposes
:param url:
:param port:
:return:
"""
for i in range(len(test_tag_category_entries)):
r = create_tag_category(url, port, name=test_tag_category_entries[i]["name"])
if r.status_code != 200:
print(f"Create Category Entry Test Nr.{i}: failed with {r.status_code} and reason {r.text}")
raise Exception("Create Category Entry Test: FAILED")
else:
test_tag_category_entries[i]["id"] = int(json.loads(r.text)["id"])
def update_category_entries(url: str, port: int):
for i in range(len(test_tag_category_entries)):
update_tag_category(url, port, category_id=test_tag_category_entries[i]["id"], name=f"Category #{i}")
updated_category = get_category_by_ID(url, port, test_tag_category_entries[i]["id"])
if updated_category['name'] != f"Category #{i}":
raise Exception("Updating the category name failed!")
def delete_category_entries(url: str, port: int):
categories = list_tag_categories(url, port)
for i in range(len(categories)):
if "category_id" in categories[i].keys():
r = delete_tag_category(url, port, category_id=categories[i]["category_id"])
else:
r = delete_tag_category_by_name(url, port, name=categories[i]["name"])
if r.status_code != 200:
raise Exception(f"Could not delete tag category! {r.status_code}, {r.text}")
print("Deleted category entries: SUCCESS")
def create_tag_category(url: str, port: int, name: str):
r = requests.post(f"http://{url}:{port}/artnet/metadata/category",
json={"name": name})
return r
def update_tag_category(url: str, port: int, name: str, category_id: int):
r = requests.post(f"http://{url}:{port}/artnet/metadata/category?id={quote(str(category_id))}",
json={"name": name})
return r
def delete_tag_category(url: str, port: int, category_id: int):
r = requests.delete(f"http://{url}:{port}/artnet/metadata/category?id={quote(str(category_id))}")
return r
def delete_tag_category_by_name(url: str, port: int, name: str):
r1 = requests.get(f"http://{url}:{port}/artnet/metadata/category?name={quote(name.strip())}")
if r1.status_code != 200:
raise ValueError("Could not delete tag category because it could not be found!")
data = json.loads(str(r1.text))
category_id = data['category_id']
r = delete_tag_category(url, port, category_id=category_id)
return r
def run_tag_category_test(url: str, port: int):
print()
print("----------------")
categories = list_tag_categories(url, port)
print(f"Starting tag name test with {len(categories)} categories!")
print("Starting the category test ...")
if len(list_tag_categories(url, port)) > 0:
print("Deleting previous category entries of tests ...")
delete_category_entries(url, port)
print(f"Creating {len(test_tag_category_entries)} category entries ...")
create_tag_categories(url, port)
create_tag_result = False if not len(list_tag_categories(url, port)) == len(test_tag_category_entries) else True
print(f"Found {len(list_tag_categories(url, port))} category entries!")
if not create_tag_result:
print(f"Failure! Unexpected number of category entries!")
print("Updating category entries with new data ...")
update_category_entries(url, port)
update_category_result = True
print("TODO")
print(f"Found {len(list_tag_categories(url, port))} category entries!")
print("Deleting all category entries ...")
delete_category_entries(url, port)
delete_category_result = False if not len(list_tag_categories(url, port)) == 0 else True
print(f"Found {len(list_tag_categories(url, port))} category entries!")
print("Category test complete!")
return create_tag_result, update_category_result, delete_category_result
Loading…
Cancel
Save