0
0

More than 1 year has passed since last update.

【python】勉強メモ 速習Flask③

Posted at

1 はじめに

今回は、DBに登録された情報を表示する学習です。

2 コード編集

app.pyと、index.htmlを以下の様に編集。

app.py
from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import pytz

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///blog.db"
db = SQLAlchemy(app)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title= db.Column(db.String(50), nullable=True)
    body = db.Column(db.String(300), nullable=True)
    created_at = db.Column(db.DateTime, nullable=False,default=datetime.now(pytz.timezone('Asia/Tokyo')))

# GETとPOSTを受け取れる様にする。
@app.route("/", methods=['GET', 'POST'])
def index():
    # ページにアクセスしたら(HTTP GETでアクセスしたら)
    if request.method == 'GET':
        # DBに登録されたデーターを全てPostで取得する。取得したデーターは、postsに、リスト形式で格納される。
        posts = Post.query.all()
        # index.htmlに表示するため、posts=postsで、取得したデーターを渡す。
        return render_template('index.html', posts=posts)


@app.route("/create", methods=['GET', 'POST']) 
def create():
    if request.method == 'POST':
        title = request.form.get('title')
        body = request.form.get('body')

        post = Post(title=title, body=body)

        db.session.add(post)
        # 変更を保存
        db.session.commit()

        return redirect('/')
    else:
        return render_template('create.html')
index.html
{% extends "base.html" %}
{% block content %}
<h1>ブログアプリケーション</h1>

<a href="/create" role="button">新規作成画面</a>
{% for post in posts %}
<article>
    <h2>{{ post.title }}</h2>
    <p>作成日時: {{ post.created_at }}</p>
    <p>{{ post.body }}</p>
</article>
{% endfor %}
{% endblock %}

新規登録画面から、新規登録を行い、登録内容が掲載さる。

Flask-10.PNG

以下の様にテスト入力したものが登録され、表示される。
Flask-11.PNG

編集方法

templatesフォルダ内に、新たに、update.htmlを作成。
create.htmlをコピーして必要箇所を修正が効率良いです。

update.html
{% extends "base.html" %}
{% block content %}
<h1>編集</h1>
<form method="POST">
    <label for="title">タイトル</label>
    <!-- value="{{ post.title }}" は、render_templateから情報を取得してくる -->
    <input type="text" name="title" value="{{ post.title }}">
    <label for="body">内容</label>
    <!-- value="{{ post.body }}" も、render_templateから情報を取得してくる -->
    <input type="text" name="body" value="{{ post.body }}">
    <input type="submit" value="更新">
</form>
{% endblock %}
index.html
{% extends "base.html" %}
{% block content %}
<h1>ブログアプリケーション</h1>

<a href="/create" role="button">新規作成画面</a>
{% for post in posts %}
<article>
    <h2>{{ post.title }}</h2>
    <!-- 編集ボタン作成 -->
    <a href="/{{post.id}}/update" role="button">編集</a>
    <p>作成日時: {{ post.created_at }}</p>
    <p>{{ post.body }}</p>
</article>
{% endfor %}
{% endblock %}

app.pyの編集

app.py
from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import pytz

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///blog.db"
db = SQLAlchemy(app)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title= db.Column(db.String(50), nullable=True)
    body = db.Column(db.String(300), nullable=True)
    created_at = db.Column(db.DateTime, nullable=False,default=datetime.now(pytz.timezone('Asia/Tokyo')))

# GETとPOSTを受け取れる様にする。
@app.route("/", methods=['GET', 'POST'])
def hello():
    # ページにアクセスしたら(HTTP GETでアクセスしたら)
    if request.method == 'GET':
        # DBに登録されたデーターを全てPostで取得する。取得したデーターは、postsに、リスト形式で格納される。
        posts = Post.query.all()
        # index.htmlに表示するため、posts=postsで、取得したデーターを渡す。
        return render_template('index.html', posts=posts)


@app.route("/create", methods=['GET', 'POST']) 
def create():
    if request.method == 'POST':
        title = request.form.get('title')
        body = request.form.get('body')

        post = Post(title=title, body=body)

        db.session.add(post)
        # 変更を保存
        db.session.commit()

        return redirect('/')
    else:
        return render_template('create.html')

# update処理を作成
@app.route("/<int:id>/update", methods=['GET', 'POST']) 
def update(id):
    post = Post.query.get(id)
    
    if request.method == 'GET':
        return render_template('update.html', post=post)
    
    # 更新ボタンが押されると、POSTが送信されるめ、eles移行が実行される
    else:
        post.title = request.form.get('title') # 書き換え
        post.body = request.form.get('body') # 書き換え
        
        # 不要なのでコメントアウト
        # post = Post(title=title, body=body)
        
        # db.session.add(post) 更新なので、addする必要はないため削除
        # commitだけすれば良い
        db.session.commit()

        return redirect('/')
        # return render_template('create.html')

ブラウザで、127.0.0.1:5000へアクセスし、編集ボタンが作成されていることを確認
Flask-12.PNG

次回は、登録内容の編集(更新)を行います。

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