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

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

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

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

integer

integerは、一般的に整数を表します。プラスやマイナス、ゼロもなりうる全ての数です。(例 : -2, -1, 0, 1, 2...)

POST

POSTはHTTPプロトコルのリクエストメソッドです。ファイルをアップロードしたときや入力フォームが送信されたときなど、クライアントがデータをサーバに送る際に利用されます。

Python

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

Q&A

解決済

2回答

627閲覧

ポストメソッドで取得してきた値をInt型に直す方法が知りたい

asasika_R

総合スコア25

Flask

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

integer

integerは、一般的に整数を表します。プラスやマイナス、ゼロもなりうる全ての数です。(例 : -2, -1, 0, 1, 2...)

POST

POSTはHTTPプロトコルのリクエストメソッドです。ファイルをアップロードしたときや入力フォームが送信されたときなど、クライアントがデータをサーバに送る際に利用されます。

Python

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

0グッド

0クリップ

投稿2022/06/28 08:46

編集2022/06/28 08:49

Pythonで家計簿アプリを作っているのですが、ポストメソッドで取得した値(数字)がInt型に直すことができずに困っています。

具体的には(下にpythonと一部のhtmlのコードを載せています)

python

1 used_money = request.form.get('used_money') 2 used_money = int(used_money) 3 check_category.remaining_budget -=used_money 4

この部分なんですが、
used_moneyをInt()で囲むと
invalid literal for int() with base 10:
とエラーが出てきました。これはIntに直せないものを直そうとしているので出るエラーだと分かったのですが、値自体はターミナルにprintしてみたところ数字がでてきており、なぜ直らないのか分かりません。

そこでこの値をInt型に直す方法と、今のままでなぜIntに直らないのか、の二点教えていただきたいです。

python

1 2from flask import Flask 3from flask import render_template,redirect,request 4from flask_sqlalchemy import SQLAlchemy 5from flask_migrate import Migrate 6import datetime 7 8app = Flask(__name__) 9app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' 10app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False 11db = SQLAlchemy(app) 12migrate = Migrate(app,db) 13 14class Category(db.Model): 15 category_name = db.Column(db.String,db.ForeignKey('detail.id'),primary_key=True) 16 budget = db.Column(db.Integer,nullable=False) 17 remaining_budget = db.Column(db.Integer,nullable=False) 18 month = db.Column(db.Integer,nullable=False) 19 20class Detail(db.Model): 21 id = db.Column(db.Integer,primary_key=True) 22 category_name = db.relationship('Category',backref='detail',lazy=True) 23 used_money = db.Column(db.Integer,nullable=False) 24 purchased_item = db.Column(db.String,nullable=False) 25 month = db.Column(db.Integer,nullable=False) 26 day = db.Column(db.Integer,nullable=False) 27 28today = datetime.date.today() 29missing_entry = 0 30duplicate_error = 0 31 32@app.route('/',methods=['GET','POST']) 33def index(): 34 if request.method == 'GET': 35 display_categorys = Category.query.filter(Category.month == 6).all() 36 display_details = Detail.query.filter(Detail.month == 6).all() 37 check_count = Detail.query.filter(Detail.purchased_item.like('%eh%')).count() 38 month = today.month 39 if check_count == 0: 40 return render_template('index.html',categorys=display_categorys,details=display_details,month=month,count=0) 41 else: 42 return render_template('index.html',categorys=display_categorys,details=display_details,month=month) 43 else: 44 month = request.get('month') 45 try: 46 search_categorys = Category.query.fileter_by(month = month).all() 47 search_details = Detail.query.filter_by(month = month).all() 48 return render_template('index.html',categorys=search_categorys,details=search_details,month=month) 49 except: 50 return render_template('index.html') 51 52@app.route('/create_category' ,methods=['GET','POST']) 53def create_category(): 54 if request.method == 'GET': 55 return render_template('create_category.html') 56 else: 57 category_name = request.form.get('category_name') 58 budget = request.form.get('budget') 59 category_month = today.month 60 add_category = Category(category_name=category_name,budget=budget,remaining_budget=budget,month=category_month) 61 db.session.add(add_category) 62 try: 63 db.session.commit() 64 return redirect('/') 65 except: 66 if category_name == '' or budget == '': 67 return render_template('create_category.html' ,missing_entry = 1) 68 else: 69 return render_template('create_category.html',duplicate_error = 1) 70 71@app.route('/<string:category_name>/create_detail/' ,methods=['GET','POST']) 72def create_detail(category_name): 73 check_category = Category.query.filter_by(category_name=category_name).first() 74 if request.method == 'GET': 75 return render_template('create_detail.html',category=check_category) 76 else: 77 purchased_item = request.form.get('purchased_item') 78 used_money = request.form.get('used_money') 79 check_category.remaining_budget -=used_money 80 detail_day = today.day 81 detail_month = today.month 82 try: 83 add_detail = Detail(purchased_item=purchased_item,used_money=used_money,day=detail_day,month=detail_month) 84 db.session.add(add_detail) 85 db.session.commit() 86 return redirect('/') 87 except: 88 return render_template('create_detail.html',missing_entry = 1) 89

