Extension Point : IAttachmentManipulator
The IAttachmentManipulator can manipulate and validate attachments before saving.
Trac allows users to attach arbitrary files to e.g. tickets or wiki pages. Plugins can hook into the attachment module to tweak the attachment saving process.
The main purpose for this interface is to allow plugins to add new attachment validation rules. Attachments violating these rules are rejected.
validate_attachment method is called when a user adds a new attachment or replaces an existing attachment. Returning a list of messages rejects the attachment, returning
 accepts it.
Note that currently there is no easy way to validate the attachment's file contents. (See #9281) The
req parameter contains a file object in
req.args['attachment''].file that can be read from. (Make sure to
seek back to
0 or only the remaining file content after the current file position may be stored.)
if 'attachment' in req.args: upload = req.args['attachment'] try: data = upload.file.read(self.sample_size) if not is_binary(data): content = to_unicode(data) finally: upload.file.seek(0) filename = upload.filename
prepare_attachment method should always be implemented as an empty dummy method for compatibility reasons:
def prepare_attachment(self, req, attachment, fields): pass
A common use case for attachments is to attach patches to tickets. An open source project might require all such patches to be explicitly licensed under the BSD license. The following minimal example IAttachmentManipulator implementation could enforce such a policy:
from trac.core import Component, implements from trac.attachment import IAttachmentManipulator from trac.mimeview.api import get_mimetype class PatchLicenseChecker(Component): implements(IAttachmentManipulator) def prepare_attachment(self, req, attachment, fields): pass def validate_attachment(self, req, attachment): mimetype = get_mimetype(attachment.filename) if mimetype == 'text/x-diff' and \ not attachment.description.contains('BSD'): return [('description', "Patches must be released under BSD license")] return 
- SpamFilter: Reject attachments that contain spam
- th:AttachFilterPlugin: Reject attachments by MIME type (guessed from file extension)
Additional Information and References
- API Reference
- See trac.attachment.IAttachmentChangeListener
- See trac.ticket.api.ITicketManipulator, trac.wiki.api.IWikiPageManipulator
- Introduced in changeset:3399
- Attachments database schema
- Related tickets:
- attachment component
- #6014 Pre-/Post-processing for compression, virus-check, etc.
- #9281 Easily accessing attachment data
- #10125 Discusses unused
- comment:15:ticket:10125 and following discuss ideas for fundamental refactoring
- #10353 Multiple error messages (Fixed in 1.0)