Home >  > 一天学会Python Web框架(十二)产品管理

一天学会Python Web框架(十二)产品管理

0

一、添加代码

在api文件夹下面新建一个product.py文件,加入以下获取产品列表接口代码

1#!/usr/bin/evn python
2# coding=utf-8
3 
4import json
5from bottle import get, put, post, delete
6from common import web_helper, db_helper, convert_helper, json_helper, string_helper
7 
8@get('/api/product/')
9def callback():
10    """
11    获取列表数据
12    """
13    # 设置查询条件
14    wheres = ''
15    # 产品分类id
16    product_class_id = convert_helper.to_int0(web_helper.get_query('product_class_id', '', is_check_null=False))
17    if product_class_id > 0:
18        wheres = 'where product_class_id=' + str(product_class_id)
19    # 页面索引
20    page_number = convert_helper.to_int1(web_helper.get_query('page', '', is_check_null=False))
21    # 页面显示记录数量
22    page_size = convert_helper.to_int0(web_helper.get_query('rows', '', is_check_null=False))
23    # 排序字段
24    sidx = web_helper.get_query('sidx', '', is_check_null=False)
25    # 顺序还是倒序排序
26    sord = web_helper.get_query('sord', '', is_check_null=False)
27    # 初始化排序字段
28    order_by = 'id desc'
29    if sidx:
30        order_by = sidx + ' ' + sord
31 
32    #############################################################
33    # 初始化输出格式(前端使用jqgrid列表,需要指定输出格式)
34    data = {
35        'records': 0,
36        'total': 0,
37        'page': 1,
38        'rows': [],
39    }
40    #############################################################
41    # 执行sql,获取指定条件的记录总数量
42    sql = 'select count(1) as records from product %(wheres)s' % {'wheres': wheres}
43    result = db_helper.read(sql)
44    # 如果查询失败或不存在指定条件记录,则直接返回初始值
45    if not result or result[0]['records'] == 0:
46        return data
47    # 保存总记录数量
48    data['records'] = result[0].get('records', 0)
49 
50    #############################################################
51    ### 设置分页索引与页面大小 ###
52    # 设置分页大小
53    if page_size is None or page_size <= 0:
54        page_size = 10
55    # 计算总页数
56    if data['records'] % page_size == 0:
57        page_total = data['records'] // page_size
58    else:
59        page_total = data['records'] // page_size + 1
60    # 记录总页面数量
61    data['total'] = page_total
62 
63    # 判断提交的页码是否超出范围
64    if page_number < 1 or page_number > page_total:
65        page_number = page_total
66    # 记录当前页面索引值
67    data['page'] = page_number
68 
69    # 计算当前页面要显示的记录起始位置
70    record_number = (page_number - 1) * page_size
71    # 设置查询分页条件
72    paging = ' limit ' + str(page_size) + ' offset ' + str(record_number)
73    ### 设置排序 ###
74    if not order_by:
75        order_by = 'id desc'
76    #############################################################
77 
78    # 组合sql查询语句
79    sql = "select * from product %(wheres)s order by %(orderby)s %(paging)s" % \
80           {'wheres': wheres, 'orderby': order_by, 'paging': paging}
81    # 读取记录
82    result = db_helper.read(sql)
83    if result:
84        # 存储记录
85        data['rows'] = result
86 
87    if data:
88        # 直接输出json
89        return web_helper.return_raise(json.dumps(data, cls=json_helper.CJsonEncoder))
90    else:
91        return web_helper.return_msg(-1, "查询失败")

二、获取指定id的记录实体

1@get('/api/product/<id:int>/')
2def callback(id):
3    """
4    获取指定记录
5    """
6    sql = """select * from product where id = %s""" % (id,)
7    # 读取记录
8    result = db_helper.read(sql)
9    if result:
10        # 直接输出json
11        return web_helper.return_msg(0, '成功', result[0])
12    else:
13        return web_helper.return_msg(-1, "查询失败")

三、添加产品与修改产品接口

