def bianji(request): if request.method == 'POST': goods = Goods() str1 = str(time.time()) time1 = str1.split('.')[0] goods.childcid = request.POST.get('childcid') goods.productname = request.POST.get('productname') goods.productlongname = request.POST.get('productlongname') goods.categoryid = request.POST.get('categoryid') goods.childcidname ='x' print() # 头像 imgName = time1+'.png' imgPath = os.path.join(settings.IMG_ROOT, imgName) print(imgPath) file = request.FILES.get('file') print(file) if file == None: imgName = 'axf.png' else: with open(imgPath, 'wb') as fp: for data in file.chunks(): fp.write(data) goods.productimg = 'http://127.0.0.1:8000/static/market/img/'+imgName goods.save() # 重定向 return redirect('axf:home') elif request.method == 'GET': return render(request, 'market/bianji.html')
def post(self): # g_name = request.form.get('g_name') # g_price = request.form.get('g_price') # 使用request.form获取的参数无校验功能 args = parser.parse_args() g_name = args.get('g_name') g_price = args.get('g_price') print(args.get('mu')) # 当该参数设置了append的action后get到的就是一个list print(args.get('User-Agent')) goods = Goods() goods.g_name = g_name goods.g_price = g_price if not goods.save(): abort(400) # data = { # 'status': 200, # 'msg': 'create success', # 'data': marshal(goods, good_fields), # } data = { 'status': 200, 'msg': 'create success', 'data': goods, # 'test': 'haha' # 如果这个字段在fields中没有,则最后返回的结果会被忽略这个字段的内容 } return data
def index(request): for i in range(1,8): wheels=Wheel() wheels.name='goodsbanner-'+str(i)+'.jpg' wheels.img='img/'+wheels.name wheels.save() goods=Goods() goods.name='goodsbanner-'+str(i)+'.jpg' goods.img='img/'+goods.name goods.price=100*i goods.store_num=10*i goods.save() goods = Goods.objects.all()[1:5] wheels = Wheel.objects.all() tuijians = Tuijian.objects.all() token = request.session.get('token') userid = cache.get(token) if userid: user = User.objects.get(pk=userid) return render(request, 'index.html', context={'wheels': wheels, 'tuijians': tuijians, 'user': user, 'token': token, 'goods': goods}) else: return render(request, 'index.html', context={'wheels': wheels, 'tuijians': tuijians, 'goods': goods})
def post(self): # g_name=request.form.get('g_name') # g_price=request.form.get('g_price') args = parser.parse_args() g_name = args.get('g_name') g_price = args.get('g_price') goods = Goods() goods.g_name = g_name goods.g_price = g_price if not goods.save(): abort(404) data = {"msg": "create success", "status": 201, "data": goods} return data
def goods_add(): """ 添加商品 """ form = GoodsForm() # 实例化form表单 supercat_list = [(v.id, v.cat_name) for v in SuperCat.query.all()] # 为super_cat_id添加属性 form.supercat_id.choices = supercat_list # 为super_cat_id添加属性 form.subcat_id.choices = [(v.id, v.cat_name) for v in SubCat.query.filter_by( super_cat_id=supercat_list[0][0]).all() ] # 为super_cat_id添加属性 form.current_price.data = form.data['original_price'] # 为current_pirce 赋值 if form.validate_on_submit(): # 添加商品情况 data = form.data goods = Goods( name=data["name"], supercat_id=int(data['supercat_id']), subcat_id=int(data['subcat_id']), picture=data["picture"], original_price=Decimal(data["original_price"]).quantize( Decimal('0.00')), # 转化为包含2位小数的形式 current_price=Decimal(data["original_price"]).quantize( Decimal('0.00')), # 转化为包含2位小数的形式 is_new=int(data["is_new"]), is_sale=int(data["is_sale"]), introduction=data["introduction"], ) db.session.add(goods) # 添加数据 db.session.commit() # 提交数据 return redirect(url_for('admin.index')) # 页面跳转 return render_template("admin/goods_add.html", form=form) # 渲染模板
def index(): PvCount.add_home_count() data_carousel = Goods.search_for_carousel() data_user = User.query_for_homepage() data_recommend = Goods.query.filter(Goods.status == True).order_by( Goods.view_count.asc()).limit(6).all() data_hot_word = WordCloud.query_for_max_on_window(90, 1) return render_template('main/index.html', data_carousel=data_carousel, data_user=data_user, data_hot_word=data_hot_word, data_recommend=data_recommend)
def index(): if request.method == 'GET': '''首页获取货物列表''' try: goodslist = Goods.query.all() except Exception as e: current_app.logger.debug(e) return jsonify(code="500", msg="获取货物列表失败") goodss = [goods.to_json() for goods in goodslist] return jsonify(code="200", msg="获取货物列表成功", goodss=goodss) if request.method == 'POST': '''新增货物''' title = request.values.get("title") price= request.values.get("price") stock = request.values.get("stock") storage_location = request.values.get("storage_location") if not all ([title, price, stock, storage_location]): return jsonify(code="403", msg="参数错误") goods = Goods() goods.title = title goods.price = price goods.stock = stock goods.storage_location = storage_location try: db.session.add(goods) db.session.commit() except Exception as e: current_app.logger.debug(e) db.session.rollback() return jsonify(code="500", msg="添加货物失败") return jsonify(code="200", msg="添加货物成功")
def addGoods(request): goods = Goods() goods.g_name = 'iphone-' + str(random.randrange(1, 20)) goods.g_price = random.randrange(9999, 20000) goods.save() return HttpResponse('添加商品成功: ' + goods.g_name)
def put_data_in_db_2(): data = take_data_from_source_2() for station_id in data.keys(): station = Stations.query.filter_by(id=station_id).first() if station is None: station = Stations(id=station_id) db.session.add(station) for title in data[station_id].keys(): amount = data[station_id][title][0] currency = data[station_id][title][1] goods = Goods.query.filter_by(title=title, station_id=station_id).first() if goods is None: goods = Goods(title=title, amount=float(amount), currency=currency) db.session.add(goods) station.goods.append(goods) else: goods.amount = amount goods.currency = currency db.session.commit()
def addgoods(request): goods = Goods() names = ['小米', '锤子', '红米', 'oppo', '华为', '魅族', '魅蓝'] temp = random.randrange(0, len(names)) goods.g_name = names[temp] + '-' + str(random.randrange(10, 100)) goods.g_price = random.randrange(100, 1000) goods.save() return HttpResponse('添加商品成功')
def goodlist(): if request.method == 'GET': goods = Goods() #实例化Goods类,进行ORM映射 Session = sessionmaker(bind=goods.engine) #创建当前会话 session = Session() shop_goods = session.query(goods.apply_table).first() print(shop_goods) return 'ok' # if __name__ == '__main__': # app.run('',8003)
def addgoods(request): goods = Goods() arr = ['iPhone', 'iPad', 'iPod', 'MacBook Pro', 'MacBook Air'] temp = random.randrange(0, len(arr)) goods.g_name = arr[temp] + '-' + str(random.randrange(0, 10)) goods.g_price = random.randrange(10000, 100000) goods.save() return HttpResponse('添加商品成功')
def new_good(): if request.method == 'POST': launch_date = request.form.get('launch_date') launch_date = datetime.strptime(launch_date, "%Y-%m-%d") good = Goods(numbers=request.form.get('numbers'), brand=request.form.get('brand'), tag=request.form.get('tag'), colour=request.form.get('colour'), buying_price=request.form.get('buying_price'), launch_date=launch_date, counts=request.form.get('counts'), remark=request.form.get('remark')) db.session.add(good) db.session.commit() flash('商品成功上架.', 'success') return redirect(url_for('goods.manage_good')) return render_template('new_goods.html')
def goods_add(): '''添加商品''' form = GoodsForm() # 实例化form表单 supercat_list = [(sup.id, sup.cat_name) for sup in SuperCat.query.all()] # 为大分类super_cat_id添加属性 form.supercat_id.choices = supercat_list # 为大分类标签添加选项 # print(supercat_list) form.subcat_id.choices = [(sub.id, sub.cat_name) for sub in SubCat.query.filter_by( super_cat_id=supercat_list[0][0]).all() ] # 先默认选00 在通过前端get请求区分选了哪个小分类 form.current_price.data = form.data[ 'original_price'] # 为current_price 赋值 默认让现价等于原价 if form.validate_on_submit(): # 验证通过 添加商品情况 data = form.data # 实现图片上传并储存 入库 # 生成随机字符串,防止图片名字重复 ran_str = ''.join( random.sample(string.ascii_letters + string.digits, 16)) pic_file = request.files['pic_file'] basedir = '/Users/mac/Desktop/MyPyPro/Pro/shopping_mall_pro/app' path = basedir + "/static/images/goods/" # 图片名称 给图片重命名 为了图片名称的唯一性 pic_file_name = ran_str + '.' + (pic_file.filename).split('.')[-1] #图片path和名称组成图片的保存路径 file_path = path + pic_file_name # 保存图片 pic_file.save(file_path) goods = Goods( name=data['name'], supercat_id=int(data['supercat_id']), subcat_id=int(data['subcat_id']), # 替换成新命名的图片名称 picture=pic_file_name, original_price=Decimal(data['original_price']).quantize( Decimal('0.00')), # 转化为包含2位小数的形式 current_price=Decimal(data['current_price']).quantize( Decimal('0.00')), is_new=int(data['is_new']), is_sale=int(data['is_sale']), introduction=data['introduction']) db.session.add(goods) db.session.commit() return redirect(url_for('admin.index')) return render_template('admin/goods_add.html', form=form) # get请求渲染模板
def update_goods(type_id, goods_id=None): """ 处理商品的添加和修改 :param type_id: 用于定位返回页面的位置 :param goods_id: 商品ID """ form = GoodsForm() goods = Goods.query.get_or_404(goods_id) if goods_id else None form.goods_obj_id = goods.id if goods else None if request.method == 'GET': if type_id > 0: form.type.data = type_id for item in GoodsImg.query.filter_by(status=False, user_id=current_user.id).all(): # 清理未关联的商品图 item.delete() if goods is not None: # 商品编辑时的表单内容注入 form.set_data(goods) if form.validate_on_submit(): kwargs = { 'number': form.number.data, 'type': form.type.data, 'cash_pledge': form.cash_pledge.data, 'size': form.size.data, 'brand': form.brand.data, 'quantity': form.quantity.data, 'details': form.details.data } if goods is None: if GoodsImg.query.filter_by(status=False, user_id=current_user.id).first(): Goods().add(form.name.data, form.price.data, **kwargs) flash('商品添加成功。') return redirect(url_for('.index', tid=form.type.data)) else: flash('请添加商品图。') else: goods.edit(form.name.data, form.price.data, **kwargs) flash('商品修改成功。') return redirect( url_for('.index', tid=type_id) + '#goods_{}'.format(goods_id)) return render_template('goods/update_goods.html', form=form, goods=goods)
def login_goods(): form = Login_Goods() # form = Login_Goods(request.method, obj=locker) # form.locker_id.choices = [(g.lockername) for g in locker] # 如果触发form实例对象中的submit的该事件。 if form.validate_on_submit(): goods = Goods(goodsname=form.goodsname.data, locker=form.locker.data, category=form.category.data, about_goods=form.about_goods.data) db.session.add(goods) db.session.commit() # print(form.locker.data) flash("Your goods is have been created!") return redirect(url_for('goods')) return render_template('/goods/login_goods.html', title='Login_Good', form=form)
def dd(): req = reqdata() url = "http://e.dangdang.com/media/api.go?action=mediaCategoryLeaf&promotionType=1&deviceSerialNo=html5&macAddr=html5&channelType=html5&permanentId=20190311144828373429030242631487465&returnType=json&channelId=70000&clientVersionNo=5.8.4&platformSource=DDDS-P&fromPlatform=106&deviceType=pconline&token=&start=21&end=41&category=ZTXYTL&dimension=dd_sale&order=0" try: res = req.requrl(url) jsonstr = json.loads(res) dic_json = jsonstr['data']['saleList'] product_list_to_insert = list() for each_json in dic_json: goods = Goods() jsons = each_json['mediaList'][0] goods.goods_name = jsons['title'] goods.goods_category = jsons['categorys'] goods.goods_summary = jsons['coverPic'] goods.goods_price = jsons['lowestPrice'] goods.goods_detail = jsons['descs'] goods.create_name = jsons['authorPenname'] product_list_to_insert.append(goods) Goods.objects.bulk_create(product_list_to_insert) return '下载成功' except Exception as e: return str(e)
def new_good(): form = GoodsCreationForm() form.set_cat_choices() if form.validate_on_submit(): filename = secure_filename(form.image.data.filename) form.image.data.save( os.path.join(app.config['UPLOAD_FOLDER'], filename)) crop_img(filename) goods = Goods(name=form.name.data, category=int(form.category.data), price=form.price.data, image=form.image.data.filename, description=form.description.data) db.session.add(goods) db.session.commit() flash('New good created') os.path.join(app.config['UPLOAD_FOLDER'], filename) return redirect(url_for('index')) return render_template('admin/newgood.html', title="New Good", form=form)
def goods_add(): form = GoodsForm() supercat_list = [(item.id, item.cat_name) for item in SuperCat.query.all()] form.supercat_id.choices = supercat_list subcat_list = [(item.id, item.cat_name) for item in SubCat.query.all()] form.subcat_id.choices = subcat_list if form.validate_on_submit(): goods = Goods( name=form.name.data, original_price=Decimal(form.original_price.data).quantize( Decimal('0.00')), current_price=Decimal(form.original_price.data).quantize( Decimal('0.00')), picture=form.picture.data, introduction=form.introduction.data, is_sale=int(form.is_sale.data), is_new=int(form.is_new.data), supercat_id=int(form.supercat_id.data), subcat_id=int(form.subcat_id.data), ) db.session.add(goods) db.session.commit() return redirect(url_for('admin.index')) return render_template('admin/goods_add.html', form=form)
def add_goods(): # 获取用户输入信息 title = request.form.get('title') img = request.files.get('img') price = request.form.get('price') detail = request.form.get('detail') if not title: return jsonify({'code': '601', 'msg': '商品名称不能为空!'}) if not price: return jsonify({'code': '602', 'msg': '请输入商品价格!'}) # 保存图片 if img: # 获取项目根路径 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 获取媒体文件路径 MEDIA_DIR = os.path.join(BASE_DIR, 'static/media') # 随机生成图片名称 filename = str(uuid.uuid4()) i = img.mimetype.split('/')[-1] image = filename + '.' + i # 拼接图片地址 path = os.path.join(MEDIA_DIR, image) img.save(path) img_url = '/static/media/' + image else: img_url = '' # 存储到数据库 goods = Goods() goods.title = title goods.img_url = img_url goods.price = price goods.detail = detail db.session.add(goods) db.session.commit() return jsonify({'code': 200, 'msg': '添加成功'})
def spiders(): # eval(str转dict)需要的参数 true = True false = False null = None qthing = request.values.get('q') api = r'https://s.taobao.com/api?_ksTS=1523179236254_226&callback=jsonp227&ajax=true&m=customized&stats_%27%20\%20%27click=search_radio_all:1&q={}&s=1&imgfile=&initiative_id=staobaoz_20180425&bcoffset=-1%27%20\%20%27&js=1&ie=utf8&rn=d5706a3802513dad625d594a35702a6b'.format(urllib.request.quote(qthing)) current_app.logger.debug(api) rep = urllib.request.urlopen(api).read().decode('utf-8') result = eval(re.findall(r'jsonp227(.*?);', rep)[0][1:-1].strip().replace("\n", "")) for r in result['API.CustomizedApi']['itemlist']['auctions']: #r = result['API.CustomizedApi']['itemlist']['auctions'][0] title = r["raw_title"]#re.sub(r'<[^>]+>', '', r["title"]) price = r["view_price"] stock = r["comment_count"] if " " in r["item_loc"]: storage_location = r["item_loc"].split(" ")[-1] else: storage_location = r["item_loc"] goods = Goods() goods.title = title goods.price = price goods.stock = stock goods.storage_location = storage_location try: db.session.add(goods) db.session.commit() except Exception as e: current_app.logger.debug(e) db.session.rollback() return jsonify(code="500", msg="添加货物失败") return jsonify(code="200", msg="添加货物成功")
def goodsup(request): token = request.session.get('token') userid = cache.get(token) if userid: user = User.objects.get(pk=userid) if request.method == 'GET': return render(request, 'mine/goodsup.html') elif request.method == 'POST': goods = Goods() goodsname = request.POST.get('goodsname') price = request.POST.get('price') title = request.POST.get('title') num = request.POST.get('num') type = request.POST.get('type') file = request.FILES['file'] file.name = str(time.time()) + str(file.name) filepath = os.path.join(settings.GOODSIMG_ROOT, file.name) with open(filepath, 'wb') as fp: for info in file.chunks(): fp.write(info) goods.img = 'img/' + file.name goods.bigimg = 'img/' + file.name goods.name = goodsname goods.price = "¥" + price goods.num = num goods.title = title goods.fatherid = type goods.save() publish = Publish() publish.goods = goods publish.user = user publish.save() return redirect('app:index') else: return redirect('app:login')
print('*****') print('t1') print(t1) print('\n') #print(text_list) print('text') print(text) # sql语句 #sql = "insert into test_db values (0,%s,%s,%s,%s,%s)" #print(sql) # 参数化方式传参 #row_count = cur.execute(sql, [text[0], text[1], text[2], text[3], text[4]]) # 显示操作结果 #print("SQL语句影响的行数为%d" % row_count) newgoods = Goods(info_img=text[0], goods_name=text[1], group_person=text[2],goods_sale_num=text[3], goods_num=text[4], goods_now_price=text[5], goods_price=text[6], goods_low_price=text[7],goods_brief=text[8]) db.session.add(newgoods) db.session.commit() goods = Goods().query.all() # for i in goods: # # print(i) #print(i[0]) #json.dumps(goods) #print(goods) #统一提交 #conn.commit() # 关闭游标 #cur.close()
def goods_update(): try: res = request.get_json() goods_id = res.get('goods_id') name = res.get('name') price = res.get('price') ku_num = res.get('ku_num') detail = res.get('detail') # {'image_data':[{'img_url':'http:xxx','is_min':1},{'img_url':'http:xxx','is_min':0}]} image_data = res.get('image_data') # img_url = res.get('img_url') postage = res.get('postage') admin_id = g.user_id Logging.logger.info('request_args:{0}'.format(res)) if not all([name, price, ku_num, image_data, postage]): return jsonify(errno=-1, errmsg='参数不完整') try: price = int(price) ku_num = int(ku_num) postage = int(postage) except Exception as e: Logging.logger.error('errmsg:{0}'.format(e)) return jsonify(errno=-1, errmsg='参数错误') if goods_id: # 修改 try: goods_id = int(goods_id) except Exception as e: Logging.logger.error('errmsg:{0}'.format(e)) return jsonify(errno=-1, errmsg='参数错误') goods_obj = Goods.query.get(goods_id) if not goods_obj: return jsonify(errno=-1, errmsg='当前商品不存在') goods_obj.name = name goods_obj.price = price now_available_num = ku_num - (goods_obj.ku_num - goods_obj.available_num) if now_available_num < 0: return jsonify(errno=-1, errmsg='商品库存数量不能小于原已兑换数量') goods_obj.available_num = now_available_num goods_obj.ku_num = ku_num goods_obj.detail = detail goods_obj.postage = postage goods_obj.admin_id = admin_id # goods_obj.img_url = img_url if image_data: # 删除原有的商品轮播图片 goods_img = GoodsImage.query.filter( GoodsImage.goods_id == goods_id).all() for img in goods_img: db.session.delete(img) # 添加新的图片 for image in image_data: image_obj = GoodsImage() image_obj.goods_id = goods_id image_obj.img_url = image.get('img_url') image_obj.is_min = image.get('is_min') db.session.add(image_obj) db.session.add(goods_obj) else: # 新增 goods = Goods.query.filter(Goods.name == name).first() if goods: return jsonify(errno=-1, errmsg='该商品名称已经存在') goods_obj = Goods() goods_obj.name = name goods_obj.price = price goods_obj.ku_num = ku_num goods_obj.available_num = ku_num goods_obj.detail = detail goods_obj.postage = postage goods_obj.admin_id = admin_id # goods_obj.img_url = img_url db.session.add(goods_obj) db.session.commit() for image in image_data: image_obj = GoodsImage() image_obj.goods_id = goods_obj.id image_obj.img_url = image.get('img_url') image_obj.is_min = image.get('is_min') db.session.add(image_obj) db.session.commit() return jsonify(errno=0, errmsg="OK") except Exception as e: Logging.logger.error('errmsg:{0}'.format(e)) db.session.rollback() return jsonify(errno=-1, errmsg='更新商品失败')
def getGoods(): goods = Goods().query.all() jsonGoods = json.dumps(goods, cls=AlchemyJsonEncoder) return jsonGoods