简体   繁体   中英

How can I write a python script to connect AngularJS with mysql database?

All over the web people use Php script to make queries between AngularJS and Mysql database. I'm making a Flask application and would like to use Python for the queries but I don't know how. Can anyone help me? Here's what I tried so far: Python script:

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;
    });
});

return data from your pyscript. use flask to run. call python file.py you can see your data in http://localhost:5000/

use this url in your angular to GET data...

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()    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM