Flask Heroku 3

``` 2024-11-30T11:58:02.774967+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jinja2/environment.py", line 969, in _load_template
2024-11-30T11:58:02.774967+00:00 app[web.1]: template = self.loader.load(self, name, self.make_globals(globals))
2024-11-30T11:58:02.774967+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jinja2/loaders.py", line 126, in load
2024-11-30T11:58:02.774967+00:00 app[web.1]: source, filename, uptodate = self.get_source(environment, name)
2024-11-30T11:58:02.774968+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/templating.py", line 59, in get_source
2024-11-30T11:58:02.774968+00:00 app[web.1]: return self._get_source_fast(environment, template)
2024-11-30T11:58:02.774968+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/templating.py", line 95, in _get_source_fast
2024-11-30T11:58:02.774968+00:00 app[web.1]: raise TemplateNotFound(template)
2024-11-30T11:58:02.774968+00:00 app[web.1]: jinja2.exceptions.TemplateNotFound: index.html
2024-11-30T11:58:02.811532+00:00 app[web.1]: 10.1.36.128 - - [30/Nov/2024:11:58:02 +0000] "GET / HTTP/1.1" 500 290 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
2024-11-30T11:58:02.811658+00:00 heroku[router]: at=info method=GET path="/" host=fractaltrail20241130-b723087de37d.herokuapp.com request_id=71bfbe3d-5df7-4ece-a108-475a5539161d fwd="222.98.167.222" dyno=web.1 connect=0ms service=38ms status=500 bytes=463 protocol=https
2024-11-30T11:58:21.742373+00:00 app[web.1]: [2024-11-30 11:58:21,742] ERROR in app: Exception on / [GET]
2024-11-30T11:58:21.742384+00:00 app[web.1]: Traceback (most recent call last):
2024-11-30T11:58:21.742384+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 2073, in wsgi_app
2024-11-30T11:58:21.742385+00:00 app[web.1]: response = self.full_dispatch_request()
2024-11-30T11:58:21.742385+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1518, in full_dispatch_request
2024-11-30T11:58:21.742386+00:00 app[web.1]: rv = self.handle_user_exception(e)
2024-11-30T11:58:21.742386+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1516, in full_dispatch_request
2024-11-30T11:58:21.742387+00:00 app[web.1]: rv = self.dispatch_request()
2024-11-30T11:58:21.742387+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1502, in dispatch_request
2024-11-30T11:58:21.742387+00:00 app[web.1]: return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
2024-11-30T11:58:21.742387+00:00 app[web.1]: File "/app/app.py", line 32, in index
2024-11-30T11:58:21.742388+00:00 app[web.1]: return render_template('index.html')
2024-11-30T11:58:21.742388+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/templating.py", line 148, in render_template
2024-11-30T11:58:21.742389+00:00 app[web.1]: ctx.app.jinja_env.get_or_select_template(template_name_or_list),
2024-11-30T11:58:21.742389+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jinja2/environment.py", line 1081, in get_or_select_template
2024-11-30T11:58:21.742390+00:00 app[web.1]: return self.get_template(template_name_or_list, parent, globals)
2024-11-30T11:58:21.742390+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jinja2/environment.py", line 1010, in get_template
2024-11-30T11:58:21.742390+00:00 app[web.1]: return self._load_template(name, globals)
2024-11-30T11:58:21.742390+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jinja2/environment.py", line 969, in _load_template
2024-11-30T11:58:21.742391+00:00 app[web.1]: template = self.loader.load(self, name, self.make_globals(globals))
2024-11-30T11:58:21.742391+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jinja2/loaders.py", line 126, in load
2024-11-30T11:58:21.742391+00:00 app[web.1]: source, filename, uptodate = self.get_source(environment, name)
2024-11-30T11:58:21.742391+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/templating.py", line 59, in get_source
2024-11-30T11:58:21.742391+00:00 app[web.1]: return self._get_source_fast(environment, template)
2024-11-30T11:58:21.742392+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/templating.py", line 95, in _get_source_fast
2024-11-30T11:58:21.742392+00:00 app[web.1]: raise TemplateNotFound(template)
2024-11-30T11:58:21.742392+00:00 app[web.1]: jinja2.exceptions.TemplateNotFound: index.html
2024-11-30T11:58:21.742889+00:00 app[web.1]: 10.1.36.128 - - [30/Nov/2024:11:58:21 +0000] "GET / HTTP/1.1" 500 290 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
2024-11-30T11:58:21.743249+00:00 heroku[router]: at=info method=GET path="/" host=fractaltrail20241130-b723087de37d.herokuapp.com request_id=692717f0-4b87-4ff1-be69-e2548b08d37c fwd="222.98.167.222" dyno=web.1 connect=0ms service=2ms status=500 bytes=463 protocol=https
2024-11-30T11:58:40.553178+00:00 app[web.1]: [2024-11-30 11:58:40,552] ERROR in app: Exception on / [GET]
2024-11-30T11:58:40.553189+00:00 app[web.1]: Traceback (most recent call last):
2024-11-30T11:58:40.553189+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 2073, in wsgi_app
2024-11-30T11:58:40.553189+00:00 app[web.1]: response = self.full_dispatch_request()
2024-11-30T11:58:40.553201+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1518, in full_dispatch_request
2024-11-30T11:58:40.553201+00:00 app[web.1]: rv = self.handle_user_exception(e)
2024-11-30T11:58:40.553202+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1516, in full_dispatch_request
2024-11-30T11:58:40.553202+00:00 app[web.1]: rv = self.dispatch_request()
2024-11-30T11:58:40.553202+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1502, in dispatch_request
2024-11-30T11:58:40.553202+00:00 app[web.1]: return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
2024-11-30T11:58:40.553203+00:00 app[web.1]: File "/app/app.py", line 32, in index
2024-11-30T11:58:40.553203+00:00 app[web.1]: return render_template('index.html')
2024-11-30T11:58:40.553203+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/templating.py", line 148, in render_template
2024-11-30T11:58:40.553204+00:00 app[web.1]: ctx.app.jinja_env.get_or_select_template(template_name_or_list),
2024-11-30T11:58:40.553208+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jinja2/environment.py", line 1081, in get_or_select_template
2024-11-30T11:58:40.553208+00:00 app[web.1]: return self.get_template(template_name_or_list, parent, globals)
2024-11-30T11:58:40.553208+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jinja2/environment.py", line 1010, in get_template
2024-11-30T11:58:40.553208+00:00 app[web.1]: return self._load_template(name, globals)
2024-11-30T11:58:40.553208+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jinja2/environment.py", line 969, in _load_template
2024-11-30T11:58:40.553209+00:00 app[web.1]: template = self.loader.load(self, name, self.make_globals(globals))
2024-11-30T11:58:40.553209+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jinja2/loaders.py", line 126, in load
2024-11-30T11:58:40.553209+00:00 app[web.1]: source, filename, uptodate = self.get_source(environment, name)
2024-11-30T11:58:40.553209+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/templating.py", line 59, in get_source
2024-11-30T11:58:40.553209+00:00 app[web.1]: return self._get_source_fast(environment, template)
2024-11-30T11:58:40.553209+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/templating.py", line 95, in _get_source_fast
2024-11-30T11:58:40.553209+00:00 app[web.1]: raise TemplateNotFound(template)
2024-11-30T11:58:40.553210+00:00 app[web.1]: jinja2.exceptions.TemplateNotFound: index.html
2024-11-30T11:58:40.553743+00:00 app[web.1]: 10.1.36.128 - - [30/Nov/2024:11:58:40 +0000] "GET / HTTP/1.1" 500 290 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
2024-11-30T11:58:40.554155+00:00 heroku[router]: at=info method=GET path="/" host=fractaltrail20241130-b723087de37d.herokuapp.com request_id=f3accac4-6039-42b7-b707-c55dc0a0ca5d fwd="222.98.167.222" dyno=web.1 connect=0ms service=2ms status=500 bytes=463 protocol=https
2024-11-30T11:58:43.106130+00:00 app[web.1]: [2024-11-30 11:58:43,105] ERROR in app: Exception on / [GET]
2024-11-30T11:58:43.106146+00:00 app[web.1]: Traceback (most recent call last):
2024-11-30T11:58:43.106147+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 2073, in wsgi_app
2024-11-30T11:58:43.106148+00:00 app[web.1]: response = self.full_dispatch_request()
2024-11-30T11:58:43.106148+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1518, in full_dispatch_request
2024-11-30T11:58:43.106149+00:00 app[web.1]: rv = self.handle_user_exception(e)
2024-11-30T11:58:43.106149+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1516, in full_dispatch_request
2024-11-30T11:58:43.106149+00:00 app[web.1]: rv = self.dispatch_request()
2024-11-30T11:58:43.106149+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/app.py", line 1502, in dispatch_request
2024-11-30T11:58:43.106160+00:00 app[web.1]: return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
2024-11-30T11:58:43.106160+00:00 app[web.1]: File "/app/app.py", line 32, in index
2024-11-30T11:58:43.106161+00:00 app[web.1]: return render_template('index.html')
2024-11-30T11:58:43.106161+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/templating.py", line 148, in render_template
2024-11-30T11:58:43.106162+00:00 app[web.1]: ctx.app.jinja_env.get_or_select_template(template_name_or_list),
2024-11-30T11:58:43.106162+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jinja2/environment.py", line 1081, in get_or_select_template
2024-11-30T11:58:43.106163+00:00 app[web.1]: return self.get_template(template_name_or_list, parent, globals)
2024-11-30T11:58:43.106163+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jinja2/environment.py", line 1010, in get_template
2024-11-30T11:58:43.106163+00:00 app[web.1]: return self._load_template(name, globals)
2024-11-30T11:58:43.106164+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jinja2/environment.py", line 969, in _load_template
2024-11-30T11:58:43.106164+00:00 app[web.1]: template = self.loader.load(self, name, self.make_globals(globals))
2024-11-30T11:58:43.106164+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jinja2/loaders.py", line 126, in load
2024-11-30T11:58:43.106164+00:00 app[web.1]: source, filename, uptodate = self.get_source(environment, name)
2024-11-30T11:58:43.106165+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/templating.py", line 59, in get_source
2024-11-30T11:58:43.106165+00:00 app[web.1]: return self._get_source_fast(environment, template)
2024-11-30T11:58:43.106165+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask/templating.py", line 95, in _get_source_fast
2024-11-30T11:58:43.106165+00:00 app[web.1]: raise TemplateNotFound(template)
2024-11-30T11:58:43.106165+00:00 app[web.1]: jinja2.exceptions.TemplateNotFound: index.html
2024-11-30T11:58:43.106684+00:00 app[web.1]: 10.1.36.128 - - [30/Nov/2024:11:58:43 +0000] "GET / HTTP/1.1" 500 290 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
2024-11-30T11:58:43.106978+00:00 heroku[router]: at=info method=GET path="/" host=fractaltrail20241130-b723087de37d.herokuapp.com request_id=276dec85-ed71-41f0-b114-780226d535a0 fwd="222.98.167.222" dyno=web.1 connect=0ms service=2ms status=500 bytes=463 protocol=https
2024-11-30T11:58:43.447763+00:00 app[web.1]: 10.1.36.128 - - [30/Nov/2024:11:58:43 +0000] "GET /favicon.ico HTTP/1.1" 404 232 "https://fractaltrail20241130-b723087de37d.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
2024-11-30T11:58:43.448153+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=fractaltrail20241130-b723087de37d.herokuapp.com request_id=0a223946-f840-4529-8ea7-d74a618ac28c fwd="222.98.167.222" dyno=web.1 connect=0ms service=1ms status=404 bytes=393 protocol=https ```

