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 with Embedded Machine Learning II : Basic Flask App

Python-Flask.png




Bookmark and Share





bogotobogo.com site search:


Note

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

Now that we have prepared the code to classify movie reviews in the previous section, we're going to work on our Flask web application. In this section, we'll setup a basic Flask app which can be found any introductory course for building a Flask app.

Our main app with embedded machine learning classification will be resumed in next article (Flask with Embedded Machine Learning III : Embedding Classifier) but not in this page.


Let's install Flask:

$ sudo install it via pip






Flask app

Here are the files for our basic app with a domain name ahaman.com:

file-directory-structure.png

The app.py has the main code that will be executed by the Python to run the Flask application. The templates directory is the directory where Flask will look for static HTML files to render.





app.py

We run our application as a single module and initializes a new Flask instance with the argument __name__ to let Flask know that it can find the HTML template folder, templates, in the same directory where our module (app.py) is located:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
	return render_template('first_app.html')

if __name__ == '__main__':
	app.run()

In the code, we used the route decorator. @app.route('/'), to specify the URL that should trigger the execution of the index function. Here, our index function simply renders the HTML file templates/first_app.html.

Then, we used the run() function to only run the application on the server when this script is directly executed by the Python interpreter (not being imported), which we ensured using the if statement with __name__ == '__main__'.





templates/first_app.html

Here is the basic html file:

<!doctype html>
<html>
<head>
	<title>My first app</title>
</head>
<body>
	<div>This is my first Flask app!</div>
</body>
</html>




Local run

Like other web frameworks, Flask allows us to run our apps locally, which is useful for developing and testing web applications before we deploy them on a public web server.

Let's start our web application:

$ python app.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

We can now enter this address in our web browser to see the web application in action. If everything has executed correctly, we should now see the following:

MyFirstAppFlask.png



WTForms : validation and rendering library for python web development

We're going to extend our basic Flask web application via WTForms library and learn how to collect data from a user using the library.

WTForms is a flexible forms validation and rendering library for python web development.

We can install it using pip:

$ sudo pip install wtforms

Here is our new directory structure:

new-directory-structure.png

We need to modify the app.py file.

Using wtforms, we extend the index() function with a text field that we will embed in our start page using the TextAreaField class, which automatically checks whether a user has provided valid input text or not.

Here is the file:

from flask import Flask, render_template, request
from wtforms import Form, TextAreaField, validators

app = Flask(__name__)

class HelloForm(Form):
	sayhello = TextAreaField('',[validators.DataRequired()])

@app.route('/')
def index():
	form = HelloForm(request.form)
	return render_template('first_app.html', form=form)

@app.route('/hello', methods=['POST'])
def hello():
	form = HelloForm(request.form)
	if request.method == 'POST' and form.validate():
		name = request.form['sayhello']
		return render_template('hello.html', name=name)
	return render_template('first_app.html', form=form)

if __name__ == '__main__':
	app.run(debug=True)

We also defined a new function, hello(), which will render an HTML page hello.html if the form has been validated. Note that we used the POST method to transport the form data to the server in the message body.

Lastly, by setting the argument debug=True inside the app.run() method so that it can help for developing new web applications.





templates/_formhelpers.html

Now, we're going to implement a generic macro in the file _formhelpers.html via the Jinja2 templating engine, which we will later import in our first_app.html file to render the text field:

{% macro render_field(field) %}
	<dt>{{ field.label }}
	<dd>{{ field(**kwargs)|safe }}
	{% if field.errors %}
		<ul class=errors>
		{% for error in field.errors %}
			<li>{{ error }}</li>
		{% endfor %}
		</ul>
	{% endif %}
	</dd>
{% endmacro %}




static/style.css

We'll have a very simple css file which doubles the font size of our HTML body elements:

body {
   font-size: 2em;
}




templates/first_app.html

Out modified first_app.html file that will now render a text form where a user can enter a name:

<!doctype html>
<html>
<head>
	<title>First app</title>
	<link rel="stylesheet" href="{{ url_for('static',
		filename='style.css') }}">
</head>

<body>
	{% from "_formhelpers.html" import render_field %}
	<div>What's your name?</div>
	<form method=post action="/hello">
		<dl>
			{{ render_field(form.sayhello) }}
		</dl>
		<input type=submit value='Say Hello' name='submit_btn'>
	</form>
</body>

</html>

In the body section, we imported the form macro from _formhelpers.html and we rendered the sayhello form that we specified in the app.py file. Also, we added a button to the same form element so that a user can submit the text field entry.





templates/hello.html

We create a hello.html file that will be rendered via the line return render_template('hello.html', name=name) inside the hello() function, which we defined in the app.py script to display the text that a user submitted via the text field. Here is the code:

<!doctype html>
<html>
<head>
	<title>First app</title>
	<link rel="stylesheet" href="{{ url_for('static',
		filename='style.css') }}">
</head>

<body>
	<div>Hello {{ name }}</div>
</body>
</html>




Run modified app.py

We can run our app again:

Rerun-App-1.png
Rerun-App1-SayHello-K-Hong.png



Github source

Source is available from ahaman-Flask-with-Machine-Learning-Sentiment-Analysis





Refs

Python Machine Learning, Sebastian Raschka





Next

Flask with Embedded Machine Learning III : Embedding Classifier









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