python pymysql flask 简易使用 和返回指定的json格式数据

pymysql.demo

import pymysql
import json
#print(print.__doc__)
conn = pymysql.connect(host="192.168.169.132",
                user="root",
                password="111111",
                database="zb")


cursor = conn.cursor()


#cursor.execute("insert into tuser (name, pass) values ('ccc', 'ccc')")
#conn.commit()


cursor.execute("select * from tuser")


sb=cursor.fetchall()
sb1 = {"data":sb,"status":1}




print(sb1)
#{'data': ((1, 'cc', 'cc', 0, None, None), (3, 'ccc', 'ccc', 0, None, None), (4, 'a', '0cc175b9c0f1b6a831c399e269772661', None, None, None), (12, 'e', 'e1671797c52e15f763380b45e841ec32', None, None, None), (13, 'r', '4b43b0aee35624cd95b910189b3dc231', None, None, None), (14, 'aaa', '47bce5c74f589f4867dbd57e9ca9f808', None, None, None), (16, 'aaaa', '74b87337454200d4d33f80c4663dc5e5', None, None, None), (17, '1', 'c4ca4238a0b923820dcc509a6f75849b', None, None, None), (18, '2', 'c81e728d9d4c2f636f067f89cc14862c', None, None, None), (19, '23', '37693cfc748049e45d87b8c7d8b9aacd', None, None, None), (20, '234', '289dff07669d7a23de0ef88d2f7129e7', None, None, None), (21, '2345', '81b073de9370ea873f548e31b8adc081', None, None, None), (22, 'ee', '08a4415e9d594ff960030b921d42b91e', None, None, None), (23, '66', '3295c76acbf4caaed33c36b1b5fc2cb1', None, None, None)), 'status': 1}


print(sb1['data'][2])


#(4, 'a', '0cc175b9c0f1b6a831c399e269772661', None, None, None)
'''
for key in sb1:
    print(key,"value:",sb1[key])
 
cursor.execute("select * from tuser")
for i in range(cursor.rowcount):
    record = cursor.fetchone()
    print(record)
'''


cursor.execute("select * from tuser")
print(cursor.rowcount)
courses = []
for i in range(cursor.rowcount):
    record = cursor.fetchone()
    course = {}
    course["name"] = record[0]
    course["info"] = record[1]
    course["price"] = record[2]
    course["sdate"] = str(record[3])
    course["edate"] = str(record[4])
    course["id"] = record[5]
    courses.append(course)
print(courses)


cursor.execute("select * from tuser")
print(cursor.rowcount)
courses = []
data = {}
for i in range(cursor.rowcount):
    record = cursor.fetchone()
    course = {}
    course["name"] = record[0]
    course["info"] = record[1]
    course["price"] = record[2]
    course["sdate"] = str(record[3])
    course["edate"] = str(record[4])
    course["id"] = record[5]
    courses.append(course)
data['code'] = "haha"


dew = []
ew = {}
ew['xcode']="a"
dew.append(ew)




data['status'] = "1"
data['data'] = courses


dew.append(data['data'])
data['xcode'] = dew
print(data)