Heroku 로그에서 jinja2.exceptions.TemplateNotFound: index.html 오류가 발생하고 있습니다. 아래 단계를 통해 문제를 해결해보세요:

  1. index.html 파일 위치 확인:
    • index.html 파일이 반드시 프로젝트 루트 폴더 내의 templates 폴더에 있어야 합니다.
    • 현재 templates 폴더가 루트에 있고 그 안에 index.html 파일이 있는지 다시 확인하세요.
  2. Git 추적 상태 확인:
    • Heroku에서 배포된 프로젝트에 index.html이 제대로 포함되지 않았을 수 있습니다. 다음 명령어로 해당 파일을 Git에 추가하고 다시 푸시하세요:
git add templates/index.html templates/result.html
git commit -m "Add missing template files"
git push heroku master

템플릿 경로가 정확한지 확인:

  • Flask에서 템플릿을 렌더링할 때는 기본적으로 templates 디렉터리를 찾습니다. 따라서 코드에서 render_template('index.html')라고만 사용하면 됩니다.
  • app.py 코드에서 render_template() 함수 호출이 제대로 되어 있는지 확인해주세요.

Heroku 재배포:

  • Heroku에서 배포 시에 캐시 문제로 인해 파일이 적용되지 않을 수 있습니다. 새로운 변경사항을 확실히 반영하기 위해서 빈 커밋을 만들어 다시 배포할 수 있습니다:
