0
1

More than 1 year has passed since last update.

ホームページを作る[Windows]

Last updated at Posted at 2022-05-22

目次

  1. 事前準備
  2. ホームページ表示
  3. 投稿フォーム作成

1. 事前準備

ここでは、flaskで作った簡潔なWebアプリケーションをHerokuに送信し、実行します。

Herokuの環境構築

こちらを参考に行ってください

ディレクトリの構築

以下のように、フォルダ、ファイルを作成します。

ディレクトリ構造
<APP NAME>/
|--flaskr/
|   |--templates/    # htmlフォルダ
|   |   |--index.html
|   |--staics/    # cssフォルダ
|   |   |--style.css
|   |--__init__.py
|   |--main.py    # flaskのメイン処理
|--flask_run.py    # flask起動
|--Procfile    # Herokuにて実行処理
|--requirements.txt    # インストール外部ライブラリ指定
|--runtime.txt    # 実行環境指定

簡潔な実行環境、アプリケーションを作成します。

/runtime.txt
python-3.9.13    # pythonバージョン指定
/requirements.txt
Flask==2.1.2    # Flaskバージョン指定
/flaskr/__init__.py
from flask import Flask
app = Flask(__name__)    # flaskオブジェクト作成

import flaskr.main    # flaskメイン処理実行
/flaskr/main.py
from flaskr import app

@app.route("/")    # [現在のURL+"/"]と通信時、実行
def index():
   return "Hello World!"    # 画面表示
/flask_run.py
import flaskr
import os
if __name__ == "__main__":
   port = int(os.getenv("PORT",5000))    # ポート指定(デフォルト:5000)
   flaskr.app.run(    # flask起動
       host="0.0.0.0",    # ipアドレス指定(localhost)
       port=port,
       debug=True    # デバッグをする
       )
/Procfile
web: python flask_run.py    # Heorkuにてmain.py実行

Herokuに送信

作成したWebアプリケーションをHeorkuに保存し、実行します。

heroku login    # Heorkuにログイン
heroku create <APP NAME>    # アプリ作成
cd <Procfileなどが置かれているディレクトリ>    # ディレクトリ移動
git init    # 共有レポジトリ作成
git add .    # ディレクトリ内すべてをコミット予約
git commit -m "first commit"    # 共有レポジトリに保存
heroku git:remote -a <APP NAME>    # HerokuとGitを結びつける
git push heroku master    # Heorkuに送信
heroku logs --app <APP NAME>    # ログ確認

表示されるURLにアクセスして、Hello World! と表示されれば完了です。
されない場合、ログを確認してください。

2. ホームページ表示

ホームページの初期画面を表示させます。

初期画面を作成

HTMLとCSSで作成します。

/flaskr/templates/index.html
<!DOCTYPE html>
<html lang="ja">
 <head>
   <meta charset="UTF-8">
   <title>ホームページ</title>
   <!-- cssと連携 -->
   <link rel="stylesheet" href="/static/style.css">
 </head>
 <body>
   <h1>ホームページ</h1>
   <p>Hello World!!</p>
 </body>
</html>
/flaskr/static/syle.css
h1{
   size: 2em;
   color:lightskyblue
}
p{
   color: aqua;
}

初期画面表示

flaskにてHTMLを表示させるコマンド(render_template)を追加します。

/flaskr/main.py
from flaskr import app
from flask import render_template

@app.route("/")    # [現在のURL+"/"]と通信時、実行
def index():
  return render_template(
      "index.html"    # index.htmlを表示する
  )

変更をHerokuへ送信させます。

git add .    # フォルダ内すべてをcommitに予約する
git commit -m "add_html"    # 変更データ保存
git push heroku master    # Herokuへ送信

Herokuのリンクに、作成した初期画面が表示されれば完成です。

3. 投稿フォーム作成

Herokuでデータベースを扱う際に、※1splite3は使用できないので、Heroku Postgresを使用します。
※1.Herokuは定期的にに最後にcommitした状態に戻るため、作成された.dbは消える。

データベース作成

以下のデータベース作成を参考にしてください。

データベース読み込み

Pythonでは、psypcopg2を使用します。
作成したデータベースのURIを環境変数に保存しておきます。

heroku config:set POSTGRESQL_DSN="<URI>" --app <アプリ名>

ファイルを以下の様に変更します。

/requirements.txt
Flask==2.1.2
#+++++++++++++++++++++++++++以下を追加+++++++++++++++++++++++++++++++++++++++++++
psycopg2==2.9.3
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/flaskr/__init__.py
from flask import Flask
app = Flask(__name__)

#+++++++++++++++++++++++++++以下を追加+++++++++++++++++++++++++++++++++++++++++++
import os
import psycopg2
DSN = os.environ.get("POSTGRESQL_DSN")    # 接続文字列取得
class DB:    # 接続するクラスを作成
   def open(self):
       self.conn = psycopg2.connect(DSN)
       self.cur = self.conn.cursor()
   def close(self):
       self.cur.close()
       self.conn.close()
   def commit(self):
       self.conn.commit()
SQL = DB()
SQL.open()
# 空のテーブル作成
SQL.cur.execute("CREATE TABLE IF NOT EXISTS comment (_name_ TEXT,_text_ TEXT)")
SQL.commit()
SQL.close()
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

import flaskr.main
/flaskr/main.py
#+++++++++++++++++++++++++++以下を変更+++++++++++++++++++++++++++++++++++++++++++
from flaskr import app, SQL    # 接続クラス取得
from flask import render_template, url_for

@app.route("/")    # [現在のURL+"/"]と通信時、実行
def index():
  return render_template(
      "index.html"    # index.htmlを表示する
  )
@app.route("/form", methods=["POST"])
def form():
   _name_ = request.form.get("date",default="????")
   _text_ = request.form.get("title",default="????")
   document = request.form.get("document",default="")
   SQL.open()
   SQL.cur.execute("INSERT INTO history VALUES (%s,%s,%s)",[date,title,document])
   SQL.commit()
   SQL.close()
   return redirect(url_for("index"))
/flaskr/templates/index.html
<!DOCTYPE html>
<html lang="ja">
 <head>
   <meta charset="UTF-8">
   <title>ホームページ</title>
   <!-- cssと連携 -->
   <link rel="stylesheet" href="/static/style.css">
 </head>
 <body>
   <h1>ホームページ</h1>
   <p>Hello World!!</p>
 </body>
</html>
0
1
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
1