第4週の質問


1. html_temp

<div class="columns is-multiline" id="tea-box">
    <div class="column is-one-third">
        <div class="card"><img class="card-img-top"
                               src="https://cdn.shopify.com/s/files/1/0119/8250/3994/files/002_____________2933_2000_1024x1024.jpg?v=1597889849">
            <div class="card-body">
                <h5 class="card-title">002 KOUSHUN 香駿</h5>
                <p class="card-text">出勤の朝、優しく目覚めの一杯</p>
                <br>
                <p>これほどすっきりと上品な煎茶が他にあるだろうか。爽やかな薫風を感じさせる水出しもまた格別。</p>
                <br>
                <a href='/detail'>
                    <button class="button is-outlined">詳細</button>
                </a>
                <button id="btn-save" class="button is-danger is-outlined">
                    <i class="fa fa-bookmark" aria-hidden="true"></i></button>
                <button id="btn-delete" class="button is-outline"><i class="fa fa-bookmark-o" aria-hidden="true"></i>
                </button>
            </div>
        </div>
    </div>
를 입력하세요


n.問題
データベースにカードを貼りたいのですが、html tempコードをどのように書けばいいですか?ONページにはTime:off、OFFページにはTime:offのみを貼ります.Robo 3 Tはリスト名で保存されています.

2.インポートリストのコードを確認する


サーバー
@app.route('/on')
def on():
    return render_template("on.html")

@app.route('/ontea', methods=["GET"])
def get_ontea():
    tea_list = list(db.list.find({}, {'_id': False}))
    return jsonify({'result': 'success', 'tea_list': tea_list})
クライアント
    function get_ontea() {
        $('#tea-box').empty();
        $.ajax({
            type: "GET",
            url: '/ontea',
            data: {},
            success: function (response) {
                let teas = response["tea_list"]
                for (let i = 0; i < teas.length; i++) {
                    let tea = teas[i]
                    console.log(tea)
n.問題
コンソールウィンドウにエラーが表示されたまま...
確認してください
ONページをクリックするとすぐにカードをポップアップさせたいです.

3.ログアウト



n.問題
ログアウトボタンを押しても何の反応もありません.
受講ノートに「履歴書開始コードに入っています」と書いてあるのはどこですか?Webplus APP.py添付ファイル.ここから何を持ってきますか.
from pymongo import MongoClient
import jwt
import datetime
import hashlib
from flask import Flask, render_template, jsonify, request, redirect, url_for
from werkzeug.utils import secure_filename
from datetime import datetime, timedelta


app = Flask(__name__)
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config['UPLOAD_FOLDER'] = "./static/profile_pics"

SECRET_KEY = 'SPARTA'

client = MongoClient('52.78.115.132', 27017, username="test", password="test")
db = client.dbsparta_plus_week4


@app.route('/')
def home():
    token_receive = request.cookies.get('mytoken')
    try:
        payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])
        user_info = db.users.find_one({"username": payload["id"]})
        return render_template('index.html', user_info=user_info)
    except jwt.ExpiredSignatureError:
        return redirect(url_for("login", msg="로그인 시간이 만료되었습니다."))
    except jwt.exceptions.DecodeError:
        return redirect(url_for("login", msg="로그인 정보가 존재하지 않습니다."))


@app.route('/login')
def login():
    msg = request.args.get("msg")
    return render_template('login.html', msg=msg)


@app.route('/user/<username>')
def user(username):
    # 각 사용자의 프로필과 글을 모아볼 수 있는 공간
    token_receive = request.cookies.get('mytoken')
    try:
        payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])
        status = (username == payload["id"])  # 내 프로필이면 True, 다른 사람 프로필 페이지면 False

        user_info = db.users.find_one({"username": username}, {"_id": False})
        return render_template('user.html', user_info=user_info, status=status)
    except (jwt.ExpiredSignatureError, jwt.exceptions.DecodeError):
        return redirect(url_for("home"))


@app.route('/sign_in', methods=['POST'])
def sign_in():
    # 로그인
    username_receive = request.form['username_give']
    password_receive = request.form['password_give']

    pw_hash = hashlib.sha256(password_receive.encode('utf-8')).hexdigest()
    result = db.users.find_one({'username': username_receive, 'password': pw_hash})

    if result is not None:
        payload = {
         'id': username_receive,
         'exp': datetime.utcnow() + timedelta(seconds=60 * 60 * 24)  # 로그인 24시간 유지
        }
        token = jwt.encode(payload, SECRET_KEY, algorithm='HS256').decode('utf-8')

        return jsonify({'result': 'success', 'token': token})
    # 찾지 못하면
    else:
        return jsonify({'result': 'fail', 'msg': '아이디/비밀번호가 일치하지 않습니다.'})


@app.route('/sign_up/save', methods=['POST'])
def sign_up():
    username_receive = request.form['username_give']
    password_receive = request.form['password_give']
    password_hash = hashlib.sha256(password_receive.encode('utf-8')).hexdigest()
    doc = {
        "username": username_receive,                               # 아이디
        "password": password_hash,                                  # 비밀번호
        "profile_name": username_receive,                           # 프로필 이름 기본값은 아이디
        "profile_pic": "",                                          # 프로필 사진 파일 이름
        "profile_pic_real": "profile_pics/profile_placeholder.png", # 프로필 사진 기본 이미지
        "profile_info": ""                                          # 프로필 한 마디
    }
    db.users.insert_one(doc)
    return jsonify({'result': 'success'})


#아이디 중복확인
@app.route('/sign_up/check_dup', methods=['POST'])
def check_dup():
    username_receive = request.form['username_give']
    exists = bool(db.users.find_one({"username": username_receive}))
    return jsonify({'result': 'success', 'exists': exists})


@app.route('/update_profile', methods=['POST'])
def save_img():
    token_receive = request.cookies.get('mytoken')
    try:
        payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])
        username = payload["id"]
        name_receive = request.form["name_give"]
        about_receive = request.form["about_give"]
        new_doc = {
            "profile_name": name_receive,
            "profile_info": about_receive
        }
        if 'file_give' in request.files:
            file = request.files["file_give"]
            filename = secure_filename(file.filename)
            extension = filename.split(".")[-1]
            file_path = f"profile_pics/{username}.{extension}"
            file.save("./static/"+file_path)
            new_doc["profile_pic"] = filename
            new_doc["profile_pic_real"] = file_path
        db.users.update_one({'username': payload['id']}, {'$set':new_doc})
        return jsonify({"result": "success", 'msg': '프로필을 업데이트했습니다.'})
    except (jwt.ExpiredSignatureError, jwt.exceptions.DecodeError):
        return redirect(url_for("home"))


