uWSGI Recipes: Document Conversion Using LibreOffice

To prepare for document conversion, we will need LibreOffice, uwsgi-python, pylokit and webob. You can also use the finished way. However, this is only for starting the uWSGI server, and to connect to the uWSGI server we will use nginx.

The simplest uWSGI application in Python consists of an application function with two arguments: environ and start_response.

import os       # import
import pylokit  # necessary
import tempfile # for us
import webob    # modules

office = pylokit.Office('\/usr\/lib\/libreoffice\/program') # load the LibreOffice library from the specified path

def application(environ, start_response): # function for uWSGI
    request = webob.Request(environ) # get the request from the environment
    file = request.POST['file'] # the file to be converted is passed through multipart\/form-data with the name file
    filename, extension = os.path.splitext(file.filename) # get the name and extension
    with tempfile.NamedTemporaryFile(suffix=extension) as inp, tempfile.NamedTemporaryFile(suffix='.%s' % request.path.split('\/')[-1]) as out: # create one temporary file with the extension of the sent file and another temporary file with the extension from the end of the request (for compatibility with unoconv-api)
        inp.write(file.file.read()) # write the contents of the sent file to the first temporary file
        inp.flush() # (since LibreOfficeKit works only with files)
        with office.documentLoad(inp.name) as doc: # load the sent file
            doc.saveAs(out.name) # export the loaded file to another temporary file (the format is taken from the extension)
            with open(out.name, 'rb') as out2: # open the other temporary file
                response = webob.Response(body=out2.read()) # create the result from reading the other temporary file
                return response(environ, start_response) # and return it

You can also add error handling.

The conversion of a test single-page odt file to pdf is about 1.5 times faster compared to unoconv-api.

Source: habr.com

Buy reliable website hosting with DDoS protection, VPS VDS servers 🔥 Buy reliable website hosting with DDoS protection, VPS VDS servers | ProHoster