Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Integrating ONLYOFFICE With a Python App

DZone 's Guide to

Integrating ONLYOFFICE With a Python App

In this article, see how to integrate ONLYOFFICE into your Python app.

· Integration Zone ·
Free Resource

ONLYOFFICE is a powerful open-source service that can bring document, spreadsheet, and presentation editing to web apps written in any programming language. In this article, we will tell you how to integrate ONLYOFFICE into your Python app.

For this, we will create a simple document management system on Python and integrate ONLYOFFICE document editors into it. This is going to be easier than you think.

Image title

DMS in Python

In this part, we will write a Python app to show integration with ONLYOFFICE on its example. It’s highly likely that the app into which you’re planning to integrate the editors has a list of files you need to open for viewing/editing. So, let’s just create an app with this functionality. The app should also allow downloading files.

For the app, we will use a Bottle framework. You can install it in the work directory using  pip install bottle  command. Now we need to create files  main.py  (the app’s code) и  index.tpl  (template), and then add the following code into the  main.py  file:

from bottle import route, run, template, get, static_file # connecting the framework and the necessary components
@route('/') # setting up routing for requests for /
def index():
    return template('index.tpl')  # showing template in response to request


run(host="localhost", port=8080)  # running the application on port 8080

When we start the application, we see an empty page on  http://localhost:8080 . As Document Server can't create new docs from scratch, we have to add default files and form a list of their names in the template. So, we create a folder  files , and put 3 files (docx, xlsx and pptx) in there.

We will use the  listdir  component to read their names.

from os import listdir

Now let’s create a variable for all the file names from the files folder:

sample_files = [f for f in listdir('files')]

To use this variable in the template, we need to pass it through the  template  method:

def index():
    return template('index.tpl', sample_files=sample_files)

Let’s show this variable in the template:

%for file in sample_files:
    <div>
        <span>{{file}}</span>
    </div>
% end

After restarting the application, we can see the list of file names on the page. Now we have to make these files available for all the app users.

Here’s a new method for it:

@get("/files/<filepath:re:.*\.*>")
def show_sample_files(filepath):
    return static_file(filepath, root="files")

Viewing Documents in Your Python App

Install Document Server with ONLYOFFICE editors. There are plenty of installation options, but we recommend using Docker:

docker run -itd -p 80:80 onlyoffice/documentserver-de

Connect document editors API in the template:

<script type="text/javascript" src="editor_url/web-apps/apps/api/documents/api.js"></script>

 editor_url  is a link to document editors.

A button to open each file for viewing:

<button onclick="view('files/{{file}}')">view</button>

Now we need to add a div with  id:

<div id="editor"></div>

The document editor will be opened in this div. But only after we call a function that will open the editor:

<script>
function view(filename) {
    if (/docx$/.exec(filename)) {
        filetype = "text"
    }
    if (/xlsx$/.exec(filename)) {
        filetype = "spreadsheet"
    }
    if (/pptx$/.exec(filename)) {
        filetype = "presentation",
        title: filename
    }

    new DocsAPI.DocEditor("editor",
        {
            documentType: filetype,
            document: {
                url: "host_url" + '/' + filename,
                title: filename
            },
            editorConfig: {mode: 'view'}
        });
  }
</script>

There are two arguments for the DocEditor function: id of the element where the editors will be opened and a JSON with the editors' settings.

All the parameters can be found in the official API documentation. In this example, we use mandatory parameters  documentType document.url and  editorConfig.mode. Let’s also add title — this is the filename that will be displayed in the editors.

The document type (documentType) will be identified by its format (docx for texts, xlsx for spreadsheets, pptx for presentations).

Pay attention to document.url. This is the link to the file we are going to open.

So, now we have everything to view docs in our Python app.

Editing Files

Let’s add the “Edit” button:

<button onclick="edit('files/{{file}}')">edit</button>

Now we need to create a new function that will open files for editing. It resembles the View function, so let’s make the common part a separate function.

Now we have 3 functions:

<script>
    var editor;
    function view(filename) {
        if (editor) {
            editor.destroyEditor()
        }
        editor = new DocsAPI.DocEditor("editor",
            {
                documentType: get_file_type(filename),
                document: {
                    url: "host_url" + '/' + filename,
                    title: filename
                },
                editorConfig: {mode: 'view'}
            });
    }

    function edit(filename) {
        if (editor) {
            editor.destroyEditor()
        }
        editor = new DocsAPI.DocEditor("editor",
            {
                documentType: get_file_type(filename),
                document: {
                    url: "host_url" + '/' + filename,
                    title: filename
                }
            });
    }

    function get_file_type(filename) {
        if (/docx$/.exec(filename)) {
            return "text"
        }
        if (/xlsx$/.exec(filename)) {
            return "spreadsheet"
        }
        if (/pptx$/.exec(filename)) {
            return "presentation"
        }
    }
