def sell_register(): form = SellForm(request.form) if request.method == 'POST': # 画像ファイルの移動 item_temp_image->item_image shutil.move( os.path.join(app.config["ITEM_TEMP_IMAGE_UPLOADS"], form.item_picture_path.data), app.config["ITEM_IMAGE_UPLOADS"]) userid = current_user.get_id() sell = Sell(User_id=userid, sell_title=form.sell_title.data, key1=form.key1.data, key2=form.key2.data, key3=form.key3.data, sell_comment=form.sell_comment.data, price=form.price.data, item_picture_path=form.item_picture_path.data, genre=form.genre.data, item_state=form.item_state.data, postage=form.postage.data, send_way=form.send_way.data, consignor=form.consignor.data, schedule=form.schedule.data, remarks=form.remarks.data) # データベース処理 with db.session.begin(subtransactions=True): # Sellテーブルにレコードの挿入 sell.create_new_sell() db.session.commit() return redirect(url_for('sell.sell_complete', item_id=sell.Sell_id)) return redirect(url_for('route.home'))
def mypagetop(): # ログイン中のユーザーがユーザーページのユーザーをフォローしているかの判定 followed = UserConnect.followed_exists(current_user.User_id) follows = UserConnect.select_follows_by_user_id(current_user.User_id) good_ratings_count, bad_ratings_count = Rating.select_rate_by_user_id( current_user.User_id) # 売上金 sales = Sell.select_sales(current_user.User_id) sales = sales.sumprice # ユーザーが出品した商品 items = Sell.select_sell_by_user_id_sort(current_user.User_id) # 最近見た本 b_items = BrowsingHistory.b_history_join_sell(Sell, current_user.User_id) # ログイン中のユーザーが過去にどの商品をいいねしたかを格納しておく liked_list = [] for item in items: liked = Likes.liked_exists(item.Sell_id) if liked: liked_list.append(item.Sell_id) for item in b_items: liked = Likes.liked_exists(item.Sell_id) if liked: liked_list.append(item.Sell_id) return render_template('mypage/mypage.html', followed=followed, follows_count=len(follows), good_ratings_count=good_ratings_count, bad_ratings_count=bad_ratings_count, items=items, liked_list=liked_list, post_c=len(items), b_items=b_items, sales=sales)
def getRecommendations(c_userid): """c_userid以外のユーザーの評点の重み付き平均を行い、c_useridへの推薦を算出する""" prefs = loadData() prefs.setdefault(c_userid, {}) on_display = Sell.select_all_sell_by_deal_status(1) sell = Sell.select_sell_id_by_user_id(c_userid) followed = UserConnect.select_follows_user_id_by_user_id(c_userid) # 一次元タプルに変換 on_display = sum(on_display, ()) followed = sum(followed, ()) sell = sum(sell, ()) totals = {} simSums = {} for other in prefs: # 自分自身とは比較しない if other == c_userid: continue sim = sim_pearson(prefs, c_userid, other) # 0以下のスコアは無視する if sim <= 0: continue for item in prefs[other]: # 評価が1か0かつ自分が出品した商品以外 if (item not in prefs[c_userid] or prefs[c_userid][item] == 0 or prefs[c_userid][item] == 1) and int(item) not in sell: # 出品中の商品の特典のみを算出 if int(item) in on_display: # 類似度*スコア totals.setdefault(item, 0) totals[item] += prefs[other][item] * sim # 類似度を合計 simSums.setdefault(item, 0) simSums[item] += sim #正規化したリストを作る rankings = [(total / simSums[item], item) for item, total in totals.items()] # ソート済みのリストを返す rankings.sort() rankings.reverse() print("*" * 100) print("アイテムレコメンド") print(rankings) print("*" * 100) recommend_id = np.array(rankings) if len(recommend_id) > 0: if len(recommend_id) >= 3: #! X[start:end]endは含まれない return recommend_id[0:3, 1] if len(recommend_id) == 2: return recommend_id[0:2, 1] if len(recommend_id) == 1: return recommend_id[0, 1] else: return None
def sell_delete(): form = SellUpdateFlgAndDeleteForm(request.form) if request.method == 'POST': with db.session.begin(subtransactions=True): Sell.delete_sell(form.Sell_id.data) BrowsingHistory.delete_b_history(form.Sell_id.data) Likes.delete_all_like(form.Sell_id.data) db.session.commit() flash('削除しました') return redirect(url_for('history.sell_on_display')) return redirect(url_for('route.home'))
def userdata(user_code): user = User.select_user_by_user_code(user_code) if user is None: return redirect(url_for('route.home')) follows = UserConnect.select_follows_by_user_id(user.User_id) good_ratings_count,bad_ratings_count = Rating.select_rate_by_user_id(user.User_id) # ユーザーが出品した商品 items = Sell.select_sell_by_user_id_sort(user.User_id) # レコメンドリスト if current_user.is_authenticated: r_user_list = u_recommend(user.User_id,current_user.User_id) else: r_user_list = u_recommend(user.User_id) # ログイン中のユーザーがユーザーをフォローしているかの判定 f_users = [] f_users.append(user) f_users.extend(r_user_list) followed_list = [] if current_user.is_authenticated: for f_user in f_users: followed = UserConnect.followed_exists(f_user.User_id) if followed: followed_list.append(f_user.User_id) # ログイン中のユーザーが過去にどの商品をいいねしたかを格納しておく liked_list = [] if current_user.is_authenticated: for item in items: liked = Likes.liked_exists(item.Sell_id) if liked: liked_list.append(item.Sell_id) return render_template( 'user/userdata.html', user=user, followed_list=followed_list, follows_count=len(follows), good_ratings_count=good_ratings_count, bad_ratings_count=bad_ratings_count, items=items, liked_list=liked_list, post_c=len(items), r_user_list=r_user_list )
def home(): """ホーム(新着順)""" # セッションの破棄 session.pop('pay_way', None) session.pop('Credit_id', None) session.pop('ShippingAddress_id', None) # 出品状態、有効フラグが有効の商品を新着順に取り出す items = Sell.select_new_sell() # レコメンドリスト r_item_list = [] r_user_list = [] if current_user.is_authenticated: r_item_list, r_user_list = recommend(current_user.User_id) # ログイン中のユーザーが過去にどの商品をいいねしたかを格納しておく liked_list = [] if current_user.is_authenticated: for item in items: liked = Likes.liked_exists(item.Sell_id) if liked: liked_list.append(item.Sell_id) return render_template('home.html', items=items, liked_list=liked_list, r_item_list=r_item_list, r_user_list=r_user_list)
def todolist_count(): """やることリストの数をカウントして返す""" count = 0 user_id = current_user.get_id() items = Sell.select_sall_status(user_id) for item in items: # 出品者 if item.User_id==user_id: buy_data = Buy.select_buy_by_sell_id(item.Sell_id) rating = Rating.select_count_sell_id_to_user_id(item.Sell_id, user_id) # 未発送 if item.has_sent == item.has_got == False: count += 1 # 発送済みで受け取り・評価待ち elif item.has_sent == True and item.has_got == False: count += 0 # 受け取り済みで相手が相互評価して自分がしてない elif item.has_sent == item.has_got == True and rating == 1: count += 1 #購入者 else: rating = Rating.select_count_sell_id_to_user_id(item.Sell_id, item.User_id) # 発送済みで商品を受取ってない if item.has_sent == True and item.has_got == False: count += 1 # 発送待ち elif item.has_sent == item.has_got == False: count += 0 # 評価待ち elif item.has_sent == item.has_got == True: count += 0 return dict(todolist_count=count)
def buy_complete(item_id): sell = Sell.select_sell_by_sell_id(item_id) buy = Buy.select_buy_by_sell_id(item_id) # レコメンドキャッシュのクリア # 読み込み速度の問題によりデモではキャッシュクリアを行わない # getRecommendations.cache_clear() # topMatches.cache_clear() return render_template('buy/buy_complete.html', item=sell, buy=buy)
def decorated_function(*args, **kwargs): sell_id = kwargs['item_id'] sell = Sell.select_sell_by_sell_id(sell_id) if sell is None: return redirect(url_for('route.home')) else: if sell.User_id != current_user.User_id: return redirect(url_for('route.home')) return func(*args, **kwargs)
def buy(item_id): """購入処理""" form = HiddenBuyForm(request.form) item = Sell.select_sell_by_sell_id(item_id) if request.method == 'POST' and form.validate(): user_id = current_user.get_id() s_address = ShippingAddress.search_shippingaddress( form.ShippingAddress_id.data) if form.pay_way.data == '2': credit = Credit.search_credit(form.Credit_id.data) buycredit = BuyCredit(credit_name=credit.credit_name, credit_num=credit.credit_num, expire=credit.expire, security_code_hash=credit.security_code_hash) with db.session.begin(subtransactions=True): buycredit.create_new_buycredit() db.session.commit() buyshippingaddress = BuyShippingAddress( last_name=s_address.last_name, first_name=s_address.first_name, last_name_kana=s_address.last_name_kana, first_name_kana=s_address.first_name_kana, zip_code=s_address.zip_code, prefecture=s_address.prefecture, address1=s_address.address1, address2=s_address.address2, address3=s_address.address3) with db.session.begin(subtransactions=True): buyshippingaddress.create_new_buyshippingaddress() db.session.commit() creditid = "" if form.pay_way.data == '2': creditid = buycredit.BuyCredit_id buy = Buy(User_id=user_id, Sell_id=item_id, pay_way=form.pay_way.data, Credit_id=creditid, ShippingAddress_id=buyshippingaddress.BuyShippingAddress_id) with db.session.begin(subtransactions=True): buy.create_new_buy() item.deal_status = Deal_status['取引中'] item.update_at = datetime.datetime.now() db.session.commit() # セッションの破棄 session.pop('pay_way', None) session.pop('Credit_id', None) session.pop('ShippingAddress_id', None) return redirect(url_for('buy.buy_complete', item_id=item_id)) return render_template('buy/buy.html', item=item, form=form)
def sell_flg_update(): form = SellUpdateFlgAndDeleteForm(request.form) # データベース処理 if request.method == 'POST': sell = Sell.select_sell_by_sell_id(form.Sell_id.data) with db.session.begin(subtransactions=True): if sell.sell_flg: sell.sell_flg = False flash('出品を一時停止しました') else: sell.sell_flg = True flash('出品を再開しました') db.session.commit() return redirect(url_for('item.itemdata', item_id=form.Sell_id.data)) return redirect(url_for('route.home'))
def transaction(item_id): """取引画面処理""" item = Sell.select_sell_by_sell_id(item_id) buy = Buy.select_buy_by_sell_id(item_id) shippingaddress = ShippingAddress.search_shippingaddress(buy.ShippingAddress_id) messageform = DealMessageForm(request.form) messages = DealMessage.get_messages_by_sell_id(item_id) noticeform = NoticeRatingForm(request.form) # ログイン中のユーザーが出品者だった場合 if current_user.User_id == item.User_id: dest_user = User.select_user_by_id(buy.User_id) # ログイン中のユーザーが購入者だった場合 elif current_user.User_id == buy.User_id: dest_user = User.select_user_by_id(item.User_id) read_message_ids = [message.DealMessage_id for message in messages if (not message.is_read) and (message.from_user_id == int(dest_user.User_id))] if read_message_ids: with db.session.begin(subtransactions=True): # is_readをTrueに更新 DealMessage.update_is_read_by_ids(read_message_ids) db.session.commit() not_checked_message_ids = [message.DealMessage_id for message in messages if message.is_read and (not message.is_checked) and (message.from_user_id == int(current_user.User_id))] if not_checked_message_ids: with db.session.begin(subtransactions=True): DealMessage.update_is_checked_by_ids(not_checked_message_ids) db.session.commit() if request.method == 'POST' and messageform.validate(read_message_ids): dealmessage = DealMessage( Sell_id = item_id, to_user_id = dest_user.User_id, from_user_id = current_user.User_id, message = messageform.message.data ) # データベース登録処理 with db.session.begin(subtransactions=True): dealmessage.create_new_dealmessage() db.session.commit() return redirect(url_for('transaction.transaction', item_id=item_id)) return render_template( 'transaction/transaction.html', item=item, buy=buy, shippingaddress=shippingaddress, messageform=messageform, messages=messages, dest_user=dest_user, noticeform=noticeform )
def decorated_function(*args, **kwargs): sell_id = kwargs['item_id'] sell = Sell.select_sell_by_sell_id(sell_id) buy = Buy.select_buy_by_sell_id(sell_id) user_id = current_user.get_id() if sell is None or buy is None: return redirect(url_for('route.home')) else: if sell.User_id != user_id and buy.User_id != user_id: return redirect(url_for('route.home')) elif not sell.sell_flg: return redirect(url_for('route.home')) elif not sell.is_active: return redirect(url_for('route.home')) elif sell.deal_status == Deal_status['出品中']: return redirect(url_for('route.home')) return func(*args, **kwargs)
def item(): form = SearchForm(request.args, meta={'csrf': False}) items = None users = None change_search = 'item' if request.method == 'GET': search_word = form.search.data sort = form.sort.data genre = form.genre.data value_min = form.value_min.data value_max = form.value_max.data status = form.state.data postages = form.postage.data deal_statuses = form.sellstate.data if form.n_d_submit.data or form.submit.data: items = Sell.item_search(search_word, sort, genre, value_min, value_max, status, postages, deal_statuses) return render_template('search/search.html', form=form, items=items, users=users, change_search=change_search)
def notice_rating(item_id): sell = Sell.select_sell_by_sell_id(item_id) buy = Buy.select_buy_by_sell_id(item_id) form = NoticeRatingForm(request.form) if request.method == 'POST' and form.validate(): if form.notice_condition.data == 'has_sent': with db.session.begin(subtransactions=True): sell.has_sent = True sell.update_at = datetime.datetime.now() db.session.commit() flash('発送通知を送信しました。') return redirect(url_for('transaction.transaction', item_id=item_id)) if form.notice_condition.data == 'has_got': rating = Rating( Sell_id = item_id, to_user_id = sell.User_id, from_user_id = current_user.User_id, rating = form.rating.data, rating_message = form.rating_message.data ) with db.session.begin(subtransactions=True): rating.create_new_rating() sell.has_got = True sell.update_at = datetime.datetime.now() db.session.commit() flash('受け取り確認と評価を送信しました') return redirect(url_for('transaction.transaction', item_id=item_id)) if form.notice_condition.data == 'seller_rating': rating = Rating( Sell_id = item_id, to_user_id = buy.User_id, from_user_id = current_user.User_id, rating = form.rating.data, rating_message = form.rating_message.data ) with db.session.begin(subtransactions=True): rating.create_new_rating() sell.deal_status = Deal_status['取引済み'] sell.update_at = datetime.datetime.now() db.session.commit() flash('評価を送信しました。取引が完了しました。') return redirect(url_for('transaction.transaction', item_id=item_id)) return redirect(url_for('transaction.transaction', item_id=item_id))
def decorated_function(*args, **kwargs): sell_id = kwargs['item_id'] sell = Sell.select_sell_by_sell_id(sell_id) user_id = current_user.get_id() if sell is None: return redirect(url_for('route.home')) else: if sell.user.User_id == user_id: flash("出品者の商品は購入できません。") return redirect(url_for('item.itemdata', item_id=sell_id)) elif not sell.sell_flg: flash("選択された商品は購入できません。") return redirect(url_for('route.home')) elif not sell.is_active: flash("選択された商品は購入できません。") return redirect(url_for('route.home')) elif sell.deal_status != Deal_status['出品中']: flash("選択された商品は出品中ではありません。") return redirect(url_for('item.itemdata', item_id=sell_id)) return func(*args, **kwargs)
def recommend(c_userid): """協調フィルタリングユーザーベースレコメンド""" # 商品レコメンド recommends = getRecommendations(str(c_userid)) # ユーザーレコメンド u_recommends = topMatches(str(c_userid)) r_item_list = [] if recommends is not None: for recommend in recommends: recommend_id = int(recommend) r_item_list.append(Sell.select_sell_by_sell_id(recommend_id)) elif recommends is None: r_item_list = [] r_user_list = [] if u_recommends is not None: for u_recommend in u_recommends: u_recommend_id = int(u_recommend) r_user_list.append(User.select_user_by_id(u_recommend_id)) elif u_recommends is None: r_user_list = [] return r_item_list, r_user_list
def sell_completed(): """出品取引済み履歴""" user_id = current_user.get_id() next_url = prev_url = items = None page = request.args.get('page', 1, type=int) posts = Sell.select_sell_by_deal_status_page(user_id, 3, page) next_url = url_for('history.sell_completed', page=posts.next_num) if posts.has_next else None prev_url = url_for('history.sell_completed', page=posts.prev_num) if posts.has_prev else None items = posts.items liked_list = [] if current_user.is_authenticated: for item in items: liked = Likes.liked_exists(item.Sell_id) if liked: liked_list.append(item.Sell_id) return render_template('history/sell_history.html', items=items, next_url=next_url, prev_url=prev_url, liked_list=liked_list)
def todolist(): """やることリスト""" user_id = current_user.get_id() now = datetime.datetime.now() items = Sell.select_sall_status(user_id) todolists =[] for item in items: elapsed = now - item.update_at todolist_data = {"item" : None, "status" : 0, "elapsed_time" : "", "partner_username" : "", "partner_user_code" : "", "partner_picture_path" : ""} # 出品者 if item.User_id==user_id: buy_data = Buy.select_buy_by_sell_id(item.Sell_id) todolist_data["partner_username"] = User.select_user_by_id(buy_data.User_id).username todolist_data["partner_user_code"] = User.select_user_by_id(buy_data.User_id).user_code todolist_data["partner_picture_path"] = User.select_user_by_id(buy_data.User_id).picture_path rating = Rating.select_count_sell_id_to_user_id(item.Sell_id, user_id) # 未発送 if item.has_sent == item.has_got == False: todolist_data["status"] = 1 # 発送済みで受け取り・評価待ち elif item.has_sent == True and item.has_got == False: todolist_data["status"] = 4 # 受け取り済みで相手が相互評価して自分がしてない elif item.has_sent == item.has_got == True and rating == 1: todolist_data["status"] = 2 rating_datas=Rating.select_sell_id_to_user_id(item.Sell_id, user_id) for rating_data in rating_datas: print(rating_data.update_at) elapsed = now - rating_data.update_at print(elapsed.days/7) #購入者 else: todolist_data["partner_username"] = User.select_user_by_id(item.User_id).username todolist_data["partner_user_code"] = User.select_user_by_id(item.User_id).user_code todolist_data["partner_picture_path"] = User.select_user_by_id(item.User_id).picture_path rating = Rating.select_count_sell_id_to_user_id(item.Sell_id, item.User_id) # 発送済みで商品を受取ってない if item.has_sent == True and item.has_got == False: todolist_data["status"] = 3 # 発送待ち elif item.has_sent == item.has_got == False: todolist_data["status"] = 4 # 評価待ち elif item.has_sent == item.has_got == True: todolist_data["status"] = 4 print("*"*100) print(elapsed.days/7) # 経過時間 if not elapsed.days//365 == 0: elapsed_time = str(elapsed.days//365) + "年" elif not elapsed.days//30 == 0: elapsed_time = str(elapsed.days//30) + "ヶ月" elif not elapsed.days//7 == 0: elapsed_time = str(elapsed.days//7) + "週間" elif not elapsed.days == 0: elapsed_time = str(elapsed.days) + "日" elif not elapsed.seconds//3600 == 0: elapsed_time = str(elapsed.seconds//3600) + "時間" elif not elapsed.seconds//60 == 0: elapsed_time = str(elapsed.seconds//60) + "分" else: elapsed_time = str(elapsed.seconds) + "秒" print(elapsed.seconds//60) print("*"*100) todolist_data["item"] = item todolist_data["elapsed_time"] = elapsed_time todolists.append(todolist_data) return render_template('todolist/todolist.html', todolists=todolists)
def sell_update(item_id): sell = Sell.select_sell_by_sell_id(item_id) if sell.remarks == None: remarks = '' form = SellUpdateForm(request.form, sell_comment=str(sell.sell_comment), genre=str(sell.genre.name), item_state=str(sell.item_state.name), postage=str(sell.postage.name), send_way=str(sell.send_way.name), consignor=str(sell.consignor), schedule=str(sell.schedule.name), remarks=str(sell.remarks)) if request.method == 'POST' and form.validate(): # 画像アップロード処理 ここから-------------------------- imagename = '' image = request.files[form.item_picture_path.name] # 画像ファイルがあった場合 if image: # 画像アップロード処理用関数 if allowed_image(image.filename): # ファイル名から拡張子を取り出す ext = image.filename.rsplit('.', 1)[1] # imagenameはユーザーID+現在の時間+.拡張子 imagename = str(current_user.User_id) + '_' + \ str(int(datetime.now().timestamp())) + '.' + ext # ファイルの保存 image.save( os.path.join(app.config["ORIGINAL_ITEM_IMAGE_UPLOADS"], imagename)) im = Image.open( os.path.join(app.config["ORIGINAL_ITEM_IMAGE_UPLOADS"], imagename)) # 最大サイズの正方形に切り出したあと、300に縮小 im_thumb = crop_max_square(im).resize((300, 300), Image.LANCZOS) # ファイルの保存 im_thumb.save( os.path.join(app.config["ITEM_IMAGE_UPLOADS"], imagename)) else: flash('画像のアップロードに失敗しました。') return render_template('sell/sell.html', form=form) # 画像アップロード処理 ここまで-------------------------- # データベース処理 with db.session.begin(subtransactions=True): if imagename: # imagenameが設定されていれば(画像があれば)更新する sell.item_picture_path = imagename sell.sell_title = str(form.sell_title.data) sell.key1 = str(form.key1.data) sell.key2 = str(form.key2.data) sell.key3 = str(form.key3.data) sell.sell_comment = str(form.sell_comment.data) sell.price = int(form.price.data) sell.genre = Genre[str(form.genre.data)] sell.item_state = Item_state[str(form.item_state.data)] sell.postage = Postage[str(form.postage.data)] sell.send_way = Send_way[str(form.send_way.data)] sell.consignor = str(form.consignor.data) sell.schedule = Schedule[str(form.schedule.data)] sell.remarks = str(form.remarks.data) db.session.commit() flash('更新に成功しました') return redirect(url_for('item.itemdata', item_id=item_id)) return render_template('sell/sell_update.html', form=form, sell=sell)
def sell_complete(item_id): sell = Sell.select_sell_by_sell_id(item_id) return render_template('sell/sell_complete.html', item=sell)