[Python] Search results don't show up on choosing "Full Category" using Flask

Discussão em 'Python' iniciado por Stack, Maio 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm creating a search site now. We were even adding a category search function. But that's where the problem popped up. If you choose "Full Category," all the search results should come out, but they don't. How do I get it to pop up?

    This is my Python code.

    from flask import Flask, render_template, request, redirect
    import json
    import os

    app = Flask(__name__)
    DATA_PATH = 'data/documents.json'

    def load_documents():
    with open(DATA_PATH, encoding='utf-8') as f:
    return json.load(f)

    def save_documents(documents):
    with open(DATA_PATH, 'w', encoding='utf-8') as f:
    json.dump(documents, f, ensure_ascii=False, indent=4)

    def generate_unique_id(documents):
    if not documents:
    return 1
    return max(doc.get('id', 0) for doc in documents) + 1

    @app.route("/", methods=["GET", "POST"])
    def index():
    query = request.args.get("query", "")
    category_filter = request.args.get("category_filter", "")
    documents = load_documents()
    print(f"Loaded documents: {documents}")
    results = documents

    if category_filter and category_filter != "":
    results = [doc for doc in results if doc["category"] == category_filter]

    if query:
    results = [doc for doc in results if query in doc["title"] or query in doc["content"]]

    print(f"Query in template: '{query}'")
    print(f"Category Filter in template: '{category_filter}'")
    print(f"Results in template: {results}")
    return render_template("index.html", query=query, results=results, category_filter=category_filter)

    @app.route("/add", methods=["POST"])
    def add():
    title = request.form["title"]
    content = request.form["content"]
    image = request.form.get("image", "")
    category = request.form.get("category", "미분류")
    documents = load_documents()
    new_id = generate_unique_id(documents)
    new_doc = {"id": new_id, "title": title, "content": content, "image": image, "category": category}
    documents.append(new_doc)
    save_documents(documents)
    return redirect("/")

    @app.route("/edit/<int:id>")
    def edit(id):
    documents = load_documents()
    document = next((doc for doc in documents if doc["id"] == id), None)
    if document:
    return render_template("edit.html", document=document)
    return redirect("/")

    @app.route("/update/<int:id>", methods=["POST"])
    def update(id):
    title = request.form["title"]
    content = request.form["content"]
    image = request.form.get("image", "")
    category = request.form.get("category", "미분류")
    documents = load_documents()
    for doc in documents:
    if doc["id"] == id:
    doc["title"] = title
    doc["content"] = content
    doc["image"] = image
    doc["category"] = category
    break
    save_documents(documents)
    return redirect("/")

    def get_all_search_terms():
    documents = load_documents()
    search_terms = []
    for doc in documents:
    search_terms.append(doc["title"])
    search_terms.append(doc["content"])
    return search_terms

    if __name__ == "__main__":
    if not os.path.exists("data"):
    os.makedirs("data")
    if not os.path.exists(DATA_PATH):
    save_documents([])
    app.run(debug=True, host='127.0.0.1', port=5000)


    This is my HTML code

    <!DOCTYPE html>
    <html lang="ko">
    <head>
    <meta charset="UTF-8">
    <title>검색 사이트</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <style>
    .add-form-floating {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 250px;
    background: #ffffffcc;
    border: 1px solid #ccc;
    padding: 15px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    font-size: 14px;
    z-index: 1000;
    }

    .add-form-floating h3 {
    margin-top: 0;
    font-size: 16px;
    }

    .add-form-floating input[type="text"],
    .add-form-floating textarea {
    width: 100%;
    margin-bottom: 8px;
    padding: 5px;
    box-sizing: border-box;
    font-size: 14px;
    }

    .add-form-floating textarea {
    height: 60px;
    resize: vertical;
    }

    .add-form-floating input[type="submit"] {
    width: 100%;
    background-color: #4CAF50;
    color: white;
    border: none;
    padding: 6px;
    border-radius: 4px;
    cursor: pointer;
    }

    .add-form-floating input[type="submit"]:hover {
    background-color: #45a049;
    }
    </style>
    </head>
    <body>
    <div class="container">
    <form method="GET" autocomplete="off">
    <input type="text" name="query" id="search-input" value="{{ query }}" placeholder="검색어를 입력하세요">
    <button type="submit">검색</button>
    <div id="autocomplete-results" class="autocomplete-results">
    </div>
    </form>
    <form method="GET">
    <select name="category_filter">
    <option value="">전체 카테고리</option>
    <option value="일상" {% if category_filter == '일상' %}selected{% endif %}>일상</option>
    <option value="정보" {% if category_filter == '정보' %}selected{% endif %}>정보</option>
    <option value="리뷰" {% if category_filter == '리뷰' %}selected{% endif %}>리뷰</option>
    <option value="질문" {% if category_filter == '질문' %}selected{% endif %}>질문</option>
    </select>
    <button type="submit">카테고리 검색</button>
    </form>
    {% if query or category_filter %}
    <h2>검색 결과:</h2>
    {% if results %}
    <ul>
    {% for r in results %}
    <li>
    <strong>{{ r.title }}</strong> <span class="category">[{{ r.category }}]</span><br>
    {{ r.content }}<br>
    {% if r.image %}
    <img src="{{ r.image }}" alt="이미지" style="max-width: 200px; margin-top: 10px;">
    {% endif %}
    <a href="/edit/{{ r.id }}"><button class="edit-button">수정</button></a>
    </li>
    {% endfor %}
    </ul>
    {% else %}
    <p>검색 결과가 없습니다.</p>
    {% endif %}
    {% endif %}
    </div>

    <!-- 고정된 위치에 있는 버튼 + 폼 -->
    <div id="floating-form" style="position: fixed;
    bottom: 20px;
    right: 20px;
    width: 300px;
    background: white;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    border-radius: 10px;
    padding: 10px;
    display: none; /* 처음엔 숨김 */
    z-index: 9999;">
    <form action="/add" method="post">
    <h3>문서 추가</h3>
    제목: <input type="text" name="title" required><br>
    내용: <textarea name="content" required></textarea><br>
    카테고리:
    <select name="category">
    <option value="미분류">미분류</option>
    <option value="일상">일상</option>
    <option value="정보">정보</option>
    <option value="리뷰">리뷰</option>
    <option value="질문">질문</option>
    </select><br><br>
    이미지 주소 (선택): <input type="text" name="image"><br>
    <input type="submit" value="추가" style="background: green; color: white; border: none; padding: 5px 10px; border-radius: 5px;">
    </form>
    </div>

    <!-- 토글 버튼 -->
    <button id="toggle-button" style="
    position: fixed;
    bottom: 20px;
    right: 20px;
    background: #4CAF50;
    color: white;
    border: none;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    font-size: 24px;
    cursor: pointer;
    z-index: 10000;">
    +
    </button>

    <script>
    const toggleBtn = document.getElementById('toggle-button');
    const form = document.getElementById('floating-form');
    let isOpen = false;

    toggleBtn.addEventListener('click', () => {
    isOpen = !isOpen;
    form.style.display = isOpen ? 'block' : 'none';
    toggleBtn.textContent = isOpen ? '×' : '+';
    });
    </script>

    </body>
    </html>


    <!DOCTYPE html>
    <html lang="ko">
    <head>
    <meta charset="UTF-8">
    <title>글 수정</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    </head>
    <body>
    <div class="container">
    <h1>글 수정</h1>
    <form action="/update/{{ document.id }}" method="post">
    제목: <input type="text" name="title" value="{{ document.title }}" required><br>
    내용: <textarea name="content" required>{{ document.content }}</textarea><br>
    카테고리:
    <select name="category">
    <option value="미분류" {% if document.category == '미분류' %}selected{% endif %}>미분류</option>
    <option value="일상" {% if document.category == '일상' %}selected{% endif %}>일상</option>
    <option value="정보" {% if document.category == '정보' %}selected{% endif %}>정보</option>
    <option value="리뷰" {% if document.category == '리뷰' %}selected{% endif %}>리뷰</option>
    <option value="질문" {% if document.category == '질문' %}selected{% endif %}>질문</option>
    </select><br><br>
    이미지 주소 (선택): <input type="text" name="image" value="{{ document.image }}"><br>
    <input type="submit" value="수정 완료">
    </form>
    <br>
    <a href="/">메인 페이지로 돌아가기</a>
    </div>
    </body>
    </html>


    This is my css code,

    body {
    font-family: sans-serif;
    background: #f9f9f9;
    padding: 40px;
    }
    .container {
    max-width: 600px;
    margin: auto;
    background: white;
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    input[type="text"] {
    width: 80%;
    padding: 8px;
    }
    button {
    padding: 8px 12px;
    }
    ul {
    list-style: none;
    padding: 0;
    }
    li {
    padding: 10px 0;
    border-bottom: 1px solid #eee;
    }
    .edit-button {
    padding: 3px 6px; /* 내부 여백을 더 줄임 */
    font-size: 0.8em; /* 글자 크기를 더 줄임 */
    margin-left: 5px; /* 간격도 조금 줄임 */
    }

    .category {
    font-size: 0.8em;
    color: gray;
    margin-left: 5px;
    }


    This is my json code.

    [
    {
    "id": 1,
    "title": "파이썬 소개",
    "content": "파이썬은 간단하고 강력한 프로그래밍 언어입니다.",
    "image": "https://www.python.org/static/community_logos/python-logo.png",
    "category": "정보"
    },
    {
    "id": 2,
    "title": "인공지능이란?",
    "content": "인공지능은 인간의 지능을 모방하는 기술입니다.",
    "image": "https://static.vecteezy.com/system/resources/previews/021/059/827/original/chatgpt-logo-chat-gpt-icon-on-white-background-free-vector.jpg",
    "category": "정보"
    },
    {
    "id": 3,
    "title": "테라리아 리뷰",
    "content": "테라리아는 픽셀 게임임에도 불구하고 그래픽이 매우 좋음. 굳",
    "image": "",
    "category": "리뷰"
    },
    {
    "id": 4,
    "title": "얭얭이 반주",
    "content": "ㅇㄴㅁㅁㄴㅇ",
    "image": "",
    "category": "일상"
    },
    {
    "id": 5,
    "title": "테라리아 리뷰2",
    "content": "망겜",
    "image": "",
    "category": "리뷰"
    }


    ]

    Continue reading...

Compartilhe esta Página