forked from fastapi/full-stack-fastapi-template
-
Notifications
You must be signed in to change notification settings - Fork 1
Add file upload/attachments for items #4
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
Open
emilkvarnhammar
wants to merge
1
commit into
master
Choose a base branch
from
feature/file-attachments
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
58 changes: 58 additions & 0 deletions
58
backend/app/alembic/versions/a1b2c3d4e5f6_add_attachment_model.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| """Add attachment model | ||
|
|
||
| Revision ID: a1b2c3d4e5f6 | ||
| Revises: fe56fa70289e | ||
| Create Date: 2026-03-06 10:00:00.000000 | ||
|
|
||
| """ | ||
| import sqlalchemy as sa | ||
| import sqlmodel.sql.sqltypes | ||
|
|
||
| from alembic import op | ||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision = "a1b2c3d4e5f6" | ||
| down_revision = "fe56fa70289e" | ||
| branch_labels = None | ||
| depends_on = None | ||
|
|
||
|
|
||
| def upgrade(): | ||
| op.create_table( | ||
| "attachment", | ||
| sa.Column( | ||
| "filename", | ||
| sqlmodel.sql.sqltypes.AutoString(length=255), | ||
| nullable=False, | ||
| ), | ||
| sa.Column( | ||
| "content_type", | ||
| sqlmodel.sql.sqltypes.AutoString(length=100), | ||
| nullable=False, | ||
| ), | ||
| sa.Column("size", sa.Integer(), nullable=False), | ||
| sa.Column( | ||
| "id", sa.Uuid(), nullable=False | ||
| ), | ||
| sa.Column( | ||
| "created_at", sa.DateTime(timezone=True), nullable=True | ||
| ), | ||
| sa.Column( | ||
| "storage_path", | ||
| sqlmodel.sql.sqltypes.AutoString(length=512), | ||
| nullable=False, | ||
| ), | ||
| sa.Column("item_id", sa.Uuid(), nullable=False), | ||
| sa.Column("uploaded_by", sa.Uuid(), nullable=False), | ||
| sa.ForeignKeyConstraint( | ||
| ["item_id"], ["item.id"], ondelete="CASCADE" | ||
| ), | ||
| sa.ForeignKeyConstraint( | ||
| ["uploaded_by"], ["user.id"] | ||
| ), | ||
| sa.PrimaryKeyConstraint("id"), | ||
| ) | ||
|
|
||
|
|
||
| def downgrade(): | ||
| op.drop_table("attachment") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,172 @@ | ||
| import os | ||
| import re | ||
| import uuid | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| from fastapi import APIRouter, HTTPException, UploadFile | ||
| from fastapi.responses import FileResponse | ||
| from sqlmodel import col, func, select | ||
|
|
||
| from app.api.deps import CurrentUser, SessionDep | ||
| from app.core.config import settings | ||
| from app.models import ( | ||
| Attachment, | ||
| AttachmentPublic, | ||
| AttachmentsPublic, | ||
| Item, | ||
| Message, | ||
| ) | ||
|
|
||
| router = APIRouter(prefix="/items/{item_id}/attachments", tags=["attachments"]) | ||
|
|
||
|
|
||
| def _sanitize_filename(filename: str) -> str: | ||
| """Remove directory separators and other unsafe characters from filename.""" | ||
| filename = os.path.basename(filename) | ||
| filename = re.sub(r"[^\w\s\-.]", "_", filename) | ||
| filename = filename.strip(". ") | ||
| if not filename: | ||
| filename = "unnamed" | ||
| return filename | ||
|
|
||
|
|
||
| def _get_item_or_404(session: SessionDep, item_id: uuid.UUID) -> Item: | ||
| item = session.get(Item, item_id) | ||
| if not item: | ||
| raise HTTPException(status_code=404, detail="Item not found") | ||
| return item | ||
|
|
||
|
|
||
| def _check_item_access(item: Item, current_user: CurrentUser) -> None: | ||
| if not current_user.is_superuser and item.owner_id != current_user.id: | ||
| raise HTTPException(status_code=403, detail="Not enough permissions") | ||
|
|
||
|
|
||
| @router.post("/", response_model=AttachmentPublic) | ||
| def upload_attachment( | ||
| *, | ||
| session: SessionDep, | ||
| current_user: CurrentUser, | ||
| item_id: uuid.UUID, | ||
| file: UploadFile, | ||
| ) -> Any: | ||
| """Upload a file attachment to an item.""" | ||
| item = _get_item_or_404(session, item_id) | ||
| _check_item_access(item, current_user) | ||
|
|
||
| if file.content_type not in settings.ALLOWED_UPLOAD_TYPES: | ||
| raise HTTPException( | ||
| status_code=400, | ||
| detail=f"File type '{file.content_type}' is not allowed. " | ||
| f"Allowed types: {', '.join(settings.ALLOWED_UPLOAD_TYPES)}", | ||
| ) | ||
|
|
||
| content = file.file.read() | ||
| if len(content) > settings.MAX_UPLOAD_SIZE: | ||
| raise HTTPException( | ||
| status_code=400, | ||
| detail=f"File size exceeds maximum of {settings.MAX_UPLOAD_SIZE} bytes", | ||
| ) | ||
|
|
||
| safe_filename = _sanitize_filename(file.filename or "unnamed") | ||
| file_id = uuid.uuid4() | ||
| storage_filename = f"{file_id}_{safe_filename}" | ||
| upload_dir = Path(settings.UPLOAD_DIR) / str(item_id) | ||
| upload_dir.mkdir(parents=True, exist_ok=True) | ||
| storage_path = upload_dir / storage_filename | ||
|
|
||
| storage_path.write_bytes(content) | ||
|
|
||
|
|
||
| attachment = Attachment( | ||
| filename=safe_filename, | ||
| content_type=file.content_type or "application/octet-stream", | ||
| size=len(content), | ||
| storage_path=str(storage_path), | ||
| item_id=item_id, | ||
| uploaded_by=current_user.id, | ||
| ) | ||
| session.add(attachment) | ||
| session.commit() | ||
| session.refresh(attachment) | ||
| return attachment | ||
|
|
||
|
|
||
| @router.get("/", response_model=AttachmentsPublic) | ||
| def list_attachments( | ||
| *, | ||
| session: SessionDep, | ||
| current_user: CurrentUser, | ||
| item_id: uuid.UUID, | ||
| ) -> Any: | ||
| """List all attachments for an item.""" | ||
| item = _get_item_or_404(session, item_id) | ||
| _check_item_access(item, current_user) | ||
|
|
||
| count_statement = ( | ||
| select(func.count()) | ||
| .select_from(Attachment) | ||
| .where(Attachment.item_id == item_id) | ||
| ) | ||
| count = session.exec(count_statement).one() | ||
|
|
||
| statement = ( | ||
| select(Attachment) | ||
| .where(Attachment.item_id == item_id) | ||
| .order_by(col(Attachment.created_at).desc()) | ||
| ) | ||
| attachments = session.exec(statement).all() | ||
|
|
||
| return AttachmentsPublic(data=attachments, count=count) | ||
|
|
||
|
|
||
| @router.get("/{attachment_id}/download") | ||
| def download_attachment( | ||
| *, | ||
| session: SessionDep, | ||
| current_user: CurrentUser, | ||
| item_id: uuid.UUID, | ||
| attachment_id: uuid.UUID, | ||
| ) -> Any: | ||
| """Download an attachment file.""" | ||
| item = _get_item_or_404(session, item_id) | ||
| _check_item_access(item, current_user) | ||
|
|
||
| attachment = session.get(Attachment, attachment_id) | ||
| if not attachment or attachment.item_id != item_id: | ||
| raise HTTPException(status_code=404, detail="Attachment not found") | ||
|
|
||
| file_path = Path(attachment.storage_path) | ||
| if not file_path.exists(): | ||
| raise HTTPException(status_code=404, detail="Attachment file not found on disk") | ||
|
|
||
| return FileResponse( | ||
| path=str(file_path), | ||
| filename=attachment.filename, | ||
| media_type=attachment.content_type, | ||
| ) | ||
|
|
||
|
|
||
| @router.delete("/{attachment_id}") | ||
| def delete_attachment( | ||
| *, | ||
| session: SessionDep, | ||
| current_user: CurrentUser, | ||
| item_id: uuid.UUID, | ||
| attachment_id: uuid.UUID, | ||
| ) -> Message: | ||
| """Delete an attachment.""" | ||
| item = _get_item_or_404(session, item_id) | ||
| _check_item_access(item, current_user) | ||
|
|
||
| attachment = session.get(Attachment, attachment_id) | ||
| if not attachment or attachment.item_id != item_id: | ||
| raise HTTPException(status_code=404, detail="Attachment not found") | ||
|
|
||
| file_path = Path(attachment.storage_path) | ||
| if file_path.exists(): | ||
| file_path.unlink() | ||
|
|
||
| session.delete(attachment) | ||
| session.commit() | ||
| return Message(message="Attachment deleted successfully") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.