遍布网络的人都使用Php脚本在AngularJS和Mysql数据库之间进行查询。我正在制作Flask应用程序,并希望使用Python进行查询,但我不知道如何。谁能帮我? 这是我到目前为止所尝试的内容: Python脚本:
import pymysql
connection = pymysql.connect(host='localhost',
user='root',
password='*******',
db='testdb',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()
cursor.execute("SELECT * from posts")
posts = cursor.fetchall()
JS:
var application = angular.module("myApp", []);
application.config(['$interpolateProvider', function($interpolateProvider) {
$interpolateProvider.startSymbol('[{');
$interpolateProvider.endSymbol('}]');
}]);
application.controller("postController", function($scope, $https){
$https.get("dbconnect.py").then( function(response) {
$scope.posts = response.data.records;
});
});
答案 0 :(得分:0)
从您的pyscript返回数据。使用flask
来运行。致电python file.py
,您可以在http://localhost:5000/
在您的角度GET
数据中使用此网址...
import pymysql, json
from flask import Flask
app = Flask(__name__)
def date_handler(obj):
return obj.isoformat() if hasattr(obj, 'isoformat') else obj
def get_db_data():
connection = pymysql.connect(host='host',
port=3307,
user='uname',
password='pwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()
cursor.execute("SELECT * from user")
posts = cursor.fetchall()
return json.dumps(posts, default=date_handler)
@app.route("/")
def hello():
xml = get_db_data()
# make fancy operations if you want
return xml
if __name__ == "__main__":
app.run()