Update decided to familiarize myself with Flask and give a proper full answer here:
Database Setup (SQL run in terminal)
# mysql -u root -p
CREATE DATABASE pythontesting;
USE DATABASE pythontesting;
CREATE TABLE students (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(255),
class varchar(255),
town varchar(255),
roll varchar(255),
PRIMARY KEY (id)
);
Python code hello.py
# Prerequisites: Python 2.7, Flask 0.12.2, Python-Mysql connector
# sudo pip install Flask
# sudo apt install python-mysqldb
# sudo pip install -U flask-cors
# Run with:
# FLASK_APP=hello.py flask run
# http://flask.pocoo.org/docs/0.12/api/#flask.request
from flask import Flask,request
# https://pypi.python.org/pypi/Flask-Cors
from flask_cors import CORS, cross_origin
# https://pythonspot.com/mysql-with-python/
import MySQLdb
import json
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}}, methods=['GET', 'POST', 'DELETE', 'PUT'])
@app.route("/api/v1/students",methods=['GET'])
def getStudents():
db = MySQLdb.connect(host="localhost", # your host
user="root", # username
passwd="password", # password
db="pythontesting") # name of the database
# Create a Cursor object to execute queries.
cur = db.cursor()
# Select data from table using SQL query.
cur.execute("SELECT * FROM students")
rows = cur.fetchall()
row_headers=[x[0] for x in cur.description] #this will extract row headers
json_data=[]
for result in rows:
json_data.append(dict(zip(row_headers,result)))
return json.dumps(json_data)
@app.route("/api/v1/students",methods=['POST'])
def createStudent():
requestData = request.get_json();
db = MySQLdb.connect(host="localhost", # your host
user="root", # username
passwd="password", # password
db="pythontesting") # name of the database
# Create a Cursor object to execute queries.
cur = db.cursor()
# https://stackoverflow.com/questions/7929364/python-best-practice-and-securest-to-connect-to-mysql-and-execute-queries
# Select data from table using SQL query.
cur.execute("INSERT INTO students (name, class, town, roll) VALUES (%s, %s, %s, %s)", (requestData["name"],requestData["class"],requestData["town"],requestData["roll"]))
db.commit()
return "OK"
@app.route("/api/v1/students",methods=['PUT'])
def updateStudents():
requestData = request.get_json();
db = MySQLdb.connect(host="localhost", # your host
user="root", # username
passwd="password", # password
db="pythontesting") # name of the database
# Create a Cursor object to execute queries.
cur = db.cursor()
# https://stackoverflow.com/questions/7929364/python-best-practice-and-securest-to-connect-to-mysql-and-execute-queries
# Select data from table using SQL query.
cur.execute("UPDATE students SET name=%s, class=%s, town=%s, roll=%s WHERE id=%s", (requestData["name"],requestData["class"],requestData["town"],requestData["roll"],requestData["id"]))
db.commit()
return "OK"
@app.route("/api/v1/students/<int:student_id>",methods=['DELETE'])
def deleteStudent(student_id):
requestData = request.get_json();
db = MySQLdb.connect(host="localhost", # your host
user="root", # username
passwd="password", # password
db="pythontesting") # name of the database
# Create a Cursor object to execute queries.
cur = db.cursor()
# Select data from table using SQL query.
cur.execute("DELETE FROM students WHERE id=%s", (student_id,))
db.commit()
return "OK"
HTML for front end index.html
<!DOCTYPE html>
<html ng-app="djangoApp">
<head>
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js"></script>
<script type="text/javascript" src="mainApp.js"></script>
<title></title>
</head>
<body ng-controller="siaMyCtrl as smc">
<button ng-hide="c.editMode" ng-click="smc.model.showAddRow = true">Add</button>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Roll</th>
<th>Town</th>
<th>Class</th>
<th></th>
</tr>
</thead>
<!-- Not valid HTML to have a form here but works -->
<form ng-submit="smc.create(smc.model.newStudent)">
<tr ng-show="smc.model.showAddRow">
<td><input ng-model="smc.model.newStudent.name"> </td>
<td><input ng-model="smc.model.newStudent.roll"> </td>
<td><input ng-model="smc.model.newStudent.town"></td>
<td><input ng-model="smc.model.newStudent.class"></td>
<td><button>Save</button></td>
</tr>
</form>
<tr
ng-repeat="c in smc.StudentsService.loadedStudents | filter:query">
<td><span ng-model="studName" ng-hide="c.editMode">{{ c.name }}</span><input ng-show="c.editMode" ng-model="c.name"> </td>
<td><span ng-model="studRoll" ng-hide="c.editMode">{{ c.roll }}</span><input ng-show="c.editMode" ng-model="c.roll"> </td>
<td><span ng-model="studTown" ng-hide="c.editMode">{{ c.town }}</span><input ng-show="c.editMode" ng-model="c.town"></td>
<td><span ng-model="studClass" ng-hide="c.editMode">{{ c.class }}</span><input ng-show="c.editMode" ng-model="c.class"></td>
<td>
<button ng-hide="c.editMode" ng-click="smc.edit(c)">Edit</button>
<button ng-hide="c.editMode" ng-click="smc.StudentsService.deleteStudent(c)">Delete</button>
<button ng-show="c.editMode" ng-click="smc.update(c)">Save</button>
<button ng-show="c.editMode" ng-click="smc.cancel(c)">Cancel</button>
</td>
</tr>
</table>
</body>
</html>
Script for angular execution mainApp.js
(function(){
var module = angular.module("djangoApp", []);
module.controller("siaMyCtrl", siaMyCtrl)
function siaMyCtrl(StudentsService) {
var ctrl = this;
ctrl.StudentsService = StudentsService;
ctrl.model = {
};
ctrl.modifyDetails = function (c) {
c.editMode = ! c.editMode
}
ctrl.update = function(student){
StudentsService.updateStudent(student)
.then(function(){
ctrl.model.showAddRow = false;
});
}
ctrl.edit = function(student){
student.editMode = true;
student.originalStudent = angular.copy(student);
}
ctrl.cancel = function(student){
angular.copy(student.originalStudent, student);
student.editMode = false;
student.originalStudent = null;
}
ctrl.create = function (student) {
StudentsService.createStudent(student)
.then(function(){
ctrl.model.showAddRow = false;
});
}
}
module.value('APIBase', 'http://127.0.0.1:5000/api/v1/');
module.service('StudentsService', function($http, APIBase){
var studentsURL = APIBase+'students';
var studentsService = {
loadedStudents: []
};
studentsService.readStudents = function(){
function successCallback(response) {
studentsService.loadedStudents = response.data;
}
return $http.get(studentsURL)
.then(successCallback, console.error)
}
studentsService.createStudent = function(student){
return $http.post(studentsURL, student).then(function(){
studentsService.readStudents();
})
}
//Notice same as create but uses PUT
studentsService.updateStudent = function(student){
return $http.put(studentsURL, student).then(function(){
studentsService.readStudents();
})
}
// Notice same as create but uses DELETE...
// you can also use a $resource to wrap this up but it uses $http under
// the hood so good to see how this works too, $http wraps the browsers
// regular XHR object and triggers angular view updates when data comes back
studentsService.deleteStudent = function(student){
return $http.delete(studentsURL+'/'+student.id).then(function(){
studentsService.readStudents();
})
}
studentsService.readStudents(); // Initialize the service with data
return studentsService;
})
})();
Wrote this up into a blog entry here so I can add details maybe not directly related to the original question:
https://www.intellectual-tech.com/blog/full-stack-python-angular-rest-api