Python3项目初始化4-->用户编辑、创建和删除

15、用户编辑
主要是修改model.py部分
SQL_GET_USER_COLUMN = ['id', 'name', 'age', 'tel', 'sex']
SQL_GET_USER_BY_ID = 'SELECT id,name,age,tel,sex FROM user2 where id=%s'
SQL_GET_USER_BY_NAME ='SELECT id,name,age,tel,sex FROM user2 where name=%s'
SQL_UPDATE_USER ='UPDATE user2 SET name=%s,age=%s,sex=%s, tel=%s where id=%s'

 

 

浏览器访问编辑,可以正常修改用户名,联系方式,年龄,性别等信息。

16、添加用户
首页index.html设置,
当前登录用户是:{{ request.session.user.name }}, <a href="/user/logout/">退出登录</a>
<a href="{% url 'user:create' %}">创建</a> ===>需要添加的部分
<table border="1" cellspacing="0">
添加url前端create.html展示,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>用户创建</title>
</head>
<body>
<form action="{% url 'user:create' %}" method="POST">
{% if errors %}
{% for key, error in errors.items %}
{{ error }} <br/>
{% endfor %}
{% endif %}
{% csrf_token %}

用户名: <input type="text" name="name" value="{{ user.name }}"/> <br />
密码: <input type="password" name="password" value=""/> <br />
再次输入密码: <input type="password" name="other_password" value=""/> <br />
联系方式: <input type="text" name="tel" value="{{ user.tel }}"/> <br />
年龄: <input type="text" name="age" value="{{ user.age }}"/> <br />
性别: <input type="radio" name="sex" value="1"
{% if user.sex != 0%} checked="checked" {% endif %}
/> 男
<input type="radio" name="sex" value="0"
{% if user.sex == 0%} checked="checked" {% endif %}/> 女 <br />
<input type="submit" value="修改"/> <br />
</form>
</body>
</html>
路由设置,
path('create/', views.create, name='create'),
视图设置:
from .models import valid_login as ... valid_create_user, create_user
def create(request):

主要是修改model.py部分
SQL_UPDATE_USER ='UPDATE user2 SET name=%s,age=%s,sex=%s, tel=%s where id=%s'
SQL_CREATE_USER ='INSERT into user2(name, password, age, tel, sex) values(%s,%s, %s,%s,%s)'

def valid_create_user(params):
is_valid = True
user = {}
errors = {}
users = get_users()
user['name'] = params.get('name', '').strip()
if user['name'] == "":
errors['name'] = '用户信息不存在'
is_valid = False

elif get_user_by_name(user['name']):
is_valid = False
errors['name'] = '用户名重复.'

user['age'] = params.get('age', '0').strip()
if not user['age'].isdigit():
errors['age'] = '年龄格式错误'
is_valid = False
user['tel'] = params.get('tel', '0')
user['sex'] = int(params.get('sex', '0'))
user['password'] = params.get('password', '').strip()

if user['password'] == '' or params.get('other_password') != user["password"]:
is_valid = False
errors['password'] = '密码不能为空, 且两次输入密码必须相同.'

return is_valid, user, errors

def create_user(params):
conn = MySQLdb.connect(host=MYSQL_HOST, port=MYSQL_PORT,
user=MYSQL_USER, passwd=MYSQL_PASSWORD,
db=MYSQL_DB, charset=MYSQL_CHARSET)
cur = conn.cursor()
args = (params['name'], params['password'], params['age'], params['tel'], params['sex'])
cur.execute(SQL_CREATE_USER, args)
conn.commit()
cur.close()
conn.close()
return True
此时页面访问,是可以添加用户的。

16、删除用户
只修改model,其他不变。
SQL_DELETE_USER ='DELETE from user2 where id=%s'
def delete_user(uid):
conn = MySQLdb.connect(host=MYSQL_HOST, port=MYSQL_PORT,
user=MYSQL_USER, passwd=MYSQL_PASSWORD,
db=MYSQL_DB, charset=MYSQL_CHARSET)
cur = conn.cursor()
cur.execute(SQL_DELETE_USER, (uid, ))
conn.commit()
cur.close()
conn.close()
return True
页面操作,可以删除用户。

17、引入dbutils函数改造代码
cat user/dbutils.py 工具类编辑。
#encoding:utf-8
import MySQLdb
import traceback
MYSQL_HOST = '192.168.1.118'
MYSQL_PORT = 3306
MYSQL_USER = 'wang'
MYSQL_PASSWORD = 'Test@123'
MYSQL_DB = 'db_name'
MYSQL_CHARSET = 'utf8'

