Flask: Python web Framework

Live Flask API Demo

Source: https://praison.com/flaskapi/

Basic

from flask import Flask
app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello, World!'

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

Integrating MySQL

class DataMySQL(Resource):
    def get(self):
        mycursor = mydb.cursor()
        mycursor.execute("select * from data")
        row_headers=[x[0] for x in mycursor.description] #this will extract row headers
        rv = mycursor.fetchall()
        json_data=[]
        for result in rv:
            json_data.append(dict(zip(row_headers,result)))        
        result = json.dumps(json_data, indent=4, sort_keys=True, default=str)
        return jsonify(result)

MySQL Connection

mydb = mysql.connector.connect(
  host="localhost",
  user="xxxx",
  passwd="xxxx",
  database="data"
)

mycursor = mydb.cursor()

Integrating Sqlite

class DataSqlite(Resource):
    def get(self):
        conn = db_connect.connect()
        query = conn.execute("select * from data;")
        result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}
        return jsonify(result)

SQLite Connection

db_connect = create_engine('sqlite:///data.db')

Connecting to Flask

app = Flask(__name__)
api = Api(app)
api.add_resource(DataMySQL, '/datamysql') # Route_MySQL_Data
api.add_resource(DataSqlite, '/datasqlite') # Route_Sqlite_Data

Initialise

from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps
import mysql.connector
import json
from bson import json_util # pip install pymongo

Prepare Virtual Environment

$ virtualenv venv
$ source venv/bin/activate
$ pip install flask flask-jsonpify flask-sqlalchemy flask-restful pymongo
$ pip freeze
$ sqlite3 data.db

Run Server

$ nohup python server.py & # To Initiate
$ ps ax | grep server.py # To Analyse
$ kill [PID] # To Stop