2

enter image description hereenter image description here

<div >
    <table class="table">
    <thead>
      <th>Name</th>
      <th>Roll</th>
      <th>Town</th>
      <th>Class</th>
    </thead>

    <tr ng-repeat="c in contacts.data |  filter:query"><button ng-hide="editMode" ng-click="modifyDetails()">Edit</button><button ng-show="editMode" ng-click="modifyDetails()">Done</button>

      <td><span ng-model="studName" ng-hide="editMode">{{ c.Name }}</span><input ng-show="editMode" ng-model="c.Name"> </td>
      <td><span ng-model="studRoll" ng-hide="editMode">{{ c.Roll }}</span><input ng-show="editMode" ng-model="c.Roll"> </td>
      <td><span ng-model="studTown" ng-hide="editMode">{{ c.Town }}</span><input ng-show="editMode" ng-model="c.Town"></td>
      <td><span ng-model="studClass" ng-hide="editMode">{{ c.Class }}</span><input ng-show="editMode" ng-model="c.Class"></td>

    </tr>
    </table>



var module = angular.module("djangoApp", [])
module.controller("siaMyCtrl", siaMyCtrl)
function siaMyCtrl($scope, $http) {

$scope.editMode = false

$http.post('http://10.2.10.55:5000/')
.then(successCallback, errorCallback)
function successCallback(response) {
$scope.contacts = response;


}
function errorCallback(error) {

}
$scope.modifyDetails = function () {
   $scope.editMode = ! $scope.editMode
}
$scope.addDetails = function () {

}}

after I save it changes the value but when I refresh It again changes to the earlier value.All these data I am getting from localhost.I want to update information on server(localhost) how can I do that

Please help me I am a beginner

   from flask import Flask, jsonify, render_template, request
   import MySQLdb, json

   app = Flask(__name__)

   @app.route('/',methods=['GET', 'POST'])
   def process():

    name1=request.form.get('name')
    roll1=request.form.get('num')
    town1=request.form.get('town')
    class1=request.form.get('cls')

    db = MySQLdb.connect("localhost","root","test123","test" )
    with db:
        cursor = db.cursor()

        sql = "SELECT * FROM geninfo1"

        cursor.execute(sql)
        rows = cursor.fetchall()
        x=[]
        for i, item in enumerate(rows):

            x.append({
                'id':rows[i][0],
                'Name':rows[i][1],
                'Class':rows[i][3],
                'Town':rows[i][4],
                'Roll':rows[i][2]
                })
    return jsonify(x)


   #     return render_template('index.html', Name=name1) 
    db.close()
    if __name__=='__main__':
       app.run(host="10.2.10.55", port=5000, debug=True)
shaunhusain
  • 19,630
  • 4
  • 38
  • 51
Lalit Vyas
  • 221
  • 5
  • 19
  • AngularJS is nothing more than a front end framework it only runs in the browser and has no direct access to a database. You need some sort of server side technology (C#, nodejs, php/laravel/lumen, java/sprint, etc. etc.) that handles accessing data on the server and sending it out to the client. To reiterate AngularJS is just a bunch of JS functions and only runs in the browser. Have you looked at $http service in angularjs? (copy/pasted this comment :) ) – shaunhusain Jan 01 '18 at 08:36
  • You need to make a call to database on every refresh....If data is present then show it or else show blank fields... – Rohan Kawade Jan 01 '18 at 08:36
  • http://10.2.10.55:5000/ <-- I presume this is just returning some static JSON data, instead you would use the $http.post and $http.get methods to call URLs that actually fetch data from a database or put data into a database. The particular language or framework or way you do that is independent of Angular itself. – shaunhusain Jan 01 '18 at 08:38
  • @shaunhusain can it be done by python? – Lalit Vyas Jan 01 '18 at 09:14
  • Sure python is an option I am not a big python developer myself so this might be a bad recommendation but have heard of people using "bottle" in python for setting up an API https://bottlepy.org/docs/dev/ Things to look for are easy way to setup "routes" or URL handlers and ways to setup database connections and do "CRUD" operations on a database, the generic term is usually an "ORM" but other things can work depending on what you need. This looks like a good place to start https://www.codementor.io/sagaragarwal94/building-a-basic-restful-api-in-python-58k02xsiq – shaunhusain Jan 01 '18 at 09:18
  • @shaunhusain and how can I connect it with angular – Lalit Vyas Jan 01 '18 at 09:52
  • Once you have endpoints setup you can use $http.post and $http.get methods in angular to post and get data to/from the server respectively. – shaunhusain Jan 01 '18 at 09:53
  • I have created one using flask but don't know how to consume it with angular – Lalit Vyas Jan 01 '18 at 09:53
  • Show your flask code as well and add the flask tag to the questions if you can. – shaunhusain Jan 01 '18 at 09:53
  • @shaunhusain please look – Lalit Vyas Jan 01 '18 at 09:58
  • Think what you want to do here is copy the whole route/function that handles it and make only one do the GET and the other do the POST, for the POST one have do an insert using the data sent to it (angular will send the payload/data as JSON so you'll need to decode the incoming JSON string then use it to create a query). For security purposes look into "SQL injection" and how to avoid it, typically using parameterized queries. The function you have defined is fine for GET you just want the POST one to do an insert. From angular you'll use $http.get to fetch and $http.post(url,data) to send. – shaunhusain Jan 01 '18 at 10:03
  • you mean to copy and paste the flask app code in js file – Lalit Vyas Jan 01 '18 at 10:06
  • can you show me by some example – Lalit Vyas Jan 01 '18 at 10:06
  • No I just mean copy/paste the part of the flask... I can do some pseudo code or comments but don't know Python well enough to fill in the details there without doing a lot of searching. In angular what you're doing is mostly fine but you would use .get on $http instead of .post to make a GET request from the browser, on the server side you want to have two different functions that handle the different GET or POST requests from the client. In your modifyDetails function you would just call ng-click="modifyDetails(c)" then use `$http.post("http://10.2.10.55:5000/", c)` – shaunhusain Jan 01 '18 at 10:08

1 Answers1

2

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

shaunhusain
  • 19,630
  • 4
  • 38
  • 51
  • @sshaunhusain not able to post – Lalit Vyas Jan 01 '18 at 14:18
  • @LALITVYAS sorry not clear what you mean can you elaborate? What happens when you attempt to post? did you change the code per above? looks like to get the data from the JSON that angular will send you'd want to use this method on the request object instead of trying to reference the .form http://flask.pocoo.org/docs/0.12/api/#flask.Request.get_json – shaunhusain Jan 01 '18 at 23:37
  • @LALITVYAS updated the code to have a full example that I actually tested locally and works. Hadn't ever done anything this complete with python so was fun to poke around and had surprisingly little issue getting this up and running (granted I'm used to lots of common hang ups with using angular and other back end frameworks) – shaunhusain Jan 02 '18 at 11:15
  • No problem it was a good chance for me to try out some things in python. I'll probably continue with some more concise versions on the blog post or make some more blog posts to cover those topics (using some libraries for doing the REST api maybe this http://python-eve.org/rest_api_for_humans.html or something similar) If this actually answers your question don't forget to hit the check mark too, if not let me know where you're hung up and can try to help. – shaunhusain Jan 04 '18 at 05:42