def execute_sql(sql, args=(), fetch=True, one=False):
    cnt, result = 0, None
    conn, cur = None, None
    try:
        conn = MySQLdb.connect(host=MYSQL_HOST, port=MYSQL_PORT,
        user=MYSQL_USER, passwd=MYSQL_PASSWORD,
        db=MYSQL_DB, charset=MYSQL_CHARSET)
        cur = conn.cursor()
        cur.execute(sql, args)
        if fetch:
            result = cur.fetchone() if one else cur.fetchall()
        else:
            conn.commit()
    except BaseException as e:
        print(e)
        print(traceback.format_exc())
    finally:
        if cur:
            cur.close()
        if conn:
            conn.close()
    return cnt, result
model.py引入工具类。
#enconding: utf-8
from .dbutils import execute_sql
SQL_LOGIN = 'SELECT id,name,password,age,tel,sex FROM user2 where name=%s and password=%s LIMIT 1'
SQL_LIST = 'SELECT id,name,age,tel,sex FROM user2'
SQL_LIST_COLUMN = ['id', 'name', 'age', 'tel', 'sex']
SQL_USER_COLUMN = ['id', 'name', 'age', 'tel', 'sex']
SQL_GET_USER_COLUMN = ['id', 'name', 'age', 'tel', 'sex']
SQL_GET_USER_BY_ID = 'SELECT id,name,age,tel,sex FROM user2 where id=%s'
SQL_GET_USER_BY_NAME ='SELECT id,name,age,tel,sex FROM user2 where name=%s'
SQL_UPDATE_USER ='UPDATE user2 SET name=%s,age=%s,sex=%s, tel=%s where id=%s'
SQL_CREATE_USER ='INSERT into user2(name, password, age, tel, sex) values(%s,%s, %s,%s,%s)'
SQL_DELETE_USER ='DELETE from user2 where id=%s'
def get_users():
    cnt, result = execute_sql(SQL_LIST)
    return [
        dict(zip(SQL_LIST_COLUMN, line))
        for line in result
]

def valid_login(name, password):
    cnt, result = execute_sql(SQL_LOGIN, (name, password), one=True)
    return dict(zip(SQL_USER_COLUMN, result)) if result else None

def delete_user(uid):
    execute_sql(SQL_DELETE_USER, (uid, ), fetch=False)
    return True

def get_user(uid):
    cnt, result = execute_sql(SQL_GET_USER_BY_ID, (uid, ), one=True)
    return dict(zip(SQL_GET_USER_COLUMN, result)) if result else None

def get_user_by_name(name):
    cnt, result = execute_sql(SQL_GET_USER_BY_NAME, (name,), one=True)
    return dict(zip(SQL_GET_USER_COLUMN, result)) if result else None

def valid_name_unique(name, uid=None):
user = get_user_by_name(name)
if uid is None:
return not user
else:
if user is None:
return True
else:
return str(user['id']) == str(uid)
def valid_update_user(params):
is_valid = True
user = {}
errors = {}
user['id'] = params.get('id', '').strip()
if get_user(user['id']) is None:
errors['id'] = '用户信息不存在'
is_valid = False
user['name'] = params.get('name', '').strip()
if not valid_name_unique(user['name'], user['id']):
errors['name'] = '用户名已存在'
is_valid = False
user['age'] = params.get('age', '0').strip()
if not user['age'].isdigit():
errors['age'] = '年龄格式错误'
is_valid = False
user['tel'] = params.get('tel', '0')
user['sex'] = int(params.get('sex', '0'))
return is_valid, user, errors

def update_user(params):
    args = (params['name'], params['age'], params['sex'], params['tel'], params['id'])
    cnt, result = execute_sql(SQL_UPDATE_USER, args, fetch=False)
    return True

def valid_create_user(params):
is_valid = True
user = {}
errors = {}
users = get_users()
user['name'] = params.get('name', '').strip()
if user['name'] == "":
errors['name'] = '用户信息不存在'
is_valid = False

elif get_user_by_name(user['name']):
is_valid = False
errors['name'] = '用户名重复.'

user['age'] = params.get('age', '0').strip()
if not user['age'].isdigit():
errors['age'] = '年龄格式错误'
is_valid = False
user['tel'] = params.get('tel', '0')
user['sex'] = int(params.get('sex', '0'))
user['password'] = params.get('password', '').strip()

if user['password'] == '' or params.get('other_password') != user["password"]:
is_valid = False
errors['password'] = '密码不能为空, 且两次输入密码必须相同.'

return is_valid, user, errors

def create_user(params):
    args = (params['name'], params['password'], params['age'], params['tel'], params['sex'])
    cnt, result = execute_sql(SQL_CREATE_USER, args, fetch=False)
    return True

def delete_user(uid):
    execute_sql(SQL_DELETE_USER, (uid, ), fetch=False)
    return True
以上验证全部功能ok。

posted @ 2022-08-02 08:00  wang_wei123  阅读(114)  评论(0编辑  收藏  举报