git commit --allow-empty -m "Trigger redeploy"
git push heroku master

이 단계를 모두 수행한 후 Heroku 로그를 다시 확인하고 문제가 해결되는지 확인해보세요.

app.py 코드에서 render_template() 함수 호출이 제대로 ‘ 안되어 있어요 ‘

app.py에서 render_template() 함수 호출을 제대로 고치기 위해서, 다음 사항을 확인하세요:

  1. 템플릿 파일 이름과 경로 확인:
    • 템플릿 파일(index.html)이 templates 폴더 안에 있어야 합니다.
    • render_template() 함수에 전달되는 파일 이름이 정확하게 index.html로 되어 있는지 확인하세요.
  2. render_template() 함수의 사용 예시:
    • render_template() 함수 호출 부분이 제대로 작성되었는지 확인해야 합니다. 예를 들어:
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)
  1. 확인 후 적용:
    • 위 코드를 확인하여 render_template('index.html') 함수 호출이 정확하게 작성되었는지, Flask의 templates 디렉터리에서 해당 파일을 찾을 수 있는지 확인해주세요.

혹시 수정한 부분을 보여주시면, 구체적으로 어떤 부분에서 문제가 있었는지 더 도와드릴 수 있어요.

``` import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf
from flask import Flask, request, render_template, redirect, url_for
from datetime import datetime, timedelta
import io
import base64
import os

# Use a non-GUI backend for Matplotlib
plt.switch_backend('Agg')

# Create Flask app
app = Flask(__name__)

# Function to load data from Yahoo Finance
def load_stock_data(ticker, start_date, end_date):
    stock = yf.download(ticker, start=start_date, end=end_date)
    stock.reset_index(inplace=True)
    return stock

# Function to format the ticker for Yahoo Finance
def format_ticker(ticker):
    if ticker.isdigit():  # Korean stock ticker
        return ticker + ".KS"
    return ticker  # US or other tickers

# Route for the index page
@app.route('/')
def index():
    return render_template('index.html')

# Route for analyzing the stock data
@app.route('/analyze', methods=['POST'])
def analyze():
    ticker = request.form['ticker']
    ticker = format_ticker(ticker)

    end_date = datetime.now()
    start_date = end_date - timedelta(days=200)

    df = load_stock_data(ticker, start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'))

    if df.empty:
        return render_template('index.html', error="No data found for the given ticker. Please try again.")

    # 1. Find Fractals
    def find_fractals(df, left_range=2, right_range=2):
        high_fractals = []
        low_fractals = []

        for i in range(left_range, len(df) - right_range):
            is_high_fractal = all(df['High'][i] > df['High'][i - j] for j in range(1, left_range + 1)) and all(df['High'][i] > df['High'][i + j] for j in range(1, right_range + 1))
            is_low_fractal = all(df['Low'][i] < df['Low'][i - j] for j in range(1, left_range + 1)) and all(df['Low'][i] < df['Low'][i + j] for j in range(1, right_range + 1))

            high_fractals.append(df['High'][i] if is_high_fractal else np.nan)
            low_fractals.append(df['Low'][i] if is_low_fractal else np.nan)

        high_fractals = [np.nan] * left_range + high_fractals + [np.nan] * right_range
        low_fractals = [np.nan] * left_range + low_fractals + [np.nan] * right_range

        return pd.Series(high_fractals, index=df.index), pd.Series(low_fractals, index=df.index)

    df['High_Fractal'], df['Low_Fractal'] = find_fractals(df)

    # 2. Add Buffer to Fractals
    def add_buffer(fractal_prices, buffer_percent, direction='minus'):
        if direction == 'plus':
            return fractal_prices * (1 + buffer_percent / 100)
        elif direction == 'minus':
            return fractal_prices * (1 - buffer_percent / 100)
        else:
            return fractal_prices

    df['High_Fractal_Buffered'] = add_buffer(df['High_Fractal'], buffer_percent=2, direction='plus')
    df['Low_Fractal_Buffered'] = add_buffer(df['Low_Fractal'], buffer_percent=2, direction='minus')

    # 3. Update Trailing Stop
    def update_trailing_stop(fractal_prices, previous_trail, price_data, direction='up'):
        trail = []
        for i in range(len(fractal_prices)):
            if i == 0:
                trail.append(fractal_prices[i] if not np.isnan(fractal_prices[i]) else price_data[i])
            else:
                if direction == 'down' and price_data[i] >= previous_trail:
                    trail.append(previous_trail)
                elif direction == 'up' and price_data[i] <= previous_trail:
                    trail.append(previous_trail)
                else:
                    trail.append(fractal_prices[i] if not np.isnan(fractal_prices[i]) else previous_trail)
            previous_trail = trail[-1]
        return pd.Series(trail, index=fractal_prices.index)

    df['Long_Trailing_Stop'] = update_trailing_stop(df['Low_Fractal_Buffered'], df['Low_Fractal_Buffered'].iloc[0], df['Close'], direction='up')
    df['Short_Trailing_Stop'] = update_trailing_stop(df['High_Fractal_Buffered'], df['High_Fractal_Buffered'].iloc[0], df['Close'], direction='down')

    # 4. Flip Trend Logic
    def flip_trend(price_data, long_trail, short_trail):
        is_long = True
        long_trail_output = []
        short_trail_output = []

        for i in range(len(price_data)):
            if is_long and price_data[i] < short_trail[i] and not np.isnan(short_trail[i]):
                is_long = False
            elif not is_long and price_data[i] > long_trail[i] and not np.isnan(long_trail[i]):
                is_long = True

            long_trail_output.append(long_trail[i] if is_long else np.nan)
            short_trail_output.append(short_trail[i] if not is_long else np.nan)

        return pd.Series(long_trail_output, index=price_data.index), pd.Series(short_trail_output, index=price_data.index)

    df['Long_Trail_Output'], df['Short_Trail_Output'] = flip_trend(df['Close'], df['Long_Trailing_Stop'], df['Short_Trailing_Stop'])

    # Plotting the Results
    plt.figure(figsize=(14, 7))
    plt.plot(df.index, df['Close'], label='Price', color='black')
    plt.plot(df.index, df['Long_Trail_Output'], label='Long Stop Price', linestyle='--', color='green')
    plt.plot(df.index, df['Short_Trail_Output'], label='Short Stop Price', linestyle='--', color='red')
    plt.scatter(df.index, df['High_Fractal'], label='High Fractal', marker='v', color='blue')
    plt.scatter(df.index, df['Low_Fractal'], label='Low Fractal', marker='^', color='orange')
    plt.legend()
    plt.tight_layout()

    # Save plot to a PNG image and encode it to base64
    img = io.BytesIO()
    plt.savefig(img, format='png')
    img.seek(0)
    plot_url = base64.b64encode(img.getvalue()).decode()
    plt.close()

    return render_template('result.html', plot_url=plot_url)

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 5000))
    app.run(host="0.0.0.0", port=port, debug=False)

# Procfile
# web: python main.py

# requirements.txt
# Flask
# pandas
# numpy
# matplotlib
# yfinance
# gunicorn  ```

