gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:58:19 25 4
gpt4 key购买 nike

enter image description here enter 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 () {

}}

保存后,该值会更改,但是当我刷新时,它会再次更改为之前的值。我从本地主机获取的所有这些数据。我想更新服务器(本地主机)上的信息,我该怎么做

请帮助我,我是初学者

   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)

最佳答案

Update 决定熟悉 Flask 并在这里给出正确的完整答案:

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

# 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代码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 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>

Angular 执行脚本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;
})


})();

将其写到此处的博客条目中,以便我可以添加可能与原始问题不直接相关的详细信息:

https://www.intellectual-tech.com/blog/full-stack-python-angular-rest-api

关于angularjs - 如何使用 Python 创建 REST API(保存和加载数据)并使用 AngularJS 使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48047970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com