Integrating ONLYOFFICE With a Python App

Integrating ONLYOFFICE With a Python App

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

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

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.

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](http://localhost:8080 "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 . 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).

Thanks for reading ❤

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Description
Learn Hands-On Python Programming By Creating Projects, GUIs and Graphics

Python is a dynamic modern object -oriented programming language
It is easy to learn and can be used to do a lot of things both big and small
Python is what is referred to as a high level language
Python is used in the industry for things like embedded software, web development, desktop applications, and even mobile apps!
SQL-Lite allows your applications to become even more powerful by storing, retrieving, and filtering through large data sets easily
If you want to learn to code, Python GUIs are the best way to start!

I designed this programming course to be easily understood by absolute beginners and young people. We start with basic Python programming concepts. Reinforce the same by developing Project and GUIs.

Why Python?

The Python coding language integrates well with other platforms – and runs on virtually all modern devices. If you’re new to coding, you can easily learn the basics in this fast and powerful coding environment. If you have experience with other computer languages, you’ll find Python simple and straightforward. This OSI-approved open-source language allows free use and distribution – even commercial distribution.

When and how do I start a career as a Python programmer?

In an independent third party survey, it has been revealed that the Python programming language is currently the most popular language for data scientists worldwide. This claim is substantiated by the Institute of Electrical and Electronic Engineers, which tracks programming languages by popularity. According to them, Python is the second most popular programming language this year for development on the web after Java.

Python Job Profiles
Software Engineer
Research Analyst
Data Analyst
Data Scientist
Software Developer
Python Salary

The median total pay for Python jobs in California, United States is $74,410, for a professional with one year of experience
Below are graphs depicting average Python salary by city
The first chart depicts average salary for a Python professional with one year of experience and the second chart depicts the average salaries by years of experience
Who Uses Python?

This course gives you a solid set of skills in one of today’s top programming languages. Today’s biggest companies (and smartest startups) use Python, including Google, Facebook, Instagram, Amazon, IBM, and NASA. Python is increasingly being used for scientific computations and data analysis
Take this course today and learn the skills you need to rub shoulders with today’s tech industry giants. Have fun, create and control intriguing and interactive Python GUIs, and enjoy a bright future! Best of Luck
Who is the target audience?

Anyone who wants to learn to code
For Complete Programming Beginners
For People New to Python
This course was designed for students with little to no programming experience
People interested in building Projects
Anyone looking to start with Python GUI development
Basic knowledge
Access to a computer
Download Python (FREE)
Should have an interest in programming
Interest in learning Python programming
Install Python 3.6 on your computer
What will you learn
Build Python Graphical User Interfaces(GUI) with Tkinter
Be able to use the in-built Python modules for their own projects
Use programming fundamentals to build a calculator
Use advanced Python concepts to code
Build Your GUI in Python programming
Use programming fundamentals to build a Project
Signup Login & Registration Programs
Quizzes
Assignments
Job Interview Preparation Questions
& Much More

Guide to Python Programming Language

Guide to Python Programming Language

Guide to Python Programming Language

Description
The course will lead you from beginning level to advance in Python Programming Language. You do not need any prior knowledge on Python or any programming language or even programming to join the course and become an expert on the topic.

The course is begin continuously developing by adding lectures regularly.

Please see the Promo and free sample video to get to know more.

Hope you will enjoy it.

Basic knowledge
An Enthusiast Mind
A Computer
Basic Knowledge To Use Computer
Internet Connection
What will you learn
Will Be Expert On Python Programming Language
Build Application On Python Programming Language

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Description
Hello and welcome to brand new series of wiredwiki. In this series i will teach you guys all you need to know about python. This series is designed for beginners but that doesn't means that i will not talk about the advanced stuff as well.

As you may all know by now that my approach of teaching is very simple and straightforward.In this series i will be talking about the all the things you need to know to jump start you python programming skills. This series is designed for noobs who are totally new to programming, so if you don't know any thing about

programming than this is the way to go guys Here is the links to all the videos that i will upload in this whole series.

In this video i will talk about all the basic introduction you need to know about python, which python version to choose, how to install python, how to get around with the interface, how to code your first program. Than we will talk about operators, expressions, numbers, strings, boo leans, lists, dictionaries, tuples and than inputs in python. With

Lots of exercises and more fun stuff, let's get started.

Download free Exercise files.

Dropbox: https://bit.ly/2AW7FYF

Who is the target audience?

First time Python programmers
Students and Teachers
IT pros who want to learn to code
Aspiring data scientists who want to add Python to their tool arsenal
Basic knowledge
Students should be comfortable working in the PC or Mac operating system
What will you learn
know basic programming concept and skill
build 6 text-based application using python
be able to learn other programming languages
be able to build sophisticated system using python in the future

To know more: