Custom scripts and more on Flask

This week our task was the following on the Linux course:

a) Create a new command in Linux and set it up to work as a script for every user.

b) Create a script that handles command line arguments.

c) Create a Flask app that has multiple paths.

d) Create a Flask app that uses templates.

e) optional: use c and d in a production-like environment

f) optional: read user input in Flask.

g) optional: Create a Flask app that reads user input from a form and calculates the area of a square.

Creating a new script for all users

I wrote a basic bash script that prints the username and date and tested it in my home folder. Then I changed the permissions so that everyone can read and execute it but not modify it. I then copied it to the /usr/bin folder so that everyone could use it by just issuing the script name. Then I created a new test user, logged into it and tested again.

nano userinfo
DATE="$(date +'%y/%m/%d')"
printf "Hello ${NAME}!\nThe date is: ${DATE}"


chmod +x userinfo
chmod g-w userinfo
sudo cp userinfo /usr/bin/
ls -l /usr/bin/userinfo
    -rwxr-xr-x 1 root root 102 Oct  1 12:23 /usr/bin/userinfo
sudo adduser test
su test


A script with command line parameters

For this script I decided to just do some basic arithmetic and then some checking for arguments. If there are no arguments, or the argument is not an integer, you get an error message.

if [ $# -eq 0 ] ; then
    echo "No arguments given. Requires 1 argument."
    if ! [[ $1 =~ $RE ]] ; then
        echo "Given argument is not a valid number"
        echo $CUBE


A Flask app with multiple paths

As a basic Flask app with just a landing page looks like this:

from flask import Flask
app = Flask(__name__)

def hello():
        return "Flask site works"
curl localhost:5000
Flask site works

I can create another route on the app by creating another function and declaring a different route with the @app.route notation.

def test():
        return "testing routes"

def test2():
        return "testing routes 2"


Flask Templates

To use templates I need to create a templates sub-folder in the directory that the app is run from and create an html file. I then need to import render_template in the python file and use it in the route that I want to.

mkdir templates
nano templates/basic.html
<!doctype html>
               <title>Flask Template</title>
               <meta charset="utf-8">
               <h1>{{ title }}</h1>
from flask import Flask, render_template
def test2():
       return render_template("basic.html", title="Template Works")


I've already setup a production-like environment once before and wrote about it on my previous post, so I won't be repeating myself here.