質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Flask

FlaskはPython用のマイクロフレームワークであり、Werkzeug・Jinja 2・good intentionsをベースにしています。

SQLAlchemy

SQLAlchemyとはPython 用のORMライブラリです。MIT Licenceのオープンソースとして提供されています。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

HTML

HTMLとは、ウェブ上の文書を記述・作成するためのマークアップ言語のことです。文章の中に記述することで、文書の論理構造などを設定することができます。ハイパーリンクを設定できるハイパーテキストであり、画像・リスト・表などのデータファイルをリンクする情報に結びつけて情報を整理します。現在あるネットワーク上のほとんどのウェブページはHTMLで作成されています。

PyCharm

エディター・開発ツール

Q&A

解決済

1回答

1481閲覧

〔Flask〕webアプリで、新規メンバー登録ができない

Ekito

総合スコア4

Flask

FlaskはPython用のマイクロフレームワークであり、Werkzeug・Jinja 2・good intentionsをベースにしています。

SQLAlchemy

SQLAlchemyとはPython 用のORMライブラリです。MIT Licenceのオープンソースとして提供されています。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

HTML

HTMLとは、ウェブ上の文書を記述・作成するためのマークアップ言語のことです。文章の中に記述することで、文書の論理構造などを設定することができます。ハイパーリンクを設定できるハイパーテキストであり、画像・リスト・表などのデータファイルをリンクする情報に結びつけて情報を整理します。現在あるネットワーク上のほとんどのウェブページはHTMLで作成されています。

PyCharm

エディター・開発ツール

0グッド

0クリップ

投稿2020/12/19 03:27

#はじめに

Python, Flaskを用いて「web上の神社にお願い事を送る」というwebアプリを開発中です。
こちらのサイトを参考にしています)
アプリにおいて、新規メンバー登録をしようとするとエラーが起きてしまいます。10個ほどファイルを作成しているのですが、PyCharm上ではエラーが検出されず、具体的にどのファイルに問題があるのかわかりません。アドバイスをいただけると幸いです。

#プログラム全体の概要
作成しているファイル全体は以下の通りです。はっきりとは分かりませんが、①②あたりに不具合があるように思われます。

①アプリの中身のプログラム(app/app.py)
②暗号化キーを扱うプログラム(app/key.py)
③webアプリを実行するプログラム(run.py)
④空のプログラム(app/_ init _.py)

⑤神社にお願い事を送れるトップページ(app/templates/index.html)
⑥メンバーとしてログインできるページ(app/templates/top.html)
⑦新規メンバー登録できるページ(app/templates/newcomer.html)

*「お願い事」の情報を保管するDB
⑧テーブルのカラム情報を定義するためのクラスを格納するプログラム(models/models.py)
⑨DBとの直接的な接続の情報を格納するプログラム(models/database.py)
⑩空のプログラム(models/_ init _.py)

#エラーの内容
ターミナルでrun.pyを実行して、以下のようなwebページを開くことができました。
top.html
その後新規登録の画面に進み、ユーザー名とパスワードを入力してボタンを押すとエラーが表示されてしまいます。
newcomer.html

エラー

PyCharmでコードを書いていましたが、そこではエラーが検出されませんでした。app.pyやkey.pyの中身に問題があるのでしょうか。ご教授いただけると幸いです。

#プログラムの内容(ソースコード)
ファイルの中身は以下のようになっています。

###①app/app.py

Python

