之前用过tornado,现在需要做个简单的接口,一下子不太会,就找了个程序,可以简单的实现从数据库中获取相关的数据。
from pyhive import hive
from flask import Flask, request, jsonify
from flask_cors import CORS
import time
host = "0.0.0.0"
port = 10000
user = "root"
passwd = "11"
db = 'test'
connection = hive.Connection(host=host, port=port, auth="LDAP", username=user, password=passwd, database=db)
cursor = connection.cursor()
app = Flask(__name__)
CORS(app, resources=r'/*')
@app.route('/login/list', methods=['POST'])
def login_list():
if request.method == 'POST':
cursor.execute("select * from login")
data = cursor.fetchall()
temp = {}
result = []
if (data!=None):
for i in data:
temp['id'] = i[0]
temp['username'] = i[1]
temp['role'] = i[2]
temp['c_time'] = i[3]
result.append(temp.copy())
print("result: ", len(data))
return jsonify(result)
else:
print("result:NULL")
return jsonify([])
@app.route('/login/add', methods=['POST'])
def login_add():
if request.method == 'POST':
id = request.form.get("id")
username = request.form.get("username")
role = request.form.get("role")
c_time = request.form.get("c_time")
try:
cursor.execute("INSERT INTO login VALUES ('%s', '%s', '%s',%s)" % (id, username, role, c_time))
connection.commit()
print("add a new user successfully")
return "1"
except Exception as e:
print("add a new user failed: ", e)
connection.rollback()
return "-1"
# 此方法报错,需要修改HIVE 相关配置:对UPDATA DEL等支持不友好!
@app.route('/login/del', methods=['POST'])
def login_del():
if request.method == 'POST':
id = request.form.get("id")
try:
cursor.execute("DELETE FROM login WHERE id='%s'" % (id))
connection.commit()
print("delete the user successfully")
return "1"
except Exception as e:
print("delete the user failed: ", e)
connection.rollback()
return "-1"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=10851)
connection.close()
print("Good bye!")
网友评论