To address the render_template() error (TemplateNotFound: index.html), you should check the following:

  1. Ensure the Correct Directory Structure:
    • Your templates folder should be in the same directory as app.py.
    • The index.html file should be inside the templates folder.
    Based on your provided screenshot, it appears you have a templates folder with index.html and result.html, so this part seems correct. However, double-check the spelling and ensure there’s no typo in the folder name or file names (templates/index.html).
  2. Verify the Git Commit:
    • It seems there might be an issue with the changes not being committed properly.
    • To confirm that index.html and result.html have been committed
git status

If you see that the files are not staged for commit, you can add them:

git add templates/index.html templates/result.html
git commit -m "Add index.html and result.html to templates directory"
git push heroku master

Check Deployment to Heroku:

  • After committing the changes, redeploy to Heroku.

Use the command

git push heroku master
  • Heroku should now have access to the updated templates folder and all the necessary HTML files.

Debug Logging:

  • To help debug the issue further, you can add some log statements to ensure the index.html is being correctly located:
import logging
logging.basicConfig(level=logging.DEBUG)

@app.route('/')
def index():
    app.logger.info("Rendering index.html")
    return render_template('index.html')

This will print to the console when index.html is being rendered, which can help identify if there’s an issue with the HTML path or the Flask setup.

After making these changes, try redeploying your app and access the root URL (/). The index.html page should load without the TemplateNotFound error.

