0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

一行日記のエラーを解消【💪諦めない心🔥】

0
Last updated at Posted at 2025-08-26

🌟 ONE LINE DIARY

ONE LINE DIARY
簡易的なログイン機能付き
※ Render(PostgreSQL)の無料枠都合上、2025年内まで公開予定

記事構成

  • :ballot_box: デプロイしてもテーブルが作成されない
  • :hourglass_flowing_sand:タイムゾーン(GMT+9)が反映されない!
  • :muscle:まとめ
  • :books: 関連記事

:ballot_box: デプロイしてもテーブルが作成されない

  • postgreSQLを使用
  • ローカル環境では問題なく動作する
  • DBは作成されているものの、サイトにアクセスするとテーブルが存在しないエラー

方針と解決策

:x: db.create_all()をメインファイルの末尾に追加(のちに、最後だと動かないことが発覚)
:x: 新たにテーブル作成用のコードファイルを作成(テーブル作成用のコードはローカル環境でしか動かなかった模様)
:x: 一度公開を取り消してDBも作り直し、再度ローカル環境で動作確認した上でデプロイ

:o: db.create_all() を @app.route('/') の前に追加する
10時間近くに及ぶ試行錯誤の末、非常に単純な結論に落ち着きました。
Flaskの db.create_all() は アプリケーションコンテキストが有効な状態 で呼ぶ必要があります。末尾に置くとコンテキスト外になり、Renderの初期化時には実行されずにエラーになっていました。
@app.route('/') の前に追加することで、展開時のテーブル作成が上手く動き、無事にデプロイできました。

with app.app_context():
   inspector = inspect(db.engine)
   if "onediary_user" not in inspector.get_table_names():
       print(">>> Creating tables...") # 心配なため経過を出力
       db.create_all()
       print(">>> Done creating tables!")

@app.route('/') # '/'より前に置く!

:hourglass_flowing_sand:タイムゾーン(GMT+9)が反映されない!

方針と解決策

  • ローカル環境では問題なし
  • Renderとの兼ね合いで、時間がずれてしまう
  • 保存はUTC、表示はJSTに変更
  • datetime.utcnow() はタイムゾーン情報を持たない naive datetime を返し、取り出したときに tzinfo=pytz.utc を付与してから astimezone() で変換することで、安全にJSTに変換できます。
from datetime import datetime

def utc_now():
    return datetime.utcnow()

class Post(db.Model):
    __tablename__ = 'onediary_post'
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text, nullable=False)
    date_created = db.Column(db.DateTime, default=utc_now) # postでは標準時を使用

@app.route('/')
def index():
    if not current_user.is_authenticated:
        return redirect(url_for('login'))
    
    # 全件取得(新しい順)
    all_posts = Post.query.filter_by(user_id=current_user.id).order_by(Post.date_created.desc()).all()
    
    # --- 絵文字用 ---
    posts_with_emoji = []
    for post in all_posts:
        emoji = analyze_emoji(post.content)
        # DBから取り出すときに、JSTに変換
        jst_date = post.date_created.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Tokyo'))
        posts_with_emoji.append({
            "content": post.content,
            "date": jst_date,
            "emoji": emoji
        })

:muscle:まとめ

全てのエラーがはじめましてなので、多大な時間を要しました。
特にDB作成は本当に大変で、忘れられない経験になりました。
次同じエラーに出会ったら、とてもスムーズに解決できそうです:sunny:
アプリ開発では小さなエラーに10時間以上ハマることもあります。
おそらく今後も同じようにはまるんだろうなと思います。
でも一つずつ解消していけば、必ず動くものが完成します。
諦めないことが一番のデバッグ術!

:books: 関連記事

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?