Skip to content

Alpha/task9 - Done Enigx Service #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Mar 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ APP_PORT=8000
MONGO_URL=mongodb://host:port
DB_NAME=dbname

JWT_SECRET_KEY=4ab2fcf7a6bc014396215ed36edb1c5d975c6574a2904132c03c
JWT_SECRET_KEY=jwt_secret_key
3 changes: 3 additions & 0 deletions .env.test.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
TENANT_ID=tenant_id
PROJECT_ID=project_id
BEARER_TOKEN=bearer_token
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
__pycache__
.env
.env.test
.mypy_cache
.pytest_cache
.ruff_cache
Expand Down
3 changes: 2 additions & 1 deletion app/schemas/fetch_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ class FetchDataType(StrEnum):


class FetchData(BaseModel):
name: str | None
type: FetchDataType
data: dict[str, Any] | list[Any] | str | None
data: bytes | dict[str, Any] | list[Any] | str | None


class FetchTokenType(StrEnum):
Expand Down
75 changes: 75 additions & 0 deletions app/services/enigx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import json
import mimetypes
from datetime import UTC, datetime
from http import HTTPStatus
from typing import Any

import requests
from loguru import logger
from requests import Response

from app.core.config.fetch import config as config_fetch
from app.schemas.fetch_config import FetchData, FetchDataType


class EnigxService:
def __init__(self, tenant_id: str, project_id: str, bearer_token: str) -> None:
self.tenant_id = tenant_id
self.project_id = project_id
self.bearer_token = bearer_token

def get_def_headers(self) -> dict[str, str]:
return {
"x-tenant-id": self.tenant_id,
"Authorization": f"Bearer {self.bearer_token}",
}

def put_to_knowledge(self, data: FetchData) -> None:
if data.type is FetchDataType.FILE:
if isinstance(data.data, bytes):
resp = self.put_file(data.name, data.data)
else:
msg = f"Invalid file data type: {type(data.data)}"
raise TypeError(msg)
else:
resp = self.put_text(json.dumps(data.data, default=str))

if resp.status_code == HTTPStatus.OK:
logger.debug(json.dumps(resp.json(), indent=2))
else:
msg = f"Enigx error: {resp.status_code}: {resp.text}"
raise ValueError(msg)

def put_file(self, filename: str | None, file_bytes: bytes, options: dict[str, Any] | None = None) -> Response:
filename = filename or "unknown"

mime_type, _ = mimetypes.guess_type(filename)
mime_type = mime_type or "application/octet-stream"

files = {
"file": (filename, file_bytes, mime_type),
"fileOptionsJson": (None, json.dumps(options), "application/json"),
}

return requests.post(
url=f"https://api.enigx.com/v1/projects/{self.project_id}/knowledge/file",
headers={
**self.get_def_headers(),
},
files=files, # type: ignore # noqa: PGH003
timeout=config_fetch.REQUEST_TIMEOUT,
)

def put_text(self, text: str) -> Response:
return requests.post(
url=f"https://api.enigx.com/v1/projects/{self.project_id}/knowledge/text",
headers={
**self.get_def_headers(),
"Content-Type": "application/json",
},
json={
"name": f"text_{datetime.now(tz=UTC).isoformat()}",
"text": text,
},
timeout=config_fetch.REQUEST_TIMEOUT,
)
18 changes: 16 additions & 2 deletions app/services/fetcher.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from urllib.parse import unquote

import requests

from app.core.config.fetch import config as config_fetch
Expand Down Expand Up @@ -36,17 +38,29 @@ def fetch(self) -> FetchData:
raise ValueError(msg)

resp_data = FetchData(
name=None,
type=self.config.data_type,
data=None,
)

if resp.status_code == self.config.success_code:
if self.config.data_type is FetchDataType.JSON:
resp_data.data = resp.json()

elif self.config.data_type is FetchDataType.FILE:
msg = "Not implemented for FILE type response"
raise NotImplementedError(msg)
content_disposition = resp.headers.get("Content-Disposition")
filename = "downloaded_file"
if content_disposition:
parts = content_disposition.split("filename=")
if len(parts) > 1:
filename = unquote(parts[1].strip('"'))
resp_data.name = filename
resp_data.data = resp.content

elif self.config.data_type is FetchDataType.HTML:
resp_data.data = resp.text
else:
msg = f"Fetch error: {resp.status_code}: {resp.text}"
raise ValueError(msg)

return resp_data
12 changes: 12 additions & 0 deletions test/core/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from pydantic_settings import BaseSettings, SettingsConfigDict


class Config(BaseSettings):
model_config = SettingsConfigDict(env_file=".env.test", extra="allow")

TENANT_ID: str = ""
PROJECT_ID: str = ""
BEARER_TOKEN: str = ""


config = Config()
38 changes: 38 additions & 0 deletions test/integration_test/service/test_enigx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import json
import time
from http import HTTPStatus

from loguru import logger

from app.services.enigx import EnigxService
from test.core.env import config as config_env_test


def test_enigx_put_file() -> None:
service = EnigxService(
tenant_id=config_env_test.TENANT_ID,
project_id=config_env_test.PROJECT_ID,
bearer_token=config_env_test.BEARER_TOKEN,
)
resp = service.put_file(
filename=f"test_{time.time()}.txt",
file_bytes=b"test",
options={
"description": "this is a test file upload",
},
)
logger.info(json.dumps(resp.json(), indent=2))

assert resp.status_code == HTTPStatus.OK


def test_enigx_put_text() -> None:
service = EnigxService(
tenant_id=config_env_test.TENANT_ID,
project_id=config_env_test.PROJECT_ID,
bearer_token=config_env_test.BEARER_TOKEN,
)
resp = service.put_text("this is a test text upload")
logger.info(json.dumps(resp.json(), indent=2))

assert resp.status_code == HTTPStatus.OK