Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python创建RESTAPI(保存和加载数据)并使用AngularJS使用它?_Angularjs_Flask - Fatal编程技术网

如何使用Python创建RESTAPI(保存和加载数据)并使用AngularJS使用它?

如何使用Python创建RESTAPI(保存和加载数据)并使用AngularJS使用它?,angularjs,flask,Angularjs,Flask,Update决定熟悉Flask,并在此处给出正确的完整答案: 数据库设置(SQL运行终端) Python代码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=hell


Update决定熟悉Flask,并在此处给出正确的完整答案:

数据库设置(SQL运行终端)

Python代码
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"
角度执行脚本
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;
  })


})();
我在这里写了一篇博文,这样我就可以添加可能与原始问题没有直接关系的细节:


AngularJS只不过是一个前端框架,它只能在浏览器中运行,不能直接访问数据库。您需要某种服务器端技术(C#、nodejs、php/laravel/lumen、java/sprint等)来处理访问服务器上的数据并将其发送到客户端。重申AngularJS只是一组JS函数,只在浏览器中运行。你看过angularjs中的$http服务了吗?(复制/粘贴此注释:))您需要在每次刷新时调用数据库…如果数据存在,则显示它,否则显示空白字段@shaunhusain这可以由python完成吗?当然python是一个选项,我自己不是一个大型python开发人员,所以这可能是一个不好的建议,但听说有人使用python中的“瓶子”来设置API。要寻找的东西是设置“路由”或URL处理程序的简单方法,以及设置数据库连接和执行“CRUD”的方法在数据库操作中,通用术语通常是“ORM”,但根据您的需要,其他东西也可以工作。这看起来是个不错的起点@sshaunhusain无法post@LALITVYAS对不起,我不清楚你的意思,你能详细解释一下吗?当您尝试发布时会发生什么?您是否根据上述更改了代码?看起来要从angular将要发送的JSON中获取数据,您可能希望在请求对象上使用此方法,而不是尝试引用.form@LALITVYAS更新了代码,以获得一个完整的示例,该示例是我在本地实际测试并运行的。我从来没有用python做过这么完整的事情,所以四处探索很有趣,而且在启动和运行这个方面没有什么问题(尽管我已经习惯了使用angular和其他后端框架的许多常见问题)。没问题,这对我来说是一个在python中尝试一些东西的好机会。我可能会继续在博客上发布一些更简洁的版本,或者发布更多的博客文章来涵盖这些主题(使用一些库来编写REST api,可能是这个或类似的东西),如果这确实回答了您的问题,请不要忘了打勾号,如果没有,请让我知道您挂在哪里,并尝试提供帮助。
# 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)
);
# 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"
<!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>
(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;
  })


})();