UWSGI Recipes: Converting Documents Using LibreOffice

To prepare the conversion of documents, we need LibreOffice , uwsgi-python , pylokit and webob . You can also use a ready-made image . But this is only for starting the uWSGI server, and we will use nginx to connect to the uWSGI server .



The simplest uWSGI python application consists of an application function with two arguments, environ and start_response



import os       # 
import pylokit  # 
import tempfile # 
import webob    # 

office = pylokit.Office('/usr/lib/libreoffice/program') #   LibreOffice   

def application(environ, start_response): #   uWSGI
    request = webob.Request(environ) #    
    file = request.POST['file'] #      multipart/form-data   file
    filename, extension = os.path.splitext(file.filename) #    
    with tempfile.NamedTemporaryFile(suffix=extension) as inp, tempfile.NamedTemporaryFile(suffix='.%s' % request.path.split('/')[-1]) as out: #                  (   unoconv-api)
        inp.write(file.file.read()) #        
        inp.flush() # (.. LibreOfficeKit -    )
        with office.documentLoad(inp.name) as doc: #    
            doc.saveAs(out.name) #        (   )
            with open(out.name, 'rb') as out2: #    
                response = webob.Response(body=out2.read()) #       
                return response(environ, start_response) #   


You can, of course, add any error handling.



Converting a test one page odt file to pdf is about 1.5 times faster than unoconv-api .



All Articles