html

1{% extends 'base.html' %} 2{% block body %} 3<h1 class="title">{{month}}月の家計簿</h1> 4<h1 class="detail_second_title">帳簿</h1> 5<h2 class="detail_category_name">カテゴリ:{{category.category_name}}</h2> 6{% if error == 1 %} 7<h3>記入漏れ、または記入エラーがあります</h3> 8{% endif %} 9<article class="detail_form"> 10 <form action="" method="POST"> 11 <label for="purchased_item" class="detail_label_purchased_money"><h3>買ったもの</h3></label> 12 <input type="text" name="purchased_item" class="detail_input_purchased_item"> 13 <label for="used_money"><h3 class="detail_label_used_money">金額</h3></label> 14 <input type="number" name="used_money" class="detail_input_used_money"> 15 <input type="submit" value="確定" class="detail_input_submit"> 16 </form> 17</article> 18{% endblock %}

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

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

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

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

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

can110

2022/06/28 09:17

printした結果をそのまま文字として提示ください。 そのさいできれば「print(f'[{used_money}]')」のように前後を[]なりで囲み余計な文字など確認しやすくするとよいです。
quickquip

2022/06/28 09:25

invalid literal for int() with base 10: の右に何も出ていませんか。 の左は ValueError: が出ていませんか。 https://teratail.com/help/question-tips#questionTips34 > 表示されたエラーメッセージをそのままコピー&ペーストしましょう。自分でタイプしなおしたり、自分で解釈・要約しようとしてはいけません。
asasika_R

2022/06/28 10:25

CAN110さん、コメントありがとうございます。 quickquipさん、アドバイスありがとうございます。
guest

回答2

0

質問文に記載されているコードを実行してみたところ、実行できませんでした。

質問には、現象が再現する最小のコードを提示ください。
そもそも、下の長いコードの中にused_money = int(used_money)が見当たりません。

また、エラーを記載する場合は、省略すること無くそのままの文章を全文記載してください。
Pythonの場合はTracebackというところからです。

再現に使ったコード

以下で確認してみました。

python:app.py

1from flask import Flask, render_template, request 2 3app = Flask(__name__) 4 5 6@app.route('/', methods=['GET', 'POST']) 7def index(): 8 if request.method == 'GET': 9 return render_template('index.html') 10 else: 11 tmp = request.form.get('used_money', None) 12 aaa = int(tmp) 13 if tmp is None: 14 return render_template('index.html', error=1) 15 # if tmp == '': 16 # return render_template('index.html', error=1) 17 if tmp.isdigit(): 18 used_money = int(tmp) 19 return render_template('index.html', used_money=used_money) 20 else: 21 return render_template('index.html') 22

html:index.html

1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6</head> 7<body> 8{% if error==1 %} 9 <span style="color: #ff0000;">error</span> 10{% endif %} 11{% if used_money %} 12 入力された数値は: {{ used_money }} 13{% endif %} 14 <article class="detail_form"> 15 <form action="" method="POST"> 16 <label for="purchased_item" class="detail_label_purchased_money"><h3>買ったもの</h3></label> 17 <input type="text" name="purchased_item" class="detail_input_purchased_item"> 18 <label for="used_money"><h3 class="detail_label_used_money">金額</h3></label> 19 <input type="number" name="used_money" class="detail_input_used_money"> 20 <input type="submit" value="確定" class="detail_input_submit"> 21 </form> 22 </article> 23</body> 24</html>

再現方法

質問文にあるエラーメッセージ(invalid literal for int() with base 10:)と完全一致するものは再現出来ませんでしたが、以下を出力はできました。
ValueError: invalid literal for int() with base 10: ''

フォームに何も入力せず「確定」を押すと再現可能です。

回答

そこでこの値をInt型に直す方法と、
今のままでなぜIntに直らないのか、の二点教えていただきたいです。

変換できる値でないと変換出来ません。
asasika_Rさんのコードでは、来たものを何もかも受け入れて、10進数でない値「''」を変換しようとしているためエラーになっているものと推測できます。

以下のように、意図せぬ値が来た場合、変換を行わないなどの処理を追加してください。(以下で全てカバーできているかはわかりませんので、確認ください。)

python

1@app.route('/', methods=['GET', 'POST']) 2def index(): 3 if request.method == 'GET': 4 return render_template('index.html') 5 else: 6 tmp = request.form.get('used_money', None) 7 if tmp is None: 8 return render_template('index.html', error=1) 9 if tmp == '': 10 return render_template('index.html', error=1) 11 if tmp.isdigit(): 12 used_money = int(tmp) 13 return render_template('index.html', used_money=used_money) 14 else: 15 return render_template('index.html') 16

request.form.getの第2引数は、取得使用としているキーが存在しない場合に取得できる値です。(used_moneyが無い場合、エラーにならずNoneが取得できます)
Noneの場合はエラーなので、エラーで終了させます。
Noneで無い場合は、取得されている値が''で無いかを確認しています。
''の場合、数字で無いのでエラーで終了させます。

この時点でtmpに値が入っていますが、数字では無い可能性を考慮し、数字かどうかを判定しています。

この判定が終わった時点で、数字で構成された文字列であるはずなので、intを使って変換し、templateに渡して表示する、という感じです。

デバッグを全くできていない印象があるのでPyCharmなどのIDE(デバッガ)の使用をお勧めします。

投稿2022/06/28 10:11

FiroProchainezo

総合スコア2401

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

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

asasika_R

2022/06/28 10:27

丁寧なご回答ありがとうございます。意図せぬ値が来た時の処理参考になりました。理解してコードに取り込みたいと思います。
guest

0

自己解決

質問の修正依頼でエラー文をもう一度出そうしたところ、正常に動きました。動いたコードの下に載せておきます。

python

1 2@app.route('/<string:category_name>/create_detail/' ,methods=['GET','POST']) 3def create_detail(category_name): 4 check_category = Category.query.filter_by(category_name=category_name).first() 5 if request.method == 'GET': 6 return render_template('create_detail.html',category=check_category) 7 else: 8 purchased_item = request.form.get('purchased_item') 9 used_money = request.form.get('used_money') 10 check_category.budget -= int(used_money) 11 detail_day = today.day 12 detail_month = today.month 13 try: 14 add_detail = Detail(purchased_item=purchased_item,used_money=used_money,day=detail_day,month=detail_month) 15 db.session.add(add_detail) 16 db.session.commit() 17 return redirect('/') 18 except: 19 return render_template('create_detail.html',missing_entry = 1) 20

投稿2022/06/28 10:25

asasika_R

総合スコア25

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.47%

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

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

質問する

関連した質問