1
2

More than 3 years have passed since last update.

Heroku、Flask、Python、にゃん子掲示板を「csvファイル」で作る

Last updated at Posted at 2020-03-10

(1)csvを使って掲示板を作成する

<ディレクトリ構成>

test
├app.py
├articles.csv
├Procfile
├requirements.txt
└templates
  ├index.html
  ├layout.html
  └index_result.html

①コンテンツの作成

仮想環境をディレクトリtestの直下に設定、起動。

python3 -m venv .
source bin/activate

必要なフレームワークとwebサーバーをインストール。

pip install flask
pip install gunicorn

articles.csvに、掲示板のデータをはじめに入れておく。

articles.csv
たま,眠いにゃー
しろ,腹減ったにゃー
クロ,なんだか暖かいにゃー
たま,ぽえーぽえーぽえー
ぽんたん,トイレットペーパーがない
なおちん,チーン

app.pyを作成。

app.py
# -*- coding: utf-8 -*-
from flask import Flask,request,render_template
app = Flask(__name__)

@app.route('/')
def bbs():
    lines = []
    #with openしてcsvファイルを読み込む
    with open('articles.csv',encoding='utf-8') as f:
        lines = f.readlines() #readlinesはリスト形式でcsvの内容を返す
    #index.htmlに返す
    return render_template('index.html',lines=lines)

#postメソッドを受け取る
@app.route('/result',methods=['POST'])
def result():
    #requestでarticleとnameの値を取得する
    article = request.form['article']
    name = request.form['name']
    #csvファイルに上書きモードで書き込む
    with open('articles.csv','a',encoding='utf-8') as f:
        f.write(name + ',' + article + '\n')
    #index_result.htmlに返す
    return render_template('index_result.html',article=article,name=name)


if __name__ == '__main__':
    app.run(debug=False)

index.htmlを作成。

index.html
{% extends 'layout.html' %}
{% block content %}
    <h1> にゃん子掲示板</h1>
    <form action='/result' method='post'>
        <label for='name'>にゃん子の名前</label>
        <input type='text' name='name'>
        <p></p>
        <label for='article'>投稿</label>
        <input type='text' name='article'>

        <button type='subimit'>書き込む</button>
    </form>

    <p></p>
    <p></p>

    <table border=1>
        <tr><th>にゃん子の名前</th><th>投稿内容</th></tr>
        {% for line in lines: %}
        <!--columnという変数をセット(変数セットにはsetが必要)  -->
        <!--splitを利用して,で分類する。splitはリストを返す  -->
            {% set column = line.rstrip().split(',') %}
            <tr><td>{{column[0]}}</td><td>{{column[1]}}</td></tr>
        {% endfor %}
    </table>

{% endblock %}

htmlのテンプレートを作成。

layout.html
<!DOCTYPE html>
<html lang='ja'>
  <head>
      <meta charset='utf-8'>
      <title>Nyanko BBS</title>
      <style>body{padding:10px;}</style>
  </head>
  <body>
    {% block content %}
    {% endblock %}
  </body>
</html>

index.htmlで入力したフォームの内容をindex_result.htmlであらわす。

layout.html
{% extends 'layout.html' %}
{% block content %}
    <h1> にゃ-んと掲示板に書き込みました</h1>
    <p>{{name}}{{article}}</p>

    <!--formで/に戻る -->
    <form action='/' method='get'>
      <button type='submit'>戻る</button>
    </form>

{% endblock %}

②Herokuへデプロイ

Herokuへのデプロイ詳細は以下の記事に書いた通りなので、詳細説明を省く。
Heroku、Flask、Python、Gitでアップロードする方法(その②)
Procfile、requirements.txtを作成、gitで操作して無事にデプロイできた。

スクリーンショット 2020-03-10 23.16.27.png
”いわし”、”魚が大好き”と投稿すると、
スクリーンショット 2020-03-10 23.16.41.png
書き込み成功!
戻ると、
スクリーンショット 2020-03-10 23.16.54.png
ちゃんと掲示板に書き込みされてます。

次回はsqlを使って掲示板を作りたい

Herokuでのcsv書き込みはしばらくすると(30分)データが消えてしまうので、sqlなどのデータベースを使って掲示板を作りたい。

1
2
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
1
2