1@post('/api/product/')
2def callback():
3    """
4    新增记录
5    """
6    name = web_helper.get_form('name', '产品名称')
7    code = web_helper.get_form('code', '产品编码')
8    product_class_id = convert_helper.to_int0(web_helper.get_form('product_class_id', '产品分类'))
9    standard = web_helper.get_form('standard', '产品规格')
10    quality_guarantee_period = web_helper.get_form('quality_guarantee_period', '保质期')
11    place_of_origin = web_helper.get_form('place_of_origin', '产地')
12    front_cover_img = web_helper.get_form('front_cover_img', '封面图片')
13    content = web_helper.get_form('content', '产品描述', is_check_special_char=False)
14    # 防sql注入攻击处理
15    content = string_helper.filter_str(content, "'")
16    # 防xss攻击处理
17    content = string_helper.clear_xss(content)
18    is_enable = convert_helper.to_int0(web_helper.get_form('is_enable', '是否启用'))
19 
20    # 添加记录(使用returning这个函数能返回指定的字段值,这里要求返回新添加记录的自增id值)
21    sql = """insert into product (name, code, product_class_id, standard, quality_guarantee_period,
22                place_of_origin, front_cover_img, content, is_enable)
23              values (%s, %s, %s, %s, %s, %s, %s, %s, %s) returning id"""
24    vars = (name, code, product_class_id, standard, quality_guarantee_period, place_of_origin, front_cover_img, content, is_enable)
25    # 写入数据库
26    result = db_helper.write(sql, vars)
27    # 判断是否提交成功
28    if result and result[0].get('id'):
29        return web_helper.return_msg(0, '成功')
30    else:
31        return web_helper.return_msg(-1, "提交失败")
32 
33 
34@put('/api/product/<id:int>/')
35def callback(id):
36    """
37    修改记录
38    """
39 
40    name = web_helper.get_form('name', '产品名称')
41    code = web_helper.get_form('code', '产品编码')
42    product_class_id = convert_helper.to_int0(web_helper.get_form('product_class_id', '产品分类'))
43    standard = web_helper.get_form('standard', '产品规格')
44    quality_guarantee_period = web_helper.get_form('quality_guarantee_period', '保质期')
45    place_of_origin = web_helper.get_form('place_of_origin', '产地')
46    front_cover_img = web_helper.get_form('front_cover_img', '封面图片')
47    content = web_helper.get_form('content', '产品描述', is_check_special_char=False)
48    # 防sql注入攻击处理
49    content = string_helper.filter_str(content, "'")
50    # 防xss攻击处理
51    content = string_helper.clear_xss(content)
52    is_enable = convert_helper.to_int0(web_helper.get_form('is_enable', '是否启用'))
53 
54    # 编辑记录
55    sql = """
56          update product
57            set name=%s, code=%s, product_class_id=%s, standard=%s, quality_guarantee_period=%s,
58                place_of_origin=%s, front_cover_img=%s, content=%s, is_enable=%s
59          where id=%s returning id"""
60    vars = (name, code, product_class_id, standard, quality_guarantee_period, place_of_origin, front_cover_img, content,
61            is_enable, id)
62    # 写入数据库
63    result = db_helper.write(sql, vars)
64    # 判断是否提交成功
65    if result and result[0].get('id'):
66        return web_helper.return_msg(0, '成功')
67    else:
68        return web_helper.return_msg(-1, "提交失败")

四、删除记录接口

1@delete('/api/product/<id:int>/')
2def callback(id):
3    """
4    删除指定记录
5    """
6    # 编辑记录
7    sql = """delete from product where id=%s returning id"""
8    vars = (id,)
9    # 写入数据库
10    result = db_helper.write(sql, vars)
11    # 判断是否提交成功
12    if result:
13        return web_helper.return_msg(0, '成功')
14    else:
15        return web_helper.return_msg(-1, "删除失败")

五、修改product_class_edit.html文件

六、 测试代码

暧昧帖

本文暂无标签

发表评论

*

*