</script>

 destroyEditor  will close the editor if it was opened.

By default, the  editorConfig parameter has the value  {"mode": "edit"} , that is why it is absent from the edit()   function.

Now files will be opened for editing.

Co-Editing Docs

Co-editing is implemented by using the same document.key for the same document in the editors' settings. Without this key, the editors will create the editing session each time you open the file.

To make users connect to the same editing session for co-editing, we need to set unique keys for each doc. Let’s use the key in the format  filename + "_key". We need to add this to all of the configs where document   is present.

 document: {
                    url: "host_url" + '/' + filepath,
                    title: filename,
                    key: filename + '_key'
                },

Saving Files

ONLYOFFICE usually stores all of the changes you made to the document while you are working there. After you close the editor, Document Server builds the file version to be saved and sends the request to callbackUrl address. This request contains document.key and the link to the just built file.

In production, you will use document.key to find the old version of the file and replace it with the new one. In our case here we do not have any database, so we just send the filename using callbackUrl.

Specify callbackUrl in the setting in editorConfig.callbackUrl. After we add this parameter, the  edit() method will look like this:

 function edit(filename) {
        const filepath = 'files/' + filename;
        if (editor) {
            editor.destroyEditor()
        }
        editor = new DocsAPI.DocEditor("editor",
            {
                documentType: get_file_type(filepath),
                document: {
                    url: "host_url" + '/' + filepath,
                    title: filename, 
                    key: filename + '_key'
                }
                ,
                editorConfig: {
                    mode: 'edit',
                    callbackUrl: "host_url" + '/callback' + '&filename=' + filename  // add file name as a request parameter
                }
            });
    }

Now we need to write a method that will save file after getting the post request to /callback address:

@post("/callback") # processing post requests for /callback
def callback():
    if request.json['status'] == 2:
        file = requests.get(request.json['url']).content
        with open('files/' + request.query['filename'], 'wb') as f:
            f.write(file)
    return "{\"error\":0}"

 # status 2  is the built file. More information about all the statuses can be found in the API documentation.

Now the new version of the file will be saved to storage after closing the editor.

Managing Users

If there are users in your app, write their identifiers (id and name) in the editors' configuration. This way you will be able to see who exactly is editing a doc.

As an example, let’s add the ability to select a user in the interface:

<select id="user_selector" onchange="pick_user()">
    <option value="1" selected="selected">JD</option>
    <option value="2">Turk</option>
    <option value="3">Elliot</option>
    <option value="4">Carla</option>
</select>

Let’s add the call of the function pick_user()  at the beginning of the tag <script>. In in the function itself, we will initialize the variables responsible for the id and the user name.

function pick_user() {
        const user_selector = document.getElementById("user_selector");
        this.current_user_name = user_selector.options[user_selector.selectedIndex].text;
        this.current_user_id = user_selector.options[user_selector.selectedIndex].value;
    }

Now we need to add the user's settings in the editors' configuration using editorConfig.user.id and  editorConfig.user.name. Let’s add these parameters to the editors' configuration in the file editing function.

 function edit(filename) {
        const filepath = 'files/' + filename;
        if (editor) {
            editor.destroyEditor()
        }
        editor = new DocsAPI.DocEditor("editor",
            {
                documentType: get_file_type(filepath),
                document: {
                    url: "host_url" + '/' + filepath,
                    title: filename
                },
                editorConfig: {
                    mode: 'edit',
                    callbackUrl: "host_url" + '/callback' + '?filename=' + filename,
                    user: {
                        id: this.current_user_id,
                        name: this.current_user_name
                    }
                }
            });
    }

We hope that this simple example will help you integrated ONLYOFFICE with your Python app. More integration examples can be found on GitHub

Earlier, we wrote about integrating editors with a Node.js app and permissions that have to be granted to ONLYOFFICE to make it work within your service (executing custom code, adding buttons, anonymous access to files, etc).

Topics:
python ,integration ,how-to ,tutorial ,open source ,document management software ,api ,document formatting services

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}