Let me know if you need further assistance!

PS C:_Fractal Trail> git status
On branch master
nothing to commit, working tree clean

Since your `git status` shows that the working tree is clean, this means all changes, including your `index.html` and `result.html` files, have already been committed.

However, the `TemplateNotFound` error indicates that Heroku might not have those files in the deployed version. Here are the next steps you should take:

1. **Verify Templates Folder in Deployed Build**:
   - Log in to Heroku and open a console in the application:
     ```sh
     heroku run bash
     ```
   - Navigate to your application root directory:
     ```sh
     cd /app
     ```
   - Check if the `templates` directory and its contents (`index.html` and `result.html`) are present:
     ```sh
     ls templates
     ```
   - If the `templates` folder or files are missing, it might indicate an issue with them being tracked properly by Git or being included in the Heroku build.

2. **Check Git Ignore Files**:
   - Ensure that `.gitignore` does not accidentally contain entries that ignore the `templates` folder or HTML files.
   - Open the `.gitignore` file, if it exists, and verify its contents:
     ```sh
     cat .gitignore
     ```
   - If `templates/` or `.html` files are ignored, remove the relevant entries.

3. **Ensure Changes Are Pushed to Heroku**:
   - Try forcing the push to Heroku in case the changes were not deployed correctly:
     ```sh
     git push heroku master --force
     ```

4. **Check the Procfile**:
   - Make sure that the `Procfile` correctly runs your `app.py` file.
   - Your current `Procfile` comment indicates:
     ```sh
     # web: python main.py
     ```
   - It should correctly reference `app.py` instead, like this:
     ```sh
     web: gunicorn app:app
     ```
   - Update the `Procfile` if necessary, commit the changes, and redeploy:
     ```sh
     git add Procfile
     git commit -m "Update Procfile to use app.py"
     git push heroku master
     ```

5. **Heroku Restart**:
   - Restart the Heroku application to apply all recent changes:
     ```sh
     heroku restart
     ```

6. **Access Logs for Detailed Errors**:
   - Run `heroku logs --tail` to check the logs again after redeploying.
   - Look for any errors related to file paths or templates not being found.

These steps should help resolve the issue with `index.html` not being found. Please try these, and let me know if the issue persists or if you encounter any other problems!
``` PS C:\_Fractal Trail> heroku run bash
Running bash on ⬢ fractaltrail20241130... up, run.9145
~ $ 
~ $ cd /app
~ $ ls templates
Index.html  Result.html
~ $  ```

댓글 달기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

위로 스크롤