User info widgets

This commit is contained in:
2024-08-09 22:50:20 +03:00
parent cb3b5a3c27
commit b0f20680b4
4 changed files with 162 additions and 13 deletions
+97
View File
@@ -0,0 +1,97 @@
from __future__ import annotations
import pydantic
import state
from PyQt6.QtWidgets import (
QWidget,
QLineEdit,
QLabel,
QVBoxLayout,
QPushButton,
QHBoxLayout,
QMessageBox,
)
from request_client import RequestClient
class User(pydantic.BaseModel):
user_id: int | None = None
username: str
email: str
@staticmethod
def get(user_id: int | None = None) -> User:
params = {}
if user_id:
url = "/users"
params["user_id"] = user_id
else:
url = "/users/current"
return User.model_validate_json(
RequestClient().client.get(url, params=params).text
)
@staticmethod
def delete():
if not RequestClient().client.delete("/users").is_success:
raise Exception("Error deleting user")
def put(self):
response = RequestClient().client.put(
"/users", json={"username": self.username, "email": self.email}
)
if not response.is_success:
QMessageBox.warning(None, "Error updating user", response.text)
return
QMessageBox.information(None, "User updated", "User updated")
class UserSearch(User):
similarity: float
@staticmethod
def search(search_str: str) -> list[UserSearch]:
return pydantic.TypeAdapter(list[UserSearch]).validate_json(
RequestClient()
.client.get("/users/search", params={"search_string": search_str})
.text
)
class UserWidget(QWidget):
def __init__(self, state: state.State):
super().__init__()
self.state = state
self.setWindowTitle("User information")
self.user = User.get()
main_layout = QVBoxLayout()
lines = [("username", self.user.username), ("email", self.user.email)]
edits = []
for line in lines:
layout = QHBoxLayout()
label = QLabel(line[0])
edit = QLineEdit(line[1])
layout.addWidget(label)
layout.addWidget(edit)
main_layout.addLayout(layout)
edits.append(edit)
self.username: QLineEdit = edits[0]
self.email: QLineEdit = edits[1]
button_layout = QHBoxLayout()
buttons = [("Update", self.update_user), ("Delete", self.delete_user)]
for text, func in buttons:
button = QPushButton(text)
button.clicked.connect(func)
button_layout.addWidget(button)
main_layout.addLayout(button_layout)
self.setLayout(main_layout)
def delete_user(self):
User.delete()
self.close()
self.state.logout()
def update_user(self):
self.user.username = self.username.text()
self.user.email = self.email.text()
self.user.put()