1from flask import Flask,render_template,request,session,redirect,url_for 2from models.models import OnegaiContent,User 3from models.database import db_session 4from datetime import datetime 5from . import key 6from hashlib import sha256 7 8app = Flask(__name__) 9app.secret_key = key.SECRET_KEY 10 11 12@app.route("/") 13@app.route("/index") 14def index(): 15 if "user_name" in session: 16 name = session["user_name"] 17 all_onegai = OnegaiContent.query.all() 18 return render_template("index.html",name=name,all_onegai=all_onegai) 19 else: 20 return redirect(url_for("top",status="logout")) 21 22 23@app.route("/add",methods=["post"]) 24def add(): 25 title = request.form["title"] 26 body = request.form["body"] 27 content = OnegaiContent(title,body,datetime.now()) 28 db_session.add(content) 29 db_session.commit() 30 return redirect(url_for("index")) 31 32 33@app.route("/update",methods=["post"]) 34def update(): 35 content = OnegaiContent.query.filter_by(id=request.form["update"]).first() 36 content.title = request.form["title"] 37 content.body = request.form["body"] 38 db_session.commit() 39 return redirect(url_for("index")) 40 41 42@app.route("/delete",methods=["post"]) 43def delete(): 44 id_list = request.form.getlist("delete") 45 for id in id_list: 46 content = OnegaiContent.query.filter_by(id=id).first() 47 db_session.delete(content) 48 db_session.commit() 49 return redirect(url_for("index")) 50 51 52@app.route("/top") 53def top(): 54 status = request.args.get("status") 55 return render_template("top.html",status=status) 56 57 58@app.route("/login",methods=["post"]) 59def login(): 60 user_name = request.form["user_name"] 61 user = User.query.filter_by(user_name=user_name).first() 62 if user: 63 password = request.form["password"] 64 hashed_password = sha256((user_name + password + key.SALT).encode("utf-8")).hexdigest() 65 if user.hashed_password == hashed_password: 66 session["user_name"] = user_name 67 return redirect(url_for("index")) 68 else: 69 return redirect(url_for("top",status="wrong_password")) 70 else: 71 return redirect(url_for("top",status="user_notfound")) 72 73 74@app.route("/newcomer") 75def newcomer(): 76 status = request.args.get("status") 77 return render_template("newcomer.html",status=status) 78 79 80@app.route("/registar",methods=["post"]) 81def registar(): 82 user_name = request.form["user_name"] 83 user = User.query.filter_by(user_name=user_name).first() 84 if user: 85 return redirect(url_for("newcomer",status="exist_user")) 86 else: 87 password = request.form["password"] 88 hashed_password = sha256((user_name + password + key.SALT).encode("utf-8")).hexdigest() 89 user = User(user_name, hashed_password) 90 db_session.add(user) 91 db_session.commit() 92 session["user_name"] = user_name 93 return redirect(url_for("index")) 94 95 96@app.route("/logout") 97def logout(): 98 session.pop("user_name", None) 99 return redirect(url_for("top",status="logout")) 100 101 102if __name__ == "__main__": 103 app.run(debug=True)

###②app/key.py

Python

1SECRET_KEY = "asiwneliwnl3li1nlk" #適当な英数字列 2SALT = "sdfjl234lk4nlksfnlel" #適当な英数字列

###③run.py

Python

1from app.app import app 2 3if __name__ == "__main__": 4 app.run()

###⑤app/templates/index.html

HTML

1<!DOCTYPE html> 2<html> 3 <head> 4 <title>{{name}}</title> 5 </head> 6 <a href="/logout">ログアウトする</a> 7 <body> 8 {% if name == "kiyokiyo" %} 9 <h1>スペシャル{{name}}神社</h1> 10 {% elif name %} 11 <h1>{{name}}神社</h1> 12 {% else %} 13 <h1>ただの神社</h1> 14 {% endif %} 15 16 <img src="/static/images/torii.jpg" alt="鳥居"> 17 18 <form action="/add" method="post"> 19 <input type="text" name="title" placeholder="title"> 20 <input type="text" name="body" placeholder="body"> 21 <input type="submit" value="Add"> 22 </form> 23 24 <form action="/update" method="post" id="update"> 25 <input type="text" name="title" placeholder="title"> 26 <input type="text" name="body" placeholder="body"> 27 <input type="submit" value="Update"> 28 </form> 29 <form action="/delete" method="post" id="delete"> 30 <input type="submit" value="Delete Selected All Onegai"> 31 </form> 32 {% for onegai in all_onegai %} 33 <div> 34 <input type="radio" name="update" value={{onegai.id}}> 35 <input type="checkbox" name="delete" form="delete" value={{onegai.id}}> 36 {{onegai.title}}:{{onegai.body}} ({{onegai.date}}) 37 </div> 38 {% endfor %} 39 </body> 40</html>

