teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

4

修正

2019/10/24 05:14

投稿

退会済みユーザー
title CHANGED
File without changes
body CHANGED
@@ -39,7 +39,6 @@
39
39
  import sys
40
40
 
41
41
  app = Flask(__name__)
42
- app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
43
42
  app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://username@localhost:5432/sample'
44
43
  db = SQLAlchemy(app)
45
44
 

3

プログラムを最新版に修正しました。

2019/10/24 05:14

投稿

退会済みユーザー
title CHANGED
File without changes
body CHANGED
@@ -34,96 +34,109 @@
34
34
 
35
35
  app.py
36
36
  ```python
37
- from flask import Flask, render_template
37
+ from flask import Flask, flash, render_template, request, redirect, url_for, abort, jsonify
38
38
  from flask_sqlalchemy import SQLAlchemy
39
+ import sys
39
40
 
40
41
  app = Flask(__name__)
42
+ app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
41
- app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://username@localhost:5432/textapp'
43
+ app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://username@localhost:5432/sample'
42
44
  db = SQLAlchemy(app)
43
45
 
44
46
  class Todo(db.Model):
45
- __tablename__ = 'texts'
47
+ __tablename__ = 'todos'
46
- id = db.Column(db.Integer, primary_key=True)
47
- username = db.Column(db.String(), nullable=False)
48
- texts = db.Column(db.String(), nullable=False)
49
48
 
50
- def __repr__(self):
49
+ id = db.Column(db.Integer, primary_key=True)
51
- return f'<Todo {self.id} {self.username} {self.texts}>'
50
+ username = db.Column(db.String(), nullable=False)
51
+ texts = db.Column(db.String(120))
52
52
 
53
+
54
+ def __repr__(self):
55
+ return f'<Todo {self.id} {self.username} {self.texts}>'
56
+
53
57
  db.create_all()
54
58
 
55
59
  #ユーザ名・テキストが入力されていたら、データベースに格納し、HTMLページに表示
56
- @app.route('/texts/create', methods=['POST'])
60
+ @app.route('/todos/create', methods=['POST'])
57
61
  def create_todo():
62
+ error = False
63
+ body = {}
64
+
65
+ try:
58
- username = request.form.get_json()['username']
66
+ username = request.form['username']
59
- texts = request.form.get_json()['texts']
67
+ texts = request.form['texts']
60
- todo = Todo(texts=texts)
68
+ todo = Todo(username=username, texts=texts)
61
69
 
70
+ if username and texts:
71
+ db.session.add(todo)
72
+ db.session.commit()
73
+ body['username'] = todo.username
74
+ body['texts'] = todo.texts
75
+ flash("成功", "success")
62
76
 
77
+ #ユーザー名、テキストが入力されていなかった時
63
- if username and texts:
78
+ elif username == "":
64
- flash("成功", "success")
79
+ flash("名前を入力してください", "failed")
65
- db.session.add(todo)
66
- db.session.commit()
80
+ b.session.rollback()
67
- return jsonify({
68
- 'username':todo.username,
69
- 'texts': todo.texts
70
- })
71
81
 
72
- #ユーザー名、テキストが入力されていなかった時
73
- elif username == "":
82
+ elif texts == "":
74
- flash("名前を入力してください", "failed")
83
+ flash("テキストを入力してくfださい", "failed")
75
- b.session.rollback()
84
+ db.session.rollback()
76
85
 
86
+ except:
77
- elif texts == "":
87
+ error = True
78
- flash("テキストを入力してくfださい", "failed")
79
88
  db.session.rollback()
89
+ print(sys.exc_info())
90
+ finally:
91
+ db.session.close()
92
+ if error:
93
+ abort (400)
94
+ else:
95
+ return jsonify(body)
80
96
 
81
-
82
97
  @app.route('/')
83
98
  def index():
84
- return render_template('index.html', data=Todo.query.all())
99
+ return render_template('index.html', data=Todo.query.all())
85
100
  ```
86
101
  templates(フォルダ)/index.html
