BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Flask app 5 - Word counts app with AngularJS front-end updates and submit error handling

Python-Flask.png




Bookmark and Share





bogotobogo.com site search:

Note

In the previous section (Flask app 4 : word counts with AngularJS polling the back-end), we setup the back-end polling and implemented basic AngularJS front-end.

In this tutorial, we'll update AngularJS for more user friendly front-end.

Here are the items that we need to do:

  1. We'll disable the submit button to prevent users from continually clicking while they are waiting for the submitted site to be counted.
  2. Then, while the application is counting the words, we'll add a display throbber/loading spinner where the word count list will go to show the user that there is activity happening in the back-end.
  3. Lastly, we'll display an error if the domain is unable to be reached.

Github source : akadrone-flask





Submit button change

Change the button in templates/index.html:

{% raw %}
<button type="submit" class="btn btn-primary" ng-disabled="loading">{{ submitButtonText }}</button>
{% endraw %}

Here, we added an ng-disabled directive and attached that to loading. This will disable the button when loading evaluates to true.

Then, we added a variable to display to the user called submitButtonText. This way we'll be able to change the text from Submit to Loading... so that the user knows what's going on.

We then wrapped the button in {% raw %} and {% endraw %} so that Jinja knows to evaluate this as raw HTML. If we don't do this, Flask will try to evaluate the {{ submitButtonText }} as a Jinja variable and Angular won't get a chance to evaluate it.


To make it work, we also need to change some lines in static/main.js. At the top of the WordcountController in main.js:

(function () {

  'use strict';

  angular.module('WordcountApp', [])

  .controller('WordcountController', ['$scope', '$log', '$http', '$timeout',
    function($scope, $log, $http, $timeout) {

	$scope.submitButtonText = 'Submit';
	$scope.loading = false;

    $scope.getResults = function() {

This sets the initial value of loading to false so that the button will not be disabled.

Another modification:

(function () {

  'use strict';

  angular.module('WordcountApp', [])

  .controller('WordcountController', ['$scope', '$log', '$http', '$timeout',
    function($scope, $log, $http, $timeout) {

	$scope.submitButtonText = 'Submit';
	$scope.loading = false;

    $scope.getResults = function() {

      $log.log('test');

      // get the URL from the input
      var userInput = $scope.url;

      // fire the API request
      $http.post('/start', {'url': userInput}).
        success(function(results) {
           $log.log(results);
	   getWordCount(results);
	   $scope.wordcounts = null;
	   $scope.loading = true;
	   $scope.submitButtonText = 'Loading...';
        }).
        error(function(error) {
          $log.log(error);
        });

    };

In the code, we set:

  1. wordcounts to null so that old values get cleared out.
  2. loading to true so that the loading button will be disabled via the ng-disabled directive we added to the HTML.
  3. submitButtonText to Loading... so that the user knows why the button is disabled.

The relevant change should be made for poller(). In other words, when the result is successful, we set loading back to false so that the button is enabled again and changed the button text back to Submit so the user knows they can submit a new URL.

    function getWordCount(jobID) {

      var timeout = '';

      var poller = function() {
        // fire another request
        $http.get('/results/'+jobID).
          success(function(data, status, headers, config) {
            if(status === 202) {
              $log.log(data, status);
            } else if (status === 200){
              $log.log(data);
              $scope.loading = false;
              $scope.submitButtonText = "Submit";
              $scope.wordcounts = data;
    	      $timeout.cancel(timeout);
              return false;
            }
            // continue to call the poller() function every 2 seconds
            // until the timeout is cancelled
            timeout = $timeout(poller, 2000);
          });
      };
      poller();
    }




Adding spinner to templates/index.html

Spinner let the user know what's going on while the code is counting words.

<!DOCTYPE html>
<html ng-app="WordcountApp">
  <head>
    <title>Wordcount</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" media="screen">

    <style>
      .container {
        max-width: 1000px;
      }
    </style>
  </head>
  <body ng-controller="WordcountController">
    <div class="container">
      <div class="row">
        <div class="col-sm-5 col-sm-offset-1">
          <h1>Wordcount</h1>
          <br>
            <form role="form" ng-submit="getResults()">
              <div class="form-group">
                <input type="text" name="url" class="form-control" id="url-box" placeholder="Enter URL..." style="max-width: 300px;" ng-model="url" required>
              </div>
              {% raw %}
              <button type="submit" class="btn btn-primary" ng-disabled="loading">{{ submitButtonText }}</button>
              {% endraw %}
            </form>
          <br>
          {% for error in errors %}
            <h4>{{ error }}</h4>
          {% endfor %}
          <br>
        </div>
        <div class="col-sm-5 col-sm-offset-1">
          <h2>Frequencies</h2>
          <br>
          <div id="results">           
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>Word</th>
                  <th>Count</th>
                </tr>
              </thead>
              <tbody>
              {% raw %}
                <tr ng-repeat="(key, val) in wordcounts">               
                  <td>{{key}}</td>
                  <td>{{val}}</td>                 
                </tr>
              {% endraw %}
              </tbody>
            </table>         
          </div>
        </div>
        <img class="col-sm-3 col-sm-offset-4" src="{{ url_for('static',
  filename='spinner.gif') }}" ng-show="loading">
      </div>
    </div>
    <br><br>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
    <script src="{{ url_for('static', filename='main.js') }}"></script>
  </body>
</html>

Note that we need to put spinner.gif into static directory.

We can also see that ng-show is attached to loading.





Error handling - a bad URL submit

We're using Bootstrap's alert class to show a warning dialog if the user submits a bad URL. By using Angular's ng-show directive we can only display the dialog when urlerror is true.

templates/index.html:

<!DOCTYPE html>
<html ng-app="WordcountApp">
  <head>
    <title>Wordcount</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" media="screen">

    <style>
      .container {
        max-width: 1000px;
      }
    </style>
  </head>
  <body ng-controller="WordcountController">
    <div class="container">
      <div class="row">
        <div class="col-sm-5 col-sm-offset-1">
          <h1>Wordcount</h1>
          <br>
          <form role="form" ng-submit="getResults()">
            <div class="form-group">
              <input type="text" name="url" class="form-control" id="url-box" placeholder="Enter URL..." style="max-width: 300px;" ng-model="url" required>
            </div>
            {% raw %}
            <button type="submit" class="btn btn-primary" ng-disabled="loading">{{ submitButtonText }}</button>
            {% endraw %}
          </form>
          <br>
          <div class="alert alert-danger" role="alert" ng-show='urlError'>
            <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
            <span class="sr-only">Error:</span>
            <span>There was an error submitting your URL.<br>
            Please check to make sure it is valid before trying again.</span>
          </div>
          <br>
        </div>
        <div class="col-sm-5 col-sm-offset-1">
          <h2>Frequencies</h2>
          <br>
          <div id="results">           
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>Word</th>
                  <th>Count</th>
                </tr>
              </thead>
              <tbody>
              {% raw %}
                <tr ng-repeat="(key, val) in wordcounts">               
                  <td>{{key}}</td>
                  <td>{{val}}</td>                 
                </tr>
              {% endraw %}
              </tbody>
            </table>         
          </div>
        </div>
        <img class="col-sm-3 col-sm-offset-4" src="{{ url_for('static',
  filename='spinner.gif') }}" ng-show="loading">
      </div>
    </div>
    <br><br>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
    <script src="{{ url_for('static', filename='main.js') }}"></script>
  </body>
</html>

static/main.js:

(function () {

  'use strict';

  angular.module('WordcountApp', [])

  .controller('WordcountController', ['$scope', '$log', '$http', '$timeout',
    function($scope, $log, $http, $timeout) {

	$scope.submitButtonText = 'Submit';
	$scope.loading = false;
	$scope.urlerror = false;

    $scope.getResults = function() {

      $log.log('test');

      // get the URL from the input
      var userInput = $scope.url;

      // fire the API request
      $http.post('/start', {'url': userInput}).
        success(function(results) {
		    $log.log(results);
		    getWordCount(results);
		    $scope.wordcounts = null;
		    $scope.loading = true;
		    $scope.submitButtonText = 'Loading...';
		    $scope.urlerror = false;
        }).
        error(function(error) {
          $log.log(error);
        });

    };

    function getWordCount(jobID) {

      var timeout = '';

      var poller = function() {
        // fire another request
        $http.get('/results/'+jobID).
          success(function(data, status, headers, config) {
            if(status === 202) {
              $log.log(data, status);
            } else if (status === 200){
              $log.log(data);
              $scope.loading = false;
              $scope.submitButtonText = "Submit";
              $scope.wordcounts = data;
    	      $timeout.cancel(timeout);
              return false;
            }
            // continue to call the poller() function every 2 seconds
            // until the timeout is cancelled
            timeout = $timeout(poller, 2000);
          }).
          error(function(error) {
	    $log.log(error);
	    $scope.loading = false;
	    $scope.submitButtonText = "Submit";
	    $scope.urlerror = true;
	  });
      };
      poller();
    }

  }]);

}());

We've made the user interface more user friendly so that the user knows what is happening while we are running the word count functionality behind the scenes.


Let's test out our new implementations.

Loading...

yahoo-loading.png

Loading finished:

yahoo-loaded.png



Apache proxy setup - local

If we want to access the page with port 80, we can setup proxy. For Apache, it looks like this:

<VirtualHost *:80>

     ServerName www.akadrone.example.com
     ServerAlias akadrone.example.com

     ProxyPreserveHost On

     ProxyPass / http://127.0.0.1:5000/
     #ProxyPassReverse / http://127.0.0.1:5000/

     ErrorLog /var/www/akadrone.com/logs/error.log
     CustomLog /var/www/akadrone.com/logs/access.log combined
     LogLevel warn
     ServerSignature Off

</VirtualHost>

Run gunicorn.sh:

$ ./gunicorn_aka.sh

where the file (gunicorn_aka.sh) should look like this:

source /home/k/MySites/akadrone/venv/bin/activate
python /home/k/MySites/akadrone/worker.py &
exec gunicorn -w 4 -b 127.0.0.1:5000 aka:app

As we can see from the script, we're running two programs: worker.py and our app (aka.py via gunicorn).


Then, we can access our app either with:

localhost:5000

or

akadrone.example.com:80


akadrone-example-com.png

To run in background, we can use pm2:

$ pm2 start gunicorn_aka.sh
pm2-aka-run.png



On production server

Here are the screen shots from akadrone.com deployed on CentOS 7 server:

Loading-akadrone.png
Loaded-akadrone.png

We used pm2:

(venv)[sfvue@sf akadrone]$ pm2 start ./gunicorn_aka.sh

with gunicorn.sh:

source /home/k/MySites/akadrone/venv/bin/activate
/home/sfvue/MySites/akadrone/venv/bin/python /home/sfvue/MySites/akadrone/worker.py &
/home/sfvue/MySites/akadrone/venv/bin/gunicorn -w 1 -b 127.0.0.1:5000 aka:app

Apache proxy config (/etc/httpd/sites-available/akadrone.com.conf):

<VirtualHost *:80>

     ServerName www.akadrone.com
     ServerAlias akadrone.com

     ProxyPreserveHost On

     ProxyPass / http://127.0.0.1:5000/
     #ProxyPassReverse / http://127.0.0.1:5000/

     ErrorLog /var/www/akadrone.com/logs/error.log
     CustomLog /var/www/akadrone.com/logs/access.log combined
     LogLevel warn
     ServerSignature Off

</VirtualHost>




References

Flask by Example - Part7









Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong








Flask



Deploying Flask Hello World App with Apache WSGI on Ubuntu 14

Flask Micro blog "Admin App" with Postgresql

Flask "Blog App" with MongoDB - Part 1 (Local via Flask server)

Flask "Blog App" with MongoDB on Ubuntu 14 - Part 2 (Local Apache WSGI)

Flask "Blog App" with MongoDB on CentOS 7 - Part 3 (Production Apache WSGI )

Flask word count app 1 with PostgreSQL and Flask-SQLAlchemy

Flask word count app 2 via BeautifulSoup, and Natural Language Toolkit (NLTK) with Gunicorn/PM2/Apache

Flask word count app 3 with Redis task queue

Flask word count app 4 with AngularJS polling the back-end

Flask word count app 5 with AngularJS front-end updates and submit error handling

Flask word count app 0 - Errors and Fixes

Flask with Embedded Machine Learning I : Serializing with pickle and DB setup

Flask with Embedded Machine Learning II : Basic Flask App

Flask with Embedded Machine Learning III : Embedding Classifier

Flask with Embedded Machine Learning IV : Deploy

Flask with Embedded Machine Learning V : Updating the classifier

Flask AJAX with jQuery

Flask blog app with Dashboard 1 - SignUp page

Flask blog app with Dashboard 2 - Sign-In / Sign-Out

Flask blog app with Dashboard 3 - Adding blog post item

Flask blog app with Dashboard 4 - Update / Delete

Flask blog app with Dashboard 5 - Uploading an image

Flask blog app with Dashboard 6 - Dash board

Flask blog app with Dashboard 7 - Like button

Flask blog app with Dashboard 8 - Deploy

Flask blog app with Dashboard - Appendix (tables and mysql stored procedures/functions

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master