@app.route('/posting', methods=['POST'])
def posting():
    token_receive = request.cookies.get('mytoken')
    try:
        payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])
        user_info = db.users.find_one({"username": payload["id"]})
        comment_receive = request.form["comment_give"]
        date_receive = request.form["date_give"]
        doc = {
            "username": user_info["username"],
            "profile_name": user_info["profile_name"],
            "profile_pic_real": user_info["profile_pic_real"],
            "comment": comment_receive,
            "date": date_receive
        }
        db.posts.insert_one(doc)
        return jsonify({"result": "success", 'msg': '포스팅 성공'})
    except (jwt.ExpiredSignatureError, jwt.exceptions.DecodeError):
        return redirect(url_for("home"))


@app.route("/get_posts", methods=['GET'])
def get_posts():
    token_receive = request.cookies.get('mytoken')
    try:
        payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])
        username_receive = request.args.get("username_give")
        if username_receive == "":
            posts = list(db.posts.find({}).sort("date", -1).limit(20))
        else:
            posts = list(db.posts.find({"username": username_receive}).sort("date", -1).limit(20))
        for post in posts:
            post["_id"] = str(post["_id"])
            post["count_heart"] = db.likes.count_documents({"post_id": post["_id"], "type": "heart"})
            post["heart_by_me"] = bool(
                db.likes.find_one({"post_id": post["_id"], "type": "heart", "username": payload['id']}))
        return jsonify({"result": "success", "msg": "포스팅을 가져왔습니다.", "posts":posts})
    except (jwt.ExpiredSignatureError, jwt.exceptions.DecodeError):
        return redirect(url_for("home"))


@app.route('/update_like', methods=['POST'])
def update_like():
    token_receive = request.cookies.get('mytoken')
    try:
        payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])

        user_info = db.users.find_one({"username": payload["id"]})
        post_id_receive = request.form["post_id_give"]
        type_receive = request.form["type_give"]
        action_receive = request.form["action_give"]
        doc = {
            "post_id": post_id_receive,
            "username": user_info["username"],
            "type": type_receive
        }
        if action_receive == "like":
            db.likes.insert_one(doc)
        else:
            db.likes.delete_one(doc)
        count = db.likes.count_documents({"post_id": post_id_receive, "type": type_receive})
        return jsonify({"result": "success", 'msg': 'updated', "count": count})
    except (jwt.ExpiredSignatureError, jwt.exceptions.DecodeError):
        return redirect(url_for("home"))


if __name__ == '__main__':
    app.run('0.0.0.0', port=5000, debug=True)
my page HTML
<script>
    function openNav() {
        document.getElementById("mySidenav").style.width = "250px";
    }

    function closeNav() {
        document.getElementById("mySidenav").style.width = "0";
    }

    function sign_out() {
        $.removeCookie('mytoken', {path: '/'});
        alert('로그아웃!')
        window.location.href = "/login"
    }

</script>
<body>
<div id="mySidenav" class="sidenav">
    <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
    <a href="/main">Home</a>
    <a href="/mylist">My List</a>
    <a href="/login">Login</a>
    {#    <a href="#">Contact</a>#}
</div>

<section class="hero">
    <div class="mypage">
        <div class="hero-body">
            <span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span>
            <hr class="my-4">
            <div class="mylist">
                <p class="title">
                    My List
                </p>
                <p class="subtitle">お気に入りお茶がここに表示されます</p>
            </div>
        </div>
    </div>
</section>

<section class="section">
    <div class="container">
        <div class="box" style="max-width: 480px;margin:auto">
            <article class="media">
                <div class="media-content">
                    <div class="content">
                        <p>
                            <strong>@{{ user_info.username }}</strong></p>
                    </div>
                </div>
            </article>
            <nav id="btns-me" class="level is-mobile" style="margin-top:2rem">
                <a class="button level-item has-text-centered is-sparta is-outlined" aria-label="logout"
                   onclick="sign_out()">로그아웃<span class="icon is-small"><i class="fa fa-sign-out"
                                                                         aria-hidden="true"></i></span>
                </a>
            </nav>
        </div>
    </div>
</section>
<section class="section is-medium">
    <h1 class="mytitle">로그인이 필요한 페이지입니다.</h1>
    <a href="/login">ログインはこちら</a>
</section>

4.ログイン/非ログイン画面の区別



n.問題
ログインしている人は@romi 4019カードしか見えませんが、ログインしていない人はログインするページが必要です.あなたに見せたい.