87
102
  ```html
88
103
  <html>
89
- <head>
104
+ <head>
90
- <title>Todo App</title>
105
+ <title>Todo App</title>
91
- <style>
106
+ <style>
92
- #error {
107
+ .hidden{
93
- display: none;
108
+ display: none;
94
- }
109
+ }
95
- </style>
110
+ </style>
96
- </head>
111
+ </head>
97
- <body>
112
+ <body>
98
- <div id="error" class="hidden">Something went wrong!</div>
99
- <form id="form" method="post" action="/texts/create">
113
+ <form method="post" action="/todos/create">
114
+ <h4>username</h4>
100
- <input type="text" id="username" name="username">
115
+ <input type= "text" name="username" />
116
+ <h4>texts</h4>
101
- <input type="text" id="texts" name="texts" />
117
+ <input type= "text" name="texts" />
102
- <input type="submit" value="Create" />
118
+ <input type= "submit" value="Create" />
103
- </form>
119
+ </form>
104
- <ul id="username">
120
+ <div id= "error" class="hidden">Something went wrong!</div>
121
+ <ul>
105
- {% for d in data %}
122
+ {% for d in data %}
106
- <li>{{d.username}}</li>
123
+ <li>{{d.username}}</li>
124
+ <li>{{d.texts}}</li>
107
- {% endfor %}
125
+ {% endfor %}
108
- </ul>
126
+ </ul>
109
- <ul id="texts">
110
- {% for d in data %}
111
- <li>{{ d.texts }}</li>
112
- {% endfor %}
113
- </ul>
114
127
  <script>
115
- const nmInput = document.getElementById('username')
128
+ const unameInput = document.getElementById('username');
116
- const descInput = document.getElementById('texts');
129
+ const txInput = document.getElementById('texts');
117
130
  document.getElementById('form').onsubmit = function(e) {
118
131
  e.preventDefault();
119
- const nm = nameInput.value;
132
+ const name = unameInput.value;
120
- const desc = descInput.value;
133
+ const texts = txInput.value;
121
134
  descInput.value = '';
122
- fetch('/texts/create', {
135
+ fetch('/todos/create', {
123
136
  method: 'POST',
124
137
  body: JSON.stringify({
125
- 'username':nm,
138
+ 'username': username,
126
- 'texts': desc,
139
+ 'texts': texts,
127
140
  }),
128
141
  headers: {
129
142
  'Content-Type': 'application/json',
@@ -133,10 +146,9 @@
133
146
  .then(jsonResponse => {
134
147
  console.log('response', jsonResponse);
135
148
  li = document.createElement('li');
136
- li.innerText = nm;
149
+ li.innerText = name;
137
- li.innerText = desc;
150
+ li.innerText = city;
138
- document.getElementById('usernames').appendChild(li);
139
- document.getElementById('texts').appendChild(li);
151
+ document.getElementById('todos').appendChild(li);
140
152
  document.getElementById('error').className = 'hidden';
141
153
  })
142
154
  .catch(function() {
@@ -144,7 +156,7 @@
144
156
  })
145
157
  }
146
158
  </script>
147
- </body>
159
+ </body>
148
160
  </html>
149
161
  ```
150
162
 

2

コードの修正

2019/10/24 04:56

投稿

退会済みユーザー
title CHANGED
File without changes
body CHANGED
@@ -4,6 +4,7 @@
4
4
  PythonのライブラリFlaskを使ってWebアプリケーションを作成しています。
5
5
  掲示板のようなもので入力されたデータをページに加えていきたいです。
6
6
  フォームが空欄の時はフラッシュメッセージを使って警告をしてデータベースには格納せず、フォームが空欄でない場合はSQLAlchemyを使ってデータベースに入力されたデータを格納しています。
7
+
7
8
  ### 発生している問題・エラーメッセージ
8
9
  現在以下のコマンドでPythonプログラムを実行すると、HTML画面は問題なく表示されるのですが、入力ボタンを押してもデータがデータベースに格納されず、ウェブブラウザにも表示されない状況です。
9
10
  ```
@@ -58,7 +59,7 @@
58
59
  texts = request.form.get_json()['texts']
59
60
  todo = Todo(texts=texts)
60
61
 
61
- #ユーザー名、テキストが入力されていなかった時
62
+
62
63
  if username and texts:
63
64
  flash("成功", "success")
64
65
  db.session.add(todo)
@@ -68,6 +69,7 @@
68
69
  'texts': todo.texts
69
70
  })
70
71
 
72
+ #ユーザー名、テキストが入力されていなかった時
71
73
  elif username == "":
72
74
  flash("名前を入力してください", "failed")
73
75
  b.session.rollback()

1

typo

2019/10/23 10:26

投稿

退会済みユーザー
title CHANGED
File without changes
body CHANGED
@@ -31,7 +31,7 @@
31
31
 
32
32
  ### 該当のソースコード
33
33
 
34
- pp.py
34
+ app.py
35
35
  ```python
36
36
  from flask import Flask, render_template
37
37
  from flask_sqlalchemy import SQLAlchemy