###⑥app/templates/top.html

HTML

1<!DOCTYPE html> 2<head> 3 <meta charset="UTF-8"> 4 <title>Login</title> 5</head> 6<body> 7 <h1>ログイン</h1> 8 {% if status == "user_notfound" %} 9 <p>ユーザが見つかりません。新規登録しましょう。</p> 10 {% elif status == "wrong_password" %} 11 <p>パスワードが間違っています。</p> 12 {% elif status == "logout" %} 13 <p>ログアウトが完了しました。</p> 14 {% endif %} 15 <form action="/login" method="post"> 16 <input type="text" name="user_name" placeholder="user name"> 17 <input type="password" name="password" placeholder="password"> 18 <input type="submit" value="Login"> 19 </form> 20 <a href="/newcomer">新規登録はこちら</a> 21</body> 22</html>

###⑦app/templates/newcomer.html

HTML

1<!DOCTYPE html> 2<head> 3 <meta charset="UTF-8"> 4 <title>Registar</title> 5</head> 6<body> 7 <h1>新規登録</h1> 8 <a href="/top">ログイン画面に戻る</a> 9 {% if status == "exist_user" %} 10 <p>そのユーザは既に登録されています。</p> 11 {% endif %} 12 <form action="/registar" method="post"> 13 <input type="text" name="user_name" placeholder="user name"> 14 <input type="password" name="password" placeholder="password"> 15 <input type="submit" value="新規登録"> 16 </form> 17</body> 18</html>

###⑧models/models.py

Python

1from sqlalchemy import Column, Integer, String, Text, DateTime 2from models.database import Base 3from datetime import datetime 4 5 6class OnegaiContent(Base): 7 __tablename__ = 'onegaicontents' 8 id = Column(Integer, primary_key=True) 9 title = Column(String(128), unique=True) 10 body = Column(Text) 11 date = Column(DateTime, default=datetime.now()) 12 13 def __init__(self, title=None, body=None, date=None): 14 self.title = title 15 self.body = body 16 self.date = date 17 18 def __repr__(self): 19 return '<Title %r>' % (self.title) 20 21class User(Base): 22 __tablename__ = 'users' 23 id = Column(Integer, primary_key=True) 24 user_name = Column(String(128), unique=True) 25 hashed_password = Column(String(128)) 26 27 def __init__(self, user_name=None, hashed_password=None): 28 self.user_name = user_name 29 self.hashed_password = hashed_password 30 31 def __repr__(self): 32 return '<Name %r>' % (self.user_name)

###⑨models/database.py

Python

1from sqlalchemy import create_engine 2from sqlalchemy.orm import scoped_session, sessionmaker 3from sqlalchemy.ext.declarative import declarative_base 4import os 5 6databese_file = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'onegai.db') 7engine = create_engine('sqlite:///' + databese_file, convert_unicode=True) 8db_session = scoped_session(sessionmaker(autocommit=False,autoflush=False,bind=engine)) 9Base = declarative_base() 10Base.query = db_session.query_property() 11 12 13def init_db(): 14 import models.models 15 Base.metadata.create_all(bind=engine)

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

これを実行していないのでは?

>>> from models.database import init_db >>> init_db()

もしもinit_db()を実行していないことが原因でInternal Errorが出るなら、Tracebackが表示されているはずです。
Tracebackが表示されるのは、PyCharmの下にあるデバッグ->コンソールですが、見る場所はあっていますか?

投稿2020/12/21 07:16

FiroProchainezo

総合スコア2401

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Ekito

2020/12/21 11:15

実行するのを忘れておりました。実行したところ無事解決しました。 ありがとうございます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問