def recover_password(email: str, db: Session = Depends(deps.get_db)) -> Any: """ Password Recovery """ user = crud.user.get_by_email(db, email=email) if not user: raise NotFoundException( "用户不存在" ) password_reset_token = generate_password_reset_token(email=email) send_reset_password_email( email_to=user.email, email=email, token=password_reset_token ) return resp_200({"msg": "Password recovery email sent"})
async def category_tab(db: Session = Depends(get_db), *, cate_id: int = Query(1, alias="cateId", title="分类Id")): """ 查询分类的 tab 信息 \n 需要 /category 接口返回的cateId参数 \n :param db: \n :param cate_id: int 需要传入分类id 目前数据库只有分类 1 有数据 \n :return: """ sql = f"SELECT tab_id,tab_name from mall_tab WHERE cate_id={cate_id}" goods_info = db.execute(sql) info = goods_info.fetchall() return response_code.resp_200(info)
def login(user: user.UserSignin): '''登录''' [email, phone] = map(user.dict().get, ['email', 'phone']) user = db.user.find_one({'$or': [{'email': email}, {'phone': phone}]}) try: token = tools.new_token(20) uid = str(user['_id']) redis.set(token, uid) return response_code.resp_200({ 'token': token, 'email': email, 'phone': phone, 'id': uid }) except Exception as e: return response_code.resp_401()
async def goods_tab(db: Session = Depends(get_db)): """ 切换的tab信息 \n :return: """ sql = "SELECT tab_id,tab_name from mall_tab WHERE is_home=1" query_data = db.execute(sql) return_data = [] for item in query_data: temp_data = { "tabId": item[0], "tabName": item[1], } return_data.append(temp_data) return response_code.resp_200(return_data)
async def home_banner(db: Session = Depends(get_db)): """ 首页轮播图 \n :return: 轮播图banner link, image """ sql = "select link,image from mall_banner order by id desc limit 10" banner_info = db.execute(sql) banner_data = [] for banner in banner_info: temp_data = { "link": banner[0], "image": banner[1] } banner_data.append(temp_data) return response_code.resp_200(banner_data)
def newpasswd(email: str, code: str, newpass: str, newpass2: str): '''修改密码''' if newpass != newpass2: return response_code.res_5000('密码不一致') flag = email redis_code = redis.get(f'{settings.CODE_KEY}{flag}') if redis_code != code: return response_code.resp_5000('验证码不正确') encrypt_passwd = generate_password_hash(newpass) db_user = db.user.find_one_and_update( {'email': email}, {'$set': { 'password': encrypt_passwd }}, retrundocument=ReturnDocument.AFTER) _id = str(db_user['_id']) ctx = {'email': email, 'id': _id} return response_code.resp_200('修改成功')
async def home_recommends(db: Session = Depends(get_db)): """ 首页推荐 recommends \n :return: 推荐信息: cateId, cateName, image """ sql = "select cate_id,cate_name,cate_thumbnail from mall_goods_cate order by id desc limit 8" query_data = db.execute(sql) return_data = [] for item in query_data: temp_data = { "cateId": item[0], "cateName": item[1], "image": item[2] } return_data.append(temp_data) return response_code.resp_200(return_data)
async def home_features(db: Session = Depends(get_db)): """ 首页特色 features \n :return: 返回features信息 link, image, title """ sql = "select link,features_image,title from mall_goods where is_features=1 order by goods_id desc limit 4" query_data = db.execute(sql) return_data = [] for item in query_data: temp_data = { "link": item[0], "image": item[1], "title": item[2] } return_data.append(temp_data) return response_code.resp_200(return_data)
def sendmessage(message: user.MessageBase ): #_from: str, message_to: str, message_content: str): [message_from, message_to, message_content, message_status, message_date] = \ map(message.dict().get, ['message_from', 'message_to', 'message_content', 'message_status', 'message_date']) print(message_from, message_to, message_content, message_status, message_date) _id = db.messages.insert({ 'message_from': message_from, 'message_to': message_to, 'message_content': message_content, 'message_status': False, 'message_date': time.time() }) logger.info(f'{message_from} send {message_content} to {message_to} ') redis.set(f'{settings.MESSAGE_KEY}{message_from}:{message_to}', message_content) ctx = {'code': '200', 'id': str(_id)} return response_code.resp_200(ctx)
def reset_password( token: str = Body(...), new_password: str = Body(...), db: Session = Depends(deps.get_db), ) -> Any: """ Reset password """ email = verify_password_reset_token(token) if not email: raise UnicornException("令牌无效") user = crud.user.get_by_email(db, email=email) if not user: raise NotFoundException("用户不存在") elif not crud.user.is_active(user): raise UnicornException("无效用户") hashed_password = get_password_hash(new_password) user.hashed_password = hashed_password db.add(user) db.commit() return resp_200({"msg": "Password updated successfully"})
def login_access_token( db: Session = Depends(deps.get_db), form_data: OAuth2PasswordRequestForm = Depends() ) -> Any: """ OAuth2 compatible token login, get an access token for future requests """ user = crud.user.authenticate( db, email=form_data.username, password=form_data.password ) if not user: raise NotFoundException("用户不存在") elif not crud.user.is_active(user): raise UnicornException("无效用户") access_token_expires = timedelta( minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) return resp_200({ "access_token": security.create_access_token( user.id, expires_delta=access_token_expires ), "token_type": "bearer", })
def sendmessage(message: user.MessageBase): [message_from, message_to, message_content, message_date] = \ map(message.dict().get, ['message_from', 'message_to', 'message_content', 'message_date']) try: _id = db.messages.find_one_and_update( { 'message_from': message_from, 'message_to': message_to, 'message_content': message_content }, {'$set': { 'message_status': True, 'message_date': message_date }}, retrundocument=ReturnDocument.AFTER) assert _id logger.info( f'del {message_from} send {message_content} to {message_to} ') redis.delete(f'{settings.MESSAGE_KEY}{message_from}:{message_to}', message_content) ctx = {'code': '200', 'id': str(_id)} return response_code.resp_200(ctx) except Exception as e: return response_code.resp_500()
async def get_date_json(year: str, month: str): if len(year) != 4 or len(month) != 2 or month not in ['01', '04', '07', '10']: return Response.resp_400(data=None, message='参数错误!') return Response.resp_200(data=await get_data_json(year + month))
def test_token(current_user: models.User = Depends(deps.get_current_user)) -> Any: """ Test access token """ return resp_200(current_user)
async def goods_detail(*, db: Session = Depends(get_db), goods_info: GoodsInfo): """ 商品详情页信息 \n goodsId 商品id 默认123 额 也只有123哈哈哈 \n :param: db :param: goods_info :return: """ sql = f"""select goods_id, banners, title, price, original_price, sales_volume, sales_collect,sales_deliver, discount_volume, discount_activity, logistics_info, shop_id, goods_image, goods_desc from mall_goods_detail where goods_id={goods_info.goodsId}""" goods_res = db.execute(sql) info = goods_res.fetchone() if not info: raise custom_exc.PostParamsError( err_desc=f"数据库没有goodsId为{goods_info.goodsId}的数据") data = { "goodsId": goods_info.goodsId, "banners": str(info[1]).split(","), "title": info[2], "price": info[3], "original_price": info[4], "sales_volume": info[5], "sales_collect": info[6], "sales_deliver": info[7], "discount_volume": str(info[8]).split(","), "discount_activity": str(info[9]).split(","), "logistics_info": str(info[10]).split(","), # 11 物流信息 "goods_image": str(info[12]).split(","), "goods_desc": info[13], } shop_id = info[11] shop_sql = f"""select shop_name, shop_image,credit_rating, goods_num, follow, cumulative_sales from mall_shop where shop_id={shop_id}""" shop_res = db.execute(shop_sql) shop_res = shop_res.fetchone() shop_info = { "shopName": shop_res[0], "shopImage": shop_res[1], "creditRating": shop_res[2], "goodsNum": shop_res[3], "follow": shop_res[4], "cumulativeSales": shop_res[5], } data["shopInfo"] = shop_info comment_sql = f"""select user_id, comment, buy_info from mall_goods_comment where goods_id={goods_info.goodsId} order by id desc limit 2""" comment_res = db.execute(comment_sql) comment_res = comment_res.fetchall() comment_info = [] for i in comment_res: temp_comment = { "userName": "******", "userImage": "https://s5.mogucdn.com/p1/160105/idid_ifrwenjuhfsggntfguzdambqhayde_160x160.jpg_48x48.webp", "comment": i[1], "buyInfo": str(i[2]).split(",") } comment_info.append(temp_comment) data["commentInfo"] = comment_info # 规格直接偷懒 data["spec"] = { "info": { "set": { "厚薄": "普通", "颜色": "黄色套装", "尺码": "S,XL,L,M,XXL", "衣长": "常规款(51-65cm)", "季节": "夏季", "材质": "其他", "领型": "其他领型", "袖长": "五分袖(中袖)", "款式": "衣裤套装", "风格": "简约" }, "key": "产品参数", "anchor": "product_info" }, "rule": { "tables": [[["尺码", "胸围", "腰围", "袖长", "肩宽"], ["S", "96", "64", "31", "36"], ["M", "100", "68", "32", "37"], ["L", "104", "72", "33", "38"], ["XL", "108", "76", "34", "39"], ["XXL", "112", "80", "35", "40"]]], "key": "尺码说明", "anchor": "size_info", "disclaimer": "※ 以上尺寸为实物人工测量,因测量方式不同会有1-2cm误差,相关数据仅作参考,以收到实物为准。" } } return response_code.resp_200(data)
async def home_goods( db: Session = Depends(get_db), tab_id: int = Query(0, alias="tabId"), page: int = 1, page_size: int = Query(10, alias="pageSize", le=50)): """ 切换的 tab 商品信息\n :param db :param tab_id 指定的tabId 类型 默认0 全部分类查询前10条\n :param page 当前多少页 默认第1页\n :param page_size 每页数量 默认10条\n :return: """ logger.info("首页商品切换请求正常") # 由于limit 从0开始,所以 默认-1 offset = (page - 1) * page_size if tab_id: # 查询当前分类到数量 count_sql = f"select count(1) from mall_goods where tab_id={tab_id}" count_data = db.execute(count_sql) all_count = count_data.fetchone()[0] if all_count <= 0: return_data = { "msg": f"当前查找的tabID:{tab_id}不存在, /home/tab 此接口获取tabId" } else: sql = f"SELECT link,image,title,price,collection from mall_goods WHERE tab_id={tab_id} order by goods_id desc limit {offset}, {page_size}" query_data = db.execute(sql) return_data = { "item": [], "pageInfo": { "allCount": all_count, "page": page, "pageSize": page_size } } for item in query_data: temp_data = { "tabId": tab_id, "link": item[0], "image": item[1], "title": item[2], "price": item[3], "collection": item[4], } return_data["item"].append(temp_data) else: # 默认查询全部分类 的前10条记录 sql = "SELECT tab_id,tab_name from mall_tab WHERE is_home=1" tab_res = db.execute(sql) # 查询出每个分类的前10条数据 # Tip: 我SQL 好弱 花了快1小时没解决,放弃,用笨办法 搜到这个也没解决https://stackoverflow.com/questions/12113699/get-top-n-records-for-each-group-of-grouped-results return_data = [] # 循环每个tab for tab in tab_res.fetchall(): data_sql = f"""SELECT tab_id,link,image,title,price,collection from mall_goods WHERE tab_id={tab[0]} order by goods_id desc limit 0, {page_size}""" query_data = db.execute(data_sql) goods_item = { "page": 1, "tabId": tab[0], "tabName": tab[1], "item": [], } for goods in query_data: temp_goods = { "link": goods[1], "image": goods[2], "title": goods[3], "price": goods[4], "collection": goods[5], } goods_item["item"].append(temp_goods) return_data.append(goods_item) return response_code.resp_200(return_data)