# 'data': ((1, 'cc', 'cc', 0, None, None), (3, 'ccc', 'ccc', 0, None, None), (4, 'a', '0cc175b9c0f1b6a831c399e269772661', None, None, None), (12, 'e', 'e1671797c52e15f763380b45e841ec32', None, None, None), (13, 'r', '4b43b0aee35624cd95b910189b3dc231', None, None, None), (14, 'aaa', '47bce5c74f589f4867dbd57e9ca9f808', None, None, None), (16, 'aaaa', '74b87337454200d4d33f80c4663dc5e5', None, None, None), (17, '1', 'c4ca4238a0b923820dcc509a6f75849b', None, None, None), (18, '2', 'c81e728d9d4c2f636f067f89cc14862c', None, None, None), (19, '23', '37693cfc748049e45d87b8c7d8b9aacd', None, None, None), (20, '234', '289dff07669d7a23de0ef88d2f7129e7', None, None, None), (21, '2345', '81b073de9370ea873f548e31b8adc081', None, None, None), (22, 'ee', '08a4415e9d594ff960030b921d42b91e', None, None, None), (23, '66', '3295c76acbf4caaed33c36b1b5fc2cb1', None, None, None)), 'status': 1}
# (4, 'a', '0cc175b9c0f1b6a831c399e269772661', None, None, None)
# 14
# [{'name': 1, 'info': 'cc', 'price': 'cc', 'sdate': '0', 'edate': 'None', 'id': None}, {'name': 3, 'info': 'ccc', 'price': 'ccc', 'sdate': '0', 'edate': 'None', 'id': None}, {'name': 4, 'info': 'a', 'price': '0cc175b9c0f1b6a831c399e269772661', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 12, 'info': 'e', 'price': 'e1671797c52e15f763380b45e841ec32', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 13, 'info': 'r', 'price': '4b43b0aee35624cd95b910189b3dc231', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 14, 'info': 'aaa', 'price': '47bce5c74f589f4867dbd57e9ca9f808', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 16, 'info': 'aaaa', 'price': '74b87337454200d4d33f80c4663dc5e5', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 17, 'info': '1', 'price': 'c4ca4238a0b923820dcc509a6f75849b', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 18, 'info': '2', 'price': 'c81e728d9d4c2f636f067f89cc14862c', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 19, 'info': '23', 'price': '37693cfc748049e45d87b8c7d8b9aacd', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 20, 'info': '234', 'price': '289dff07669d7a23de0ef88d2f7129e7', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 21, 'info': '2345', 'price': '81b073de9370ea873f548e31b8adc081', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 22, 'info': 'ee', 'price': '08a4415e9d594ff960030b921d42b91e', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 23, 'info': '66', 'price': '3295c76acbf4caaed33c36b1b5fc2cb1', 'sdate': 'None', 'edate': 'None', 'id': None}]
# 14
# {'code': 'haha', 'status': '1', 'data': [{'name': 1, 'info': 'cc', 'price': 'cc', 'sdate': '0', 'edate': 'None', 'id': None}, {'name': 3, 'info': 'ccc', 'price': 'ccc', 'sdate': '0', 'edate': 'None', 'id': None}, {'name': 4, 'info': 'a', 'price': '0cc175b9c0f1b6a831c399e269772661', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 12, 'info': 'e', 'price': 'e1671797c52e15f763380b45e841ec32', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 13, 'info': 'r', 'price': '4b43b0aee35624cd95b910189b3dc231', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 14, 'info': 'aaa', 'price': '47bce5c74f589f4867dbd57e9ca9f808', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 16, 'info': 'aaaa', 'price': '74b87337454200d4d33f80c4663dc5e5', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 17, 'info': '1', 'price': 'c4ca4238a0b923820dcc509a6f75849b', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 18, 'info': '2', 'price': 'c81e728d9d4c2f636f067f89cc14862c', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 19, 'info': '23', 'price': '37693cfc748049e45d87b8c7d8b9aacd', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 20, 'info': '234', 'price': '289dff07669d7a23de0ef88d2f7129e7', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 21, 'info': '2345', 'price': '81b073de9370ea873f548e31b8adc081', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 22, 'info': 'ee', 'price': '08a4415e9d594ff960030b921d42b91e', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 23, 'info': '66', 'price': '3295c76acbf4caaed33c36b1b5fc2cb1', 'sdate': 'None', 'edate': 'None', 'id': None}], 'xcode': [{'xcode': 'a'}, [{'name': 1, 'info': 'cc', 'price': 'cc', 'sdate': '0', 'edate': 'None', 'id': None}, {'name': 3, 'info': 'ccc', 'price': 'ccc', 'sdate': '0', 'edate': 'None', 'id': None}, {'name': 4, 'info': 'a', 'price': '0cc175b9c0f1b6a831c399e269772661', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 12, 'info': 'e', 'price': 'e1671797c52e15f763380b45e841ec32', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 13, 'info': 'r', 'price': '4b43b0aee35624cd95b910189b3dc231', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 14, 'info': 'aaa', 'price': '47bce5c74f589f4867dbd57e9ca9f808', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 16, 'info': 'aaaa', 'price': '74b87337454200d4d33f80c4663dc5e5', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 17, 'info': '1', 'price': 'c4ca4238a0b923820dcc509a6f75849b', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 18, 'info': '2', 'price': 'c81e728d9d4c2f636f067f89cc14862c', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 19, 'info': '23', 'price': '37693cfc748049e45d87b8c7d8b9aacd', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 20, 'info': '234', 'price': '289dff07669d7a23de0ef88d2f7129e7', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 21, 'info': '2345', 'price': '81b073de9370ea873f548e31b8adc081', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 22, 'info': 'ee', 'price': '08a4415e9d594ff960030b921d42b91e', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 23, 'info': '66', 'price': '3295c76acbf4caaed33c36b1b5fc2cb1', 'sdate': 'None', 'edate': 'None', 'id': None}]]}


mysql.py
import pymysql

def get_conn():
    conn = pymysql.connect(host="192.168.169.132",
                           user="root",
                           password="111111",
                           database="zb",
                           )


    return conn


#def execute(conn, sql):
#    cursor = conn.cursor()
#    cursor.execute(sql)
#    conn.commit()
#    return cursor

def select(cursor, sql):
    cursor.execute(sql)
    return cursor

def insert(cursor, sql):
    cursor.execute(sql)

def update(cursor, sql):
    cursor.execute(sql)


main.py

from flask import Flask
from flask import request
import json
import mysql

import uuid
import hashlib

app = Flask("live-server")


def toJson(**kwargs):
    return json.dumps(kwargs) # 把json转换成字符串

# 创建session
def getSession():
    uuidObj = uuid.uuid1()
    uuidStr = str(uuidObj)

    # 对UUID进行 md5 hash
    print(type(uuidStr))

    # str, bytes  QString QByteArray

    return hashlib.md5(uuidStr.encode()).hexdigest()


@app.route("/addcourse", methods=['POST', 'GET'])
def addcourse():
    try:
        json = request.json
        print(json)

        session = json['session']
        name = json['name']
        desc = json['desc']
        teacher = json['teacher']
        sdate = json['sdate']
        edate = json['edate']
        price = json['price']

        conn = mysql.get_conn()
        cursor = conn.cursor()

        mysql.select(cursor, "select id from tuser where session='%s'" % session)
        if cursor.rowcount == 0:
            return toJson(result="err", reason="session error")

        sql = "insert into tcourse (name, info, price, sdate, edate) values ('%s', '%s', %d, '%s', '%s')" % (
            name, desc, price, sdate, edate
        )
        print(sql)
        mysql.insert(cursor, sql)

        mysql.select(cursor, "select max(id) from tcourse")
        courseid = cursor.fetchone()[0]

        mysql.select(cursor, "select id from tuser where name='%s'" % teacher)
        userid = cursor.fetchone()[0]

        mysql.insert(cursor, "insert into trelation (userid, courseid, relation) values(%d, %d, 0)" % (userid, courseid))
        conn.commit()

    except Exception as e:
        print(str(e))
        return toJson(result = "err", reason=str(e))
    return toJson(result='ok')

@app.route("/charge", methods=['POST', 'GET'])
def charge():
    try:
        json = request.json
        print(json)
        session = json['session']
        money = json['money']

        conn = mysql.get_conn()
        cursor = conn.cursor()

        # 1. 用户表
        #    1. 先获得原来的余额
        #    2. 相加再更新
        # 2. 充值记录表
        #    1. 插入一条记录
        mysql.select(cursor, "select balance, id from tuser where session='%s'" % session)
        if cursor.rowcount == 0:
            return toJson(result="err", reason="session error")

        record = cursor.fetchone()
        balance = record[0]
        userid = record[1]

        new_balance = balance + money
        mysql.update(cursor, "update tuser set balance=%d where id=%d" % (new_balance, userid))
        mysql.insert(cursor, "insert into tcharge (userid, money, balance) values (%d, %d, %d)" % (userid,money, new_balance))

        conn.commit()

        return toJson(result="ok", balance=new_balance)
    except Exception as e:
        return toJson(result="err", reason=str(e))




@app.route("/login", methods=['POST', 'GET'])
def login():
    try:
        json = request.json
        print(json)
        username = json['username']
        password = json['password']
        password = hashlib.md5(password.encode()).hexdigest()
        type = json['type']

        conn = mysql.get_conn()
        cursor = conn.cursor()

        mysql.select(cursor, "select * from tuser where name='%s' and pass='%s'" % (username, password))

        if cursor.rowcount == 1:
            session = getSession()
            mysql.update(cursor, "update tuser set session='%s' where name='%s'" % (session, username))
            conn.commit()

            return toJson(result = "ok", session = session)

    except Exception as e:
        return toJson(result = "err", reason = str(e))

    # 3. 返回数据给客户端
    # return
    return toJson(result = "err", reason = "username or password error")

@app.route("/reg", methods=['POST', 'GET'])
def reg():

    try:
        # 1. 获取客户端的数据
        json = request.json

        username = json['username']
        password = json['password']
        password = hashlib.md5(password.encode()).hexdigest()

        # 2. 写入数据库
        # 使用pymysql访问数据
        conn = mysql.get_conn()
        cursor = conn.cursor()
        mysql.insert(cursor, "insert into tuser (name, pass)values('%s', '%s')" % (username, password))
        conn.commit()

    # {
    #    result: ok
    # }
    # {
    #    result: err,
    #    reason: whasdfsadf
    # }

    except Exception as e:
        return toJson(result = "err", reason = str(e))

    # 3. 返回数据给客户端
    # return

    cursor.execute("select * from tuser limit 4")
    print(cursor.rowcount)
    courses = []
    data = {}
    for i in range(cursor.rowcount):
        record = cursor.fetchone()
        course = {}
        course["name"] = record[0]
        course["info"] = record[1]
        course["price"] = record[2]
        course["sdate"] = str(record[3])
        course["edate"] = str(record[4])
        course["id"] = record[5]
        courses.append(course)
    data['code'] = 1
    data['data'] = courses
    print(data)
    print(toJson(result='no',shuju=courses,datas=data))
    return(toJson(result='no',shuju=courses,datas=data))


app.run(host="0.0.0.0", port=10099)


#{'code': 1, 'data': [{'name': 1, 'info': 'cc', 'price': 'cc', 'sdate': '0', 'edate': 'None', 'id': None}, {'name': 3, 'info': 'ccc', 'price': 'ccc', 'sdate': '0', 'edate': 'None', 'id': None}, {'name': 4, 'info': 'a', 'price': '0cc175b9c0f1b6a831c399e269772661', 'sdate': 'None', 'edate': 'None', 'id': None}, {'name': 12, 'info': 'e', 'price': 'e1671797c52e15f763380b45e841ec32', 'sdate': 'None', 'edate': 'None', 'id': None}]}
# {"result": "no", "shuju": [{"name": 1, "info": "cc", "price": "cc", "sdate": "0", "edate": "None", "id": null}, {"name": 3, "info": "ccc", "price": "ccc", "sdate": "0", "edate": "None", "id": null}, {"name": 4, "info": "a", "price": "0cc175b9c0f1b6a831c399e269772661", "sdate": "None", "edate": "None", "id": null}, {"name": 12, "info": "e", "price": "e1671797c52e15f763380b45e841ec32", "sdate": "None", "edate": "None", "id": null}], "datas": {"code": 1, "data": [{"name": 1, "info": "cc", "price": "cc", "sdate": "0", "edate": "None", "id": null}, {"name": 3, "info": "ccc", "price": "ccc", "sdate": "0", "edate": "None", "id": null}, {"name": 4, "info": "a", "price": "0cc175b9c0f1b6a831c399e269772661", "sdate": "None", "edate": "None", "id": null}, {"name": 12, "info": "e", "price": "e1671797c52e15f763380b45e841ec32", "sdate": "None", "edate": "None", "id": null}]}}


你可能感兴趣的:(python)