Opskrifter til uWSGI: konvertering af dokumenter med LibreOffice

For document conversion, we will need LibreOffice, uwsgi-python, pylokit og webob. You can also use a ready-made approach. However, this is only for starting the uWSGI server, and for connecting 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 # needed
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 for conversion is passed via 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 passed 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 passed file into the first temporary file
        inp.flush() # (since LibreOfficeKit seems to only work with files)
        with office.documentLoad(inp.name) as doc: # load the passed 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 a result from reading the other temporary file
                return response(environ, start_response) # and return it

Of course, you can also add error handling.

Converting a test single-page odt file to pdf takes about 1.5 times faster compared to unoconv-api.

Kilde: habr.com

Køb pålidelig webhosting med DDoS-beskyttelse, VPS VDS-servere 🔥 Køb pålidelig webhosting med DDoS-beskyttelse, VPS VDS-servere | ProHoster