Python Web Application Development Using Flask and MySQL

Python is one of the widely used languages for web development and Django is the de facto web development framework. But still there are some other frameworks which though not much popular, but still are appreciated by folks who have used it. One such web development framework which is gaining popularity is Flask.

Developing a Web Application with Flask
Flask is a microframework for Python based on Werkzeug, the python WSGI Utility Library and Jinja2, a template engine for Python. Flask has just the bare essentials to get you started with web development without much hassle. To get started with development in Flask :
  • Make sure you have Python installed.
  • Install Flask using Pip pip install Flask
  • Make sure you have MySQL installed.
Now, suppose we are developing a login page for a web application. From the terminal, create a directory for our application.
mkdir FlaskApp
cd FlaskApp
Inside the FlaskApp directory lets create a This is how it looks like
from flask import Flask
app = Flask(__name__)

def hello():
    return "Welcome to Python Flask App!"

if __name__ == "__main__":
In the above code, we have simply defined a route / and the function to call hello. Now, time to run the application. From the terminal, type

It would show Browse the above URL and it would display the message Welcome to Python Flask App!.
Congrats on running you First Python Flask App !!

Connecting MySQL and Flask
In order to connect Flask and MySQL, we would need to install Flask-MySQL which is an extension, which allows us to connect to MySQL database. In order to install that get to your terminal and type
mysql -u  -p
and then enter your password when prompted. Now, create a new database called EmpData and a table called User with 3 columns - UserId, Username, Password.


