Thursday, May 28, 2009

Trac Wiki Add Attachment Programatically

Yesterday, I was surprised to find out that there is no utility in trac-admin for adding/deleting attachments from a wiki page. I wanted a simple test script to accomplish this. I took a look at the moin2trac.py script and ended up ripping out a small part of it in order to put together a minimal test script. This was tested using trac-0.11.4 with Python 2.5.
import os
from trac.attachment import Attachment
from trac.admin.console import TracAdmin

wikidir = r'C:\Path\To\My\TracProject'

admin = TracAdmin()
admin.env_set(wikidir)

filename = r'c:\Path\To\My\Images\2_0.jpg'

attachment = Attachment(admin.env_open(), 'wiki', 'tutorials/page1')

size = os.stat(filename)[6]
attfile = open(filename,'rb')

attachment.insert(os.path.basename(filename), attfile, size)

The parameters should be reasonably self-explanatory, although do not hesitate to send any questions. I'm thinking it would be reasonably simple to add this functionality to trac-admin. I will probably take a look at this sometime soon and submit a patch.

Cheers!

1 comment:

Pedahzur said...

Thanks for the tips here. This got me started on the steps I needed to add attachments to tickets from Python.

A big help!