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 hello.py. This is how it looks like
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Welcome to Python Flask App!"


if __name__ == "__main__":
    app.run()
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
python hello.py

It would show http://127.0.0.1:5000/. 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 DATABASE EmpData;

mysql> CREATE TABLE User(
 userId INT NOT NULL AUTO_INCREMENT,
 userName VARCHAR(100) NOT NULL,
 password VARCHAR(40) NOT NULL,
 PRIMARY KEY(userId)
 );
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 hello.py and try to connect MySQL using flask-mysql.
First of all, initialize the extension by importing it in hello.py as shown below:
from flaskext.mysql import MySQL
Now, we need to configure the database host, database name, user name and password into our hello.py. Simply add the config keys and modify the hello.py 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'
mysql.init_app(app)

@app.route("/")
def hello():
    return "Welcome to Python Flask App!"

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

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:

@app.route("/Authenticate")
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"
    else:
     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
python hello.py
And browse to http://127.0.0.1:5000/Authenticate?UserName=jay&Password=jay 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 http://127.0.0.1:5000/Authenticate?UserName=Admin&Password=admin and we get
Logged in successfully
Hence It Worked!!

Conclusion
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>
<html>

<head>
  <title>Page Title</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
</head>

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

</html>
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">
</uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission>
Also make sure that your OnCreate method in Activity.java looks like

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(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>
</div>

Also include a script to Add the input from text boxes



<script>
  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));
    }
  }
</script>

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.
  grunt.initConfig({
    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.
  grunt.loadNpmTasks('grunt-contrib-uglify');

  // 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