paint-brush
Implement a Systemd Service on a Flask APIby@noaahhh
1,258 reads
1,258 reads

Implement a Systemd Service on a Flask API

by Nuh YurdusevenDecember 9th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

An easy-to-use framework software for creating simple APIs can be used in the application development process or for custom. The 'systemd' package is a software package included in Linux operating systems. It is created by the init process and takes 1 as the process id (PID) Services are started automatically and can be managed by root users. To add it to your script file, download the flask module `pip3` and include it on the page and create an app object to create your routes.

Company Mentioned

Mention Thumbnail
featured image - Implement a Systemd Service on a Flask API
Nuh Yurduseven HackerNoon profile picture


In this post, I want to show you something about a productivity trick on the server-side. I will discuss the systemd package on Linux systems.


First of all, systemd is a software package included in Linux operating systems.


It is created by the init process and takes 1 as the process id (PID). systemd services are started automatically and can be managed by root users. With the sytemctl command, systemd services can be started (start) and stopped (stop), applications that have changed configuration files can be re-read and restarted (reload), the status of the process can be obtained (status), and its activation can be controlled after the system restarts ( enable/disable). For more information, see the manual page.


$ man systemctl


Flask microframework is a very easy-to-use framework software for creating simple APIs. To add it to your script file, it is sufficient to download the flask module pip3 and include it on the page, and create an app object to create your routes. Then the script below can be used.


import flask
app = flask.Flask(__name__)
app.config["DEBUG"] = True

@app.route('/', methods=['GET'])
def function_one():
return "<div style=\"   display: flex;justify-content: center;align-items: center;height: 100%;border: 3px solid green;  \" ><p>Hello sir, It seems to work properly.Here is<span style=\"font-size:50px; color:white; background-color:red\"> / </span></p> </div>"

@app.route('/users', methods=['GET'])
def function_two():
return "<div style=\"   display: flex;justify-content: center;align-items: center;height: 100%;border: 3px solid green;  \" ><p>Hello sir, It seems to work properly.Here is<span style=\"font-size:50px; color:white; background-color:green\"> /users</span> </p> </div>"

@app.route('/products', methods=['GET'])
def function_three():
return "<div style=\"   display: flex;justify-content: center;align-items: center;height: 100%;border: 3px solid green;  \" ><p>Hello sir, It seems to work properly.Here is<span style=\"font-size:50px; color:white; background-color:blue\"> /products </span></p> </div>"

app.run()


By default, it starts working on the localhost:5000 port. To change port or host, you can give a new host and port with app.run(host='ip_addr',port='port' ).


After the script is saved as app.py, it can be converted to a systemd service by writing the systemd service.


When a flask application is run with python, it is raised on the "development server". There are different options for the API to be raised in the "Production" environment. You can learn from the Flask manual page.


Check out flask Deployment options


Depending on the operating system, sudo vi /lib/systemd/system/myFlaskApp.service or Let's open it in nano editor. This path may differ depending on the distro. To find out where other services are, e.g. for MariaDB service,


$ locate mariadb


If there is no output, use the updatedb command and try again. services can also be found under /usr/lib/systemd/system/… Or you can create such a directory under the /usr directory.


Open the /lib/systemd/system/myFlaskApp.service file and add the following lines


[Unit]
Description=My flask API service
[Install]
WantedBy=multi-user.target
[Service]
Type=simple
User=$USER
PermissionsStartOnly=true
ExecStart=/usr/bin/python3 /your/path/app.py
Restart=on-failure
TimeoutSec=600 


Note: Here we set Restart=on-failure. This indicates that we only want it to restart when the exit code is not 0. We can also add Restart=always and RestartSec=1 lines instead. It makes it reboot in any case.

You can add a config file with sudo vi /etc/init/myFlaskApp.config.


description "MyFlaskApp"
start on stopped rc RUNLEVEL=[2345]
respawn
exec python3 /your/path/app.py


Then, command following command on Linux terminal.


$ sudo systemctl start myFlaskApp


You can start the service with this command. Make sure it is in the active(running) state with systemctl status.


application gif


This method can be useful for developments made on the cloud service, but it is recommended to use the deployment options above in terms of both performance and manageability in the production environment.


This service runs in the background without user intervention. It takes a pid as can be seen with sytemctl status. If a modular API structure is created and the route operation and other operations are isolated from each other, this method may be useful in situations where no modifications to this file are required. In this way, we can call it “life hacking”.


First published here