To address the issues with processing media files (photos and videos) in your Odoo 17 project integrated with FastAPI, we'll follow best practices to ensure efficient handling, security, and scalability. Below are the steps to enhance your current implementation:
-
Avoid Storing Large Media in the Database:
Storing large binary files directly in the database can lead to performance issues. Instead, leverage Odoo’s built-in attachment system, which stores files in the filestore, making it more efficient and scalable.
-
Implement File Validation:
Ensure that only allowed file types and sizes are uploaded to prevent potential security vulnerabilities and excessive storage use.
-
Optimize File Handling in FastAPI:
Utilize asynchronous file operations and avoid loading entire files into memory to handle large uploads efficiently.
-
Enhance Media URL Generation:
Simplify media URL generation and ensure it integrates seamlessly with Odoo’s routing for serving media files.
-
Improve Code Structure and Error Handling:
Organize your code for better readability and maintainability, and enhance error handling to provide more meaningful responses.
Below is the revised code incorporating these best practices:
1. Update Odoo Models
Use Odoo’s Attachment System:
Instead of storing media directly in your custom models, leverage Odoo's ir.attachment model. This approach utilizes Odoo's filestore, which is optimized for handling large files.
from odoo import models, fields, api, _
import datetime
class Application(models.Model):
_name = 'mahallam.application'
_description = 'Application'
# Existing fields...
image_ids = fields.Many2many('ir.attachment',
string=_('Images'),
domain=[('res_model', '=', 'mahallam.application.media')],
attachment=True)
after_image_ids = fields.Many2many('ir.attachment',
string=_('After Images'),
domain=[('res_model', '=', 'mahallam.application.after.media')],
attachment=True)
# ... rest of the model
class ApplicationMedia(models.Model):
_name = 'mahallam.application.media'
_description = 'Application Media'
application_id = fields.Many2one('mahallam.application', string='Application', required=True, ondelete='cascade')
# Removed 'media' and 'media_name' fields since attachments will handle this
class ApplicationAfterMedia(models.Model):
_name = 'mahallam.application.after.media'
_description = 'Application After Media'
application_id = fields.Many2one('mahallam.application', string='Application', required=True, ondelete='cascade')
# Removed 'media' and 'media_name' fields
2. Enhance FastAPI Endpoints
a. File Validation:
Define allowed file types and maximum file size to ensure only appropriate files are uploaded.
from fastapi import HTTPException
from typing import List
import imghdr
ALLOWED_IMAGE_TYPES = ["jpeg", "png", "gif"]
ALLOWED_VIDEO_TYPES = ["mp4", "avi", "mov"]
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10 MB
def validate_file(upload_file: UploadFile):
if upload_file.content_type.startswith('image/'):
file_type = imghdr.what(upload_file.file)
if file_type not in ALLOWED_IMAGE_TYPES:
raise HTTPException(status_code=400, detail=f"Unsupported image type: {file_type}")
elif upload_file.content_type.startswith('video/'):
file_extension = upload_file.filename.split('.')[-1].lower()
if file_extension not in ALLOWED_VIDEO_TYPES:
raise HTTPException(status_code=400, detail=f"Unsupported video type: {file_extension}")
else:
raise HTTPException(status_code=400, detail="Unsupported file type")
upload_file.file.seek(0, 2) # Seek to the end of the file
file_size = upload_file.file.tell()
upload_file.file.seek(0) # Reset the file pointer to the beginning
if file_size > MAX_FILE_SIZE:
raise HTTPException(status_code=400, detail="File size exceeds the maximum allowed limit")
b. Optimize File Upload Handling:
Use Odoo’s attachment creation capabilities to handle file uploads efficiently without reading the entire file into memory.
from fastapi import APIRouter, Depends, UploadFile, File, Form, HTTPException
from typing import List
from pydantic import BaseModel
from datetime import datetime
from odoo.addons.fastapi_addon.schemas.base_schema import PagedCollection
from ..settings import STAGE
import uuid
router = APIRouter()
# Define your Pydantic models as before...
@router.post("/create", response_model=ApplicationDetail)
async def create_application(
env: Annotated[Environment, Depends(odoo_env)],
partner: Annotated[Partner, Depends(get_partner_with_session)],
category_id: int = Form(...),
subcategory_id: int = Form(...),
description: str = Form(...),
latitude: float = Form(...),
longitude: float = Form(...),
media_files: List[UploadFile] = File(...),
):
# Validate and prepare application data
Application = env['mahallam.application'].sudo()
ApplicationMedia = env['mahallam.application.media'].sudo()
main_home = partner.home_ids.filtered(lambda h: h.is_main_home)
application_vals = {
'category_id': category_id,
'subcategory_id': subcategory_id,
'description': description,
'latitude': latitude,
'longitude': longitude,
'status': 'created',
'partner_id': partner.id,
}
if main_home:
application_vals.update({
'mahalla_id': main_home.home_id.mahalla_id.id,
'district_id': main_home.home_id.district_id.id,
'region_id': main_home.home_id.region_id.id,
})
application = Application.create(application_vals)
# Process each uploaded file
for media_file in media_files:
validate_file(media_file) # Validate the file
# Generate a unique name to prevent conflicts
unique_filename = f"{uuid.uuid4()}_{media_file.filename}"
# Create an attachment using Odoo's attachment system
attachment = env['ir.attachment'].sudo().create({
'name': unique_filename,
'type': 'binary',
'datas': media_file.file.read(), # Read file content
'res_model': 'mahallam.application.media',
'res_id': ApplicationMedia.create({
'application_id': application.id,
}).id,
'mimetype': media_file.content_type,
'db_datas': False, # Store in filestore
})
# Optionally, you can link the attachment to the application directly
# if you prefer to use many2many with 'ir.attachment'
return await get_application_detail(application.id, env, partner)
c. Optimize Retrieval of Media URLs:
Simplify the get_media_url function and ensure URLs are correctly generated based on the environment.
def get_media_url(attachment_id: int):
if STAGE == "production":
base_url = "https://mahallam-backend.uicgroup.tech"
else:
base_url = "http://localhost:8070"
unique_token = unique_str_generator(10)
return f"{base_url}/web/image/ir.attachment/{attachment_id}/datas/?unique={unique_token}"
d. Update get_application_detail Endpoint:
@router.get("/{application_id}", response_model=ApplicationDetail)
async def get_application_detail(
application_id: int,
env: Annotated[Environment, Depends(odoo_env)],
partner: Annotated[Partner, Depends(get_partner_with_session)],
):
Application = env['mahallam.application'].sudo()
application = Application.browse(application_id)
if not application.exists():
raise HTTPException(status_code=404, detail=_("Application not found"))
# Fetch attachments related to the application
images = env['ir.attachment'].sudo().search([
('res_model', '=', 'mahallam.application.media'),
('res_id', 'in', application.image_ids.ids)
])
after_images = env['ir.attachment'].sudo().search([
('res_model', '=', 'mahallam.application.after.media'),
('res_id', 'in', application.after_image_ids.ids)
])
return ApplicationDetail(
id=application.id,
status=application.status,
description=application.description,
date=application.created_at,
category=application.category_id.name if application.category_id else None,
subcategory=application.subcategory_id.name if application.subcategory_id else None,
state=[(state.name, state.description) for state in application.state_id],
images=[get_media_url(media.id) for media in images],
after_images=[get_media_url(media.id) for media in after_images],
is_author=application.partner_id.id == partner.id
)
3. Additional Best Practices
a. Asynchronous File Handling:
Ensure that file operations in FastAPI are non-blocking. Since Odoo’s ORM operations are synchronous, consider using background tasks for intensive operations if necessary.
b. Security Considerations:
- Authentication & Authorization: Ensure that only authorized users can upload and access media files.
- Sanitize File Names: Prevent directory traversal attacks by sanitizing file names.
- Use Secure URLs: To prevent unauthorized access, consider implementing token-based access for media URLs or ensuring that media-serving endpoints respect user permissions.
c. Error Handling:
Enhance error handling to cover more scenarios and provide meaningful feedback to the client.
from fastapi import Request
@router.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
return JSONResponse(
status_code=exc.status_code,
content={"message": exc.detail},
)
d. Logging:
Implement logging to monitor file upload activities and debug issues effectively.
import logging
logger = logging.getLogger(__name__)
# In your create_application endpoint
try:
# File processing logic...
logger.info(f"User {partner.id} uploaded file {unique_filename} for application {application.id}")
except Exception as e:
logger.error(f"Error uploading file {media_file.filename}: {str(e)}")
raise HTTPException(status_code=500, detail="Internal Server Error")
4. Summary of Changes
- Model Adjustments: Leveraged Odoo’s
ir.attachment for handling media files instead of storing binaries directly in custom models.
- File Validation: Added validation for file types and sizes to ensure only appropriate files are uploaded.
- Optimized File Handling: Used Odoo’s attachment creation to handle file uploads efficiently and avoid loading entire files into memory.
- Media URL Generation: Simplified and secured media URL generation, ensuring it aligns with the environment settings.
- Enhanced Security and Error Handling: Implemented better security practices and comprehensive error handling to provide meaningful responses and maintain application integrity.
- Logging: Added logging to monitor and debug file upload processes effectively.
By implementing these changes, your FastAPI and Odoo integration will handle media files more efficiently, securely, and in line with best practices. This approach ensures scalability and maintainability as your application grows.