mysql> CREATE TABLE User(
 userName VARCHAR(100) NOT NULL,
 password VARCHAR(40) NOT NULL,
Now, insert some data into the table User
 mysql> insert into User values('','Admin','admin');
So, we are all set with the MySQL database. Now, let's go back to the and try to connect MySQL using flask-mysql.
First of all, initialize the extension by importing it in as shown below:
from flaskext.mysql import MySQL
Now, we need to configure the database host, database name, user name and password into our Simply add the config keys and modify the as follows:

from flask import Flask
from flaskext.mysql import MySQL

mysql = MySQL()
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'EmpData'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

def hello():
    return "Welcome to Python Flask App!"

if __name__ == "__main__":

We will be accessing the data from MySQL using cursor. We can create one using our mysql object. We would also be adding another method called Authenticate in order to validate login process. So, lets add the following code:

def Authenticate():
    username = request.args.get('UserName')
    password = request.args.get('Password')
    cursor = mysql.connect().cursor()
    cursor.execute("SELECT * from User where Username='" + username + "' and Password='" + password + "'")
    data = cursor.fetchone()
    if data is None:
     return "Username or Password is wrong"
     return "Logged in successfully"

At this point, we are almost done with out coding and now its time to test our app. Let's run it by typing
And browse to since our Authenticate methods expects a UserName and Password to validate. Browsing the above url it shows :
Username or Password is wrong
which is obvious. So let's now try to browse using the correct username and password and we get
Logged in successfully
Hence It Worked!!

Flask is a simple framework for Python web application development. There are a number of different frameworks available for the same purpose. But it varies from individual to individual and depends on how one picks up a particular framework. But for beginners, I think Flask gives a better understanding of basics of WSGI and Python web development in particular.

A Simple Phonegap Application in Android For Adding Two Numbers

This is an Phonegap application targeting Android and hence developed using Eclipse.Its a beginner's application and will be helpful for any one who just started with Phonegap.

So let's get started.First of all create an android application in android.Let's call it AddNumber.
Now go to the assets folder and create a www folder if its not already there. Inside the www folder create a file called index.html .

Now we'll be using jQuery Mobile template for this app.So lets build the html page using jQuery mobile.If you are not familiar with jQuery mobile don't its pretty straight forward, just have a look jQueryMobile .
Now here goes our index.html code.

<!DOCTYPE html>

  <title>Page Title</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="" />
  <script src=""></script>
  <script src=""></script>

  <div data-role="page">
    <div data-role="header">
      <h1>Add Two Number</h1>
    <!-- /header -->
    <div data-role="content">
      <p>Hello Phonegap.</p>
    <!-- /content -->
    <div data-role="footer">
      <h4>Page Footer</h4>
    <!-- /footer -->
  <!-- /page -->

Ok so that is the html code for our index.html.The comments are quite self explanatory i believe.It has three portion the header portion,content portion and the footer portion. Now lets bring Phonegap into the picture.Add cordova-2.9.0.jar into libs folder.Right click and do add to build path.Now add cordova.js into assets/www/js/.And include the script into the index.html head
<script src="js/cordova.js"></script>
Now copy the xml folder from Phonegap zip to res/ .We also need to include some permission to the AndroidManifest.xml file

<uses-permission android:name="android.permission.CAMERA">
<uses-permission android:name="android.permission.VIBRATE">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS">
<uses-permission android:name="android.permission.READ_PHONE_STATE">
<uses-permission android:name="android.permission.INTERNET">
<uses-permission android:name="android.permission.RECEIVE_SMS">
<uses-permission android:name="android.permission.RECORD_AUDIO">
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS">
<uses-permission android:name="android.permission.READ_CONTACTS">
<uses-permission android:name="android.permission.WRITE_CONTACTS">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"> 
<uses-permission android:name="android.permission.GET_ACCOUNTS">
<uses-permission android:name="android.permission.BROADCAST_STICKY">
Also make sure that your OnCreate method in looks like

public void onCreate(Bundle savedInstanceState) {
this.setIntegerProperty("loadUrlTimeoutValue", 60000);        super.loadUrl("file:///android_asset/www/index.html",6000);
 Now lets just simple run the app and see if we are on the right track.So what we get is below :

Now lets modify the content portion to include two text boxes and a button.Modify the content portion as below:

<div data-role="content">
  <label for="txtNum1">Num 1:</label>
  <input id="txtNum1" name="txtNum1" type="text" value="" />
  <label for="txtNum2">Num 2:</label>
  <input id="txtNum2" name="txtNum2" type="text" value="" /> <a data-inline="true" data-role="button" onclick="Add();">Add </a>

Also include a script to Add the input from text boxes

  function Add() {
    var v1 = document.getElementById('txtNum1').value;
    var v2 = document.getElementById('txtNum2').value;
    if (v1 == "" || v2 == "") {
      alert('Both Values Required');
    } else {
      alert(Number(v1) + Number(v2));

Now try running the Application and you will get to see some thing like below

Ok so that was a simple Phonegap Application to Add Two Numbers on Android.
Hope it would be helpful.
In our next tutorial i would show how to use a javascript framework like Knockoutjs to build Phonegap applications.

Warning : Cannot read property 'min' of undefined Used grunt --force

Gruntjs is a javascript task runner which makes most of the mudane tasks like minification, compilation ,testing etc automated.
While trying to make the minification thing working i encountered an errors which was quite silly and i spent quite some time searching for solutions before i finally figured it out.

So what i  was trying to do, was to compress a normal javascript file using Grunt.So as per the documentation first i installed grunt-cli ( i already have nodejs and npm installed )

npm install -g grunt-cli
After that create package.json file
  "name": "hello",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-jshint": "~0.6.0",
    "grunt-contrib-nodeunit": "~0.2.0",
    "grunt-contrib-uglify": "~0.2.2"
After that we need to install all the dependencies specified in the package.json
npm install
After that create Gruntfile.js in the app directory
module.exports = function(grunt) {

  // Project configuration.
    pkg: grunt.file.readJSON('package.json'),
    uglify: {
      build: {
        src: 'src/hello.js',
        dest: 'build/hello.min.js'

  // Load the plugin that provides the "uglify" task.

  // Default task(s).
  grunt.registerTask('default', ['uglify']);

Now run
grunt or grunt --force
So as per the grunt command the file hello.js in src must minify to hello.min.js in build folder.But instead i got an error as shown below

Warning: Uglification failed. Used --force, continuing.
Warning: Cannot read property 'min' of undefined Used --force, continuing.

Done, but with warnings.
The issue was quite silly.It was a bug in the file that i was trying to minify, hello.js. In order to verify if there is any thing wrong with the installation process then try running
grunt --verbose --stack --debug
if you want to verify if there is any issue with your js file which you are trying to minify use this web implementation of Uglify