Table of Contents
- Mini Project 1: Sorting App
In this mini project, you will develop a web app to sort numbers. By the end of this assignment, you should be able to:
- Create a simple web app using Flask web framework
- Use Transcrypt Python library to create front-end web script with Python
- Run a localhost web server
You need to have Git to do the project. Download and install the software according to your OS:
- Windows: Git for Windows
- Mac OS: Git for MacOS
Clone the mini project repository from Github. On your terminal or Git Bash, type the following:
cd Downloads
git clone https://github.com/Data-Driven-World/d2w_mini_projectsOnce you have downloaded the repository, you can go to the repository and to the folder called mp_sort for this mini project.
Windows:
cd d2w_mini_projects\mp_sort
dir
Unix/MacOS
cd d2w_mini_projects/mp_sort
lsThe last command should output the following:
Readme.md
application.py
Pipfile
Pipfile.lock
appThis handout can be found in the file Readme.md.
You should open Anaconda Prompt to do the following steps.
In the following steps, whenever there is a different between the OS commands, the Windows prompt will be represented by:
>while the MacOS/Linux prompt will be represented by:
$Go to the root folder mp_sort.
Windows:
> cd %USERPROFILE%\Downloads\d2w_mini_projects\mp_sort
Unix/MacOS:
$ cd ~/Downloads/d2w_mini_projects/mp_sortFirst make sure that you have installed pipenv package.
pip install --user pipenvWe will call mp_sort folder as the root folder of our application.
From the root folder, install the packages specified in the Pipfile.
pipenv installThe above steps will install Flask and Transcrypt Python libraries and some other necessary packages.
To activate the virtualenv, run
pipenv shellAlternatively, you can choose everytime you run a command to prepend that command with the following:
pipenv runOk, so let's enter into the shell by typing:
pipenv shellYou should see the word (mp_sort) in your prompt something like:
Windows:
(mp_sort) folder >
Unix/MacOS:
(mp_sort) user $To exit the virtual environment at the end of this mini project, simply type:
exitAll the subsequent exercises assumes you are in the virtualenv shell.
We are using Flask web framework to create this web app. The first file you may notice is application.py in the root folder. Open that file using a text editor. You should see the following:
from app import application
if __name__ == "__main__":
application.run(host="0.0.0.0", port=8080, debug=True)The last two lines runs the application object when it is run on the shell. The value will be used when you deploy it to Amazon Elastic Beanstalk. It also enables the debug mode to True so that you can see any error messages when they occur. The application object is imported in the first line from the app package. The app package is in a folder called app:
mp_sort/
app/
__init__.py
routes.py
static/
templates/The file __init__.py contains the line that creates the application object as a Flask instance.
from flask import Flask
application = Flask(__name__)
from app import routesThis file also import the file routes.py which defines the URL routing.
from flask import render_template
from app import application
@application.route('/')
@application.route('/index')
def index():
return render_template('index.html', title='Mini Project 1 Home')
@application.route('/ex1')
def exercise1():
return render_template('ex1.html', title='Mini Project 1 Exercise 1')
@application.route('/ex2')
def exercise2():
return render_template('ex2.html', title='Mini Project 1 Exercise 2')The first route indicates when a user enter the URL with "/" or "/index" at the end, our web app will serve this request by calling index() function. The index() function will return a HTML response following a template called index.html. This file index.html can be found inside the templates folder.
mp_sort/
app/
__init__.py
routes.py
static/
templates/
index.html
ex1.html
ex2.htmlThe other two routes does the same by serving any request to "/ex1" and "/ex2". The templates for these two are provided inside the template folder.
For Exercise 1, you may want to look into the file ex1.html. Open this file in a text editor.
HTML code normally contains of two section, the header and the body. Each of the elements can be identified by their tags. The header element for ex1.html is as below:
<head>
<title>{{title}}</title>
<script type="module">import * as library from '/static/__target__/library.js'; window.library = library;</script>
</head>The <title> set the title of the page. Inside this tag we found {{title}}. The two curly braces is a Jinja template syntax that allow you to change the HTML code. It is a kind of variable that you can set. This variable title is actually set when render_template() is called in routes.py.
@application.route('/ex1')
def exercise1():
return render_template('ex1.html', title='Mini Project 1 Exercise 1')In this code, the variable title is set to Mini Project 1 Exercise 1.
The second tag <script ...>...</script> is to import our script. We will generate this Javascript file library.js from our Python library.py file inside the static folder.
mp_sort/
app/
__init__.py
routes.py
static/
library.pyAll your work for this mini project will be done inside library.py.
Javascript is the commonly used language for front-end web development. However, since this course only covers Python. We will use Transcrypt library which can compile and translate Python script into a Javascript file. To compile library.py, first we need to go into the static folder.
Windows:
> cd %USERPROFILE\Downloads\d2w_mini_projects\mp_sort\app\static
> dir
Unix/MacOS:
$ cd ~/Downloads/d2w_mini_projects/mp_sort/app/static
$ lsThe last command will list the file in that folder, and you should see:
library.pyRun Transcrypt on library.py:
python -m transcrypt -b -n libraryThe option -b means to build the javascript library. You can use --help for more options. Once it is done, you should be able to see a folder called __target__ containing several files. To see the content of that folder:
Windows:
> dir
> dir __target__
Unix/MacOS:
$ ls
$ ls __target__The output should be something like the following:
__target__/
library.js
library.project
math.js
org.transcrypt.__runtime__.js
random.jsYou should see library.js created inside this folder.
Now you are ready to run your web app in your local computer. To do so, you need to go back to the root directory. This can be done with the following:
Windows:
> cd ..\..
Unix/MacOS:
$ cd ../..which means go up the folder two times. Or, simply
Windows:
> cd %USERPROFILE\Downloads\d2w_mini_projects\mp_sort
Unix/MacOS:
$ cd ~/Downloads/d2w_mini_projects/mp_sort/You should see application.py in this root folder.
If you use Vocareum terminal, which is a linux terminal, to run your Flask application, you can do so by running the runflaskvoc.sh script. Before running this script, make sure the voc=True is set true in the following line inside mp_sort/app/__init__.py.
# set voc=False if you run on local computer
application.wsgi_app = PrefixMiddleware(application.wsgi_app, voc=True)Now, make sure you are inside the mp_sort folder by using the pwd command.
pwdUse ls to ensure that you see the runflaskvoc.sh in the current folder.
lsMake sure that the script is executable by running the following command.
chmod a+x ./runflaskvoc.shThe above script is to change the file to be executable for all users, group and owner.
To run the script, type the following.
./runflaskvoc.shOnce it is running, you can open another tab in your browser and type the following url: https://myserver.vocareum.com/.
To stop the web app type CTRL+C.
If you are using your own computer, make sure to change the flag voc=False in the following line inside mp_sort/app/__init__.py.
# set voc=False if you run on local computer
application.wsgi_app = PrefixMiddleware(application.wsgi_app, voc=False)Now, you can run Flask by typing:
flask runYou should see that some output will be thrown out, which one of them would be:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)Now you can open your browser at http://127.0.0.1:5000/ to see the web app. You should see something like the following:
To stop the web app type CTRL+C.
We will start with Exercise 1. Open ex1.html in your text editor. You should see these few lines of code:
<p>
<div id="generate">...</div>
<button onclick="library.generate()">Generate 10 numbers</button>
</p>We have two buttons. The first button is to generate 10 random numbers. The event onclick is binded to the function generate() in your library.py. Fill in this function to do the following:
- generate 10 random integers and store it into the global variable
array, - create a single string containing all the numbers. For example,
3, 1, 2, 4, 8, 6, 5, 9, 0, 7.
In ex1.html, you should also find the following lines:
<p>
<div id="sorted">...</div>
<button onclick="library.sortnumber1()">Sort</button>
</p>The second button is to sort the generated random numbers. The event onclick is binded to the function sortnumber1() in your library.py. Fill in this function to do the following:
- get the random numbers from
generateHTML id. Hint: usedocument.getElementById(id).innerHTMLto get the numbers, - remove the other characters and create a list of integers called
sortedarray, - sort the list using either bubble sort or insertion sort,
- create a single string containing the sorted numbers.
Now, let's move on to Exercise 2. In this exercise, instead of randomly generate the numbers, you will ask the user to enter the sequence of numbers using a Text Input.
Open ex2.html. You should see the following:
<p>
<div id="generate">Enter a sequence of numbers separated by a comma (","):</div>
## Enter the code here to create a Text Input. ##
</p>Search the internet to find out how to create a Text Input field and enter the code in the line indicated. Replace that line with the correct tag and code for Text Input. Name the text input numbers. You may want to also specify some default values to appear in the text input.
You should also see the following line:
<p>
<div id="sorted">...</div>
<button onclick="library.sortnumber2()">Sort</button>
</p>This button's even onclick is binded to sortnumber2() function in your library.py. Modify that function to do the following:
- get the string from the text input stored in the variable
value, - split the string using comma as a separator,
- remove all trailing whitespaces and convert them to numbers,
- sort the list of numbers,
- create a single string containing the sorted numbers and store it to
array_str.
The expected output for both exercises 1 and 2 can be found in this video.
