後で参照用 検索機能/status登録 / タグ登録 code全文

### code全文

```ruby:run.py
from app import app, db

if __name__ == "__main__":
    # アプリケーションコンテキストの中でDBを作成
    with app.app_context():
        db.create_all()  # データベースのテーブルを作成

    # Flaskアプリケーションの実行
    app.run(debug=True, use_reloader=True)
```

```app.py
from flask import Flask, render_template, request, redirect, url_for, render_template_string
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///books.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    author = db.Column(db.String(100), nullable=False)
    tags = db.Column(db.String(200), nullable=True)
    memo = db.Column(db.Text, nullable=True)
    status = db.Column(db.String(10), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.now)

# 一覧 + 登録 + 検索 + 並び替え
@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        title = request.form["title"].strip()
        author = request.form["author"].strip()
        tags = request.form["tags"].strip()
        memo = request.form["memo"].strip()
        status = request.form["status"].strip()
        if title and author:
            db.session.add(Book(title=title, author=author, tags=tags, memo=memo, status=status))
            db.session.commit()
        return redirect("/")

    keyword = request.args.get("q", "")
    sort = request.args.get("sort", "tags")

    books = Book.query

    if keyword:
        books = books.filter(
        Book.title.contains(keyword) |
        Book.author.contains(keyword) |
        Book.tags.contains(keyword) |
        Book.status.contains(keyword) |
        Book.memo.contains(keyword)
    )

    if sort == "title":
        books = books.order_by(Book.title.asc())
    elif sort == "tags":
        books = books.order_by(Book.tags.asc())
    elif sort == "status":
        books = books.order_by(Book.status.asc())
    else:
        books = books.order_by(Book.created_at.desc()) 

    statuses = ["未読", "読んでる", "読了"]  # 例：ステータス一覧 

    tags = ["ギャグ", "ホラー", "冒険", "恋愛", "泣ける"]

    return render_template_string("""
        <h2>📚 本の登録</h2>
        <form method="POST">
            タイトル: <input type="text" name="title"><br>
            著者: <input type="text" name="author"><br>
            タグ: <input type="text" name="tags"><br>
            メモ: <br><textarea name="memo" rows="3" cols="40"></textarea><br>
            ステータス: <input type="text" name="status"><br>
            <input type="submit" value="登録">
        </form>

        <h3>🔍 検索</h3>
        <form method="GET">
            <h2>キーワード</h2>
             <input type="text" name="q" value="{{ request.args.get('q', '') }}">
            <input type="submit" value="検索">
        </form>
        <br>
        
        # ステータス検索
        <form method="GET">
            <h2>ステータス</h2>
             <input type="text" name="q" value="{{ request.args.get('q', '') }}">
            <input type="submit" value="検索">
        </form>

        # タグ検索
        <form method="GET">
            <h2>タグ</h2>
             <input type="text" name="q" value="{{ request.args.get('q', '') }}">
            <input type="submit" value="検索">
        </form>
        

        <h2>📖 登録済みの本</h2>
        <ul>
        {% for book in books %}
            <li>
                <strong>{{ book.title }}</strong> / {{ book.author }}（{{ book.created_at.strftime('%Y-%m-%d') }}）<br>
                タグ: {{ book.tags }}<br>
                メモ: <pre style="background:#eee; padding:5px;">{{ book.memo }}</pre>
                ステータス: {{ book.status }}<br>
                [<a href="/edit/{{book.id}}">編集</a>]
                [<a href="/delete/{{book.id}}" onclick="return confirm('削除していい？');">削除</a>]
            </li>
        {% else %}
            <li>データめよら</li>
        {% endfor %}
        </ul>
    """, books=books.all() statuses=statuses, manytag=manytag)

@app.route("/edit/<int:id>", methods=["GET", "POST"])
def edit(id):
    book = Book.query.get(id)
    if request.method == "POST":
        book.title = request.form["title"].strip()
        book.author = request.form["author"].strip()
        book.tags = request.form["tags"].strip()
        book.memo = request.form["memo"].strip()
        book.status = request.form["status"].strip()
        db.session.commit()
        return redirect("/")

    statuses = ["未読", "読んでる", "読了"]

    tags = ["ギャグ", "ホラー", "冒険", "恋愛", "泣ける"]

    return render_template_string("""
        <h2>✏️ 編集</h2>
        <form method="POST">
            タイトル: <input type="text" name="title" value="{{book.title}}"><br>
            著者: <input type="text" name="author" value="{{book.author}}"><br>
            メモ: <br><textarea name="memo" rows="3" cols="40">{{book.memo}}</textarea><br>
              <label for="tags">Tags:</label>
              <select name="tags" id="tags">
              {% for tags in manytag %}
              <option value="{{ tags }}" {% if tags == book.tags %}selected{% endif %}>{{ tags }}</option>
              {% endfor %}
               </select>
               <label for="tags">Tags:</label>
               <select name="tags" id="tags">
               {% for tags in manytag %}
               <option value="{{ tags }}" {% if tags == book.tags %}selected{% endif %}>{{ tags }}</option>
               {% endfor %}
               </select>
            <input type="submit" value="更新">
        </form>
        <a href="/">戻る</a>
    """, book=book, statuses=statuses, manytag=manytag)

@app.route("/delete/<int:id>")
def delete(id):
    db.session.delete(Book.query.get(id))
    db.session.commit()
    return redirect("/")
```