Skip to content

Commit

Permalink
增加操作MySQL数据库
Browse files Browse the repository at this point in the history
  • Loading branch information
wintests committed Apr 19, 2020
1 parent a043d59 commit bf790c0
Show file tree
Hide file tree
Showing 6 changed files with 102 additions and 31 deletions.
65 changes: 41 additions & 24 deletions api/user.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
from flask import Flask, jsonify, request
from common.mysql_operate import db
import re

app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False # jsonify返回的中文正常显示

data = [
{"id": 1, "username": "小明", "password": "123456", "role": 0, "sex": 0, "telephone": "10086", "address": "北京市海淀区"},
{"id": 2, "username": "李华", "password": "abc", "role": 1, "sex": 0, "telephone": "10010", "address": "广州市天河区"},
{"id": 3, "username": "大白", "password": "666666", "role": 0, "sex": 1, "telephone": "10000", "address": "深圳市南山区"}
]


@app.route('/')
def hello_world():
Expand All @@ -18,49 +14,70 @@ def hello_world():
@app.route("/users", methods=["GET"])
def get_all_users():
"""获取所有用户信息"""
return jsonify({"code": "0", "data": data, "msg": "操作成功"})
sql = "SELECT * FROM user"
data = db.select_db(sql)
print("获取所有用户信息 == >> {}".format(data))
return jsonify({"code": "0", "data": data, "msg": "查询成功"})


@app.route("/users/<int:user_id>", methods=["GET"])
def get_user(user_id):
@app.route("/users/<string:username>", methods=["GET"])
def get_user(username):
"""获取某个用户信息"""
if user_id > 0 and user_id <= len(data):
return jsonify({"code": "0", "data": data[user_id - 1], "msg": "操作成功"})
return jsonify({"code": "1", "msg": "用户不存在"})
sql = "SELECT * FROM user WHERE username = '{}'".format(username)
data = db.select_db(sql)
print("获取 {} 用户信息 == >> {}".format(username, data))
if data:
return jsonify({"code": "0", "data": data, "msg": "查询成功"})
return jsonify({"code": "1004", "msg": "查不到相关用户的信息"})


@app.route("/register", methods=['POST'])
def user_register():
username = request.json.get("username").strip() # 用户名
password = request.json.get("password").strip() # 密码
sex = request.json.get("sex", "0").strip() # 性别,默认为0(男性)
telephone = request.json.get("telephone", "").strip() # 手机号,默认为空
address = request.json.get("telphone", "").strip() # 地址,默认为空
telephone = request.json.get("telephone", "").strip() # 手机号,默认为空串
address = request.json.get("address", "").strip() # 地址,默认为空串
if username and password and telephone:
import re
if username == "wintest":
return jsonify({"code": 2002, "msg": "用户名已存在!!!"})
sql1 = "SELECT username FROM user WHERE username = '{}'".format(username)
res1 = db.select_db(sql1)
print("查询到用户名 ==>> {}".format(res1))
sql2 = "SELECT telephone FROM user WHERE telephone = '{}'".format(telephone)
res2 = db.select_db(sql2)
print("查询到手机号 ==>> {}".format(res2))
if res1:
return jsonify({"code": 2002, "msg": "用户名已存在,注册失败!!!"})
elif not (sex == "0" or sex == "1"):
return jsonify({"code": 2003, "msg": "输入的性别只能是 0(男) 或 1(女)!!!"})
elif not (len(telephone) == 11 and re.match("^1[3,5,7,8]\d{9}$", telephone)):
return jsonify({"code": 2004, "msg": "手机号格式不正确!!!"})
elif res2:
return jsonify({"code": 2005, "msg": "手机号已被注册!!!"})
else:
sql3 = "INSERT INTO user(username, password, role, sex, telephone, address) " \
"VALUES('{}', '{}', '1', '{}', '{}', '{}')".format(username, password, sex, telephone, address)
db.execute_db(sql3)
print("新增用户信息 ==>> {}".format(sql3))
return jsonify({"code": 0, "msg": "恭喜,注册成功!"})
else:
return jsonify({"code": 2001, "msg": "用户名/密码/手机号不能为空,请检查!!!"})


@app.route("/login", methods=['POST'])
def user_login():
username = request.values.get("username")
password = request.values.get("password")
username = request.values.get("username").strip()
password = request.values.get("password").strip()
if username and password:
if username == "wintest" and password == "123456":
sql1 = "SELECT username FROM user WHERE username = '{}'".format(username)
res1 = db.select_db(sql1)
print("查询到用户名 ==>> {}".format(res1))
if not res1:
return jsonify({"code": 1003, "msg": "用户名不存在!!!"})
sql2 = "SELECT * FROM user WHERE username = '{}' and password = '{}'".format(username, password)
res2 = db.select_db(sql2)
print("获取 {} 用户信息 == >> {}".format(username, res2))
if res2:
return jsonify({"code": 0, "msg": "恭喜,登录成功!"})
return jsonify({"code": 1002, "msg": "用户名或密码错误!!!"})
else:
return jsonify({"code": 1001, "msg": "用户名或密码不能为空!!!"})


if __name__ == '__main__':
app.run()
15 changes: 8 additions & 7 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from flask import Flask
import os, sys
from config.setting import SERVER_PORT
from api.user import app

app = Flask(__name__)

@app.route('/')
def hello_world():
return 'Hello World!'
# 项目根路径
BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, BASE_PATH) # 将项目根路径临时加入环境变量,程序退出后失效

if __name__ == '__main__':
app.run()
# host为主机ip地址,port指定访问端口号,debug=True设置调试模式打开
app.run(host="0.0.0.0", port=SERVER_PORT, debug=True)
Empty file added common/__init__.py
Empty file.
44 changes: 44 additions & 0 deletions common/mysql_operate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import pymysql
from config.setting import MYSQL_HOST,MYSQL_PORT,MYSQL_USER,MYSQL_PASSWD,MYSQL_DB

class MysqlDb():

def __init__(self, host, port, user, passwd, db):
# 建立数据库连接
self.conn = pymysql.connect(
host=host,
port=port,
user=user,
passwd=passwd,
db=db
)
# 通过 cursor() 创建游标对象,并让查询结果以字典格式输出
self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

def __del__(self): # 对象资源被释放时触发,在对象即将被删除时的最后操作
# 关闭游标
self.cur.close()
# 关闭数据库连接
self.conn.close()

def select_db(self, sql):
"""查询"""
# 使用 execute() 执行sql
self.cur.execute(sql)
# 使用 fetchall() 获取查询结果
data = self.cur.fetchall()
return data

def execute_db(self, sql):
"""更新/新增/删除"""
try:
# 使用 execute() 执行sql
self.cur.execute(sql)
# 提交事务
self.conn.commit()
except Exception as e:
print("操作出现错误:{}".format(e))
# 回滚所有更改
self.conn.rollback()

db = MysqlDb(MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASSWD, MYSQL_DB)
Empty file added config/__init__.py
Empty file.
9 changes: 9 additions & 0 deletions config/setting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# 服务端口配置
SERVER_PORT = 9999

# MySQL配置
MYSQL_HOST = "192.168.89.128"
MYSQL_PORT = 3306
MYSQL_USER = "root"
MYSQL_PASSWD = "123456"
MYSQL_DB = "flask_demo"

0 comments on commit bf790c0

Please sign in to comment.