Download app/api/v1/datasources.py from isold/meloon: direct link, hf CLI and curl.
- Browser
- Download file 6.33 kB
-
https://huggingface.co/spaces/isold/meloon/resolve/main/app/api/v1/datasources.py
- Command line
-
hf download hf://spaces/isold/meloon/app/api/v1/datasources.py
-
curl -L -o datasources.py https://huggingface.co/spaces/isold/meloon/resolve/main/app/api/v1/datasources.py
6.33 kB
| from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File, Form | |
| from sqlalchemy.orm import Session | |
| from typing import List, Optional | |
| import os | |
| import shutil | |
| import uuid | |
| from app.api import deps | |
| from app.models.models import DataSource, User, DataSourceType, FileStatus | |
| from app.schemas import schemas | |
| router = APIRouter() | |
| UPLOAD_DIR = "uploads" | |
| os.makedirs(UPLOAD_DIR, exist_ok=True) | |
| def read_data_sources( | |
| db: Session = Depends(deps.get_db), | |
| current_user: User = Depends(deps.get_current_user), | |
| skip: int = 0, | |
| limit: int = 100, | |
| ): | |
| data_sources = db.query(DataSource).filter(DataSource.user_id == current_user.id).offset(skip).limit(limit).all() | |
| return data_sources | |
| def create_data_source( | |
| data_source_in: schemas.DataSourceCreate, | |
| db: Session = Depends(deps.get_db), | |
| current_user: User = Depends(deps.get_current_user), | |
| ): | |
| ds = DataSource( | |
| **data_source_in.model_dump(), | |
| user_id=current_user.id | |
| ) | |
| db.add(ds) | |
| db.commit() | |
| db.refresh(ds) | |
| return ds | |
| def upload_data_source( | |
| file: UploadFile = File(...), | |
| name: Optional[str] = Form(None), | |
| db: Session = Depends(deps.get_db), | |
| current_user: User = Depends(deps.get_current_user), | |
| ): | |
| if not name: | |
| name = file.filename | |
| # Determine type | |
| ext = file.filename.split('.')[-1].lower() | |
| if ext in ['xls', 'xlsx']: | |
| ds_type = DataSourceType.excel | |
| elif ext == 'csv': | |
| ds_type = DataSourceType.csv | |
| else: | |
| raise HTTPException(status_code=400, detail="Unsupported file type") | |
| # Save file | |
| file_id = str(uuid.uuid4()) | |
| file_path = os.path.join(UPLOAD_DIR, f"{file_id}_{file.filename}") | |
| with open(file_path, "wb") as buffer: | |
| shutil.copyfileobj(file.file, buffer) | |
| ds = DataSource( | |
| name=name, | |
| type=ds_type, | |
| file_path=file_path, | |
| file_status=FileStatus.completed, | |
| user_id=current_user.id | |
| ) | |
| db.add(ds) | |
| db.commit() | |
| db.refresh(ds) | |
| return ds | |
| def test_connection_params( | |
| data_source_in: schemas.DataSourceCreate, | |
| current_user: User = Depends(deps.get_current_user), | |
| ): | |
| """Test connection parameters without saving to database""" | |
| print(f"[DEBUG] Received test connection request: {data_source_in}") | |
| print(f"[DEBUG] Type: {data_source_in.type}, Host: {data_source_in.host}, Username: {data_source_in.username}") | |
| if data_source_in.type in [DataSourceType.mysql, DataSourceType.postgresql, DataSourceType.clickhouse]: | |
| # Validate required fields - password is optional for testing | |
| if not data_source_in.host or not data_source_in.username: | |
| print(f"[DEBUG] Missing connection details - Host: {data_source_in.host}, Username: {data_source_in.username}") | |
| raise HTTPException(status_code=400, detail="Missing host or username") | |
| # Here you would implement actual connection test logic | |
| # For now, simulate success if basic fields are present | |
| try: | |
| # TODO: Implement actual database connection test | |
| # import pymysql or psycopg2 and test connection | |
| print("[DEBUG] Connection test passed") | |
| return {"status": "ok"} | |
| except Exception as e: | |
| print(f"[DEBUG] Connection test failed: {str(e)}") | |
| raise HTTPException(status_code=400, detail=f"Connection failed: {str(e)}") | |
| print("[DEBUG] Non-DB type, returning ok") | |
| return {"status": "ok"} | |
| def test_connection( | |
| id: int, | |
| db: Session = Depends(deps.get_db), | |
| current_user: User = Depends(deps.get_current_user), | |
| ): | |
| ds = db.query(DataSource).filter(DataSource.id == id, DataSource.user_id == current_user.id).first() | |
| if not ds: | |
| raise HTTPException(status_code=404, detail="Data source not found") | |
| if ds.type in [DataSourceType.mysql, DataSourceType.postgresql]: | |
| # Implement actual connection test logic here | |
| # For now, simulate success if fields are present | |
| if ds.host and ds.username: | |
| return {"status": "ok"} | |
| else: | |
| raise HTTPException(status_code=400, detail="Missing connection details") | |
| elif ds.type in [DataSourceType.excel, DataSourceType.csv]: | |
| if os.path.exists(ds.file_path): | |
| return {"status": "ok"} | |
| else: | |
| raise HTTPException(status_code=400, detail="File not found") | |
| return {"status": "ok"} | |
| def update_data_source( | |
| id: int, | |
| data_source_in: schemas.DataSourceCreate, | |
| db: Session = Depends(deps.get_db), | |
| current_user: User = Depends(deps.get_current_user), | |
| ): | |
| """Update an existing data source""" | |
| ds = db.query(DataSource).filter(DataSource.id == id, DataSource.user_id == current_user.id).first() | |
| if not ds: | |
| raise HTTPException(status_code=404, detail="Data source not found") | |
| # Update fields | |
| # Update fields | |
| update_data = data_source_in.model_dump(exclude_unset=True) | |
| for field, value in update_data.items(): | |
| # Skip empty password update to preserve existing password | |
| if field == "password" and not value: | |
| continue | |
| setattr(ds, field, value) | |
| db.commit() | |
| db.refresh(ds) | |
| return ds | |
| def delete_data_source( | |
| id: int, | |
| db: Session = Depends(deps.get_db), | |
| current_user: User = Depends(deps.get_current_user), | |
| ): | |
| ds = db.query(DataSource).filter(DataSource.id == id, DataSource.user_id == current_user.id).first() | |
| if not ds: | |
| raise HTTPException(status_code=404, detail="Data source not found") | |
| # Optional: Delete file if it exists | |
| if ds.file_path and os.path.exists(ds.file_path): | |
| try: | |
| os.remove(ds.file_path) | |
| except OSError: | |
| pass # Log error or ignore | |
| db.delete(ds) | |
| db.commit() | |
| return None | |