【发布时间】:2021-08-18 00:35:15
【问题描述】:
我正在学习 Flask,我使用这个框架开始了我的第一个项目。目前我想将用户输入保存到数据库中,但我得到了一个
TypeError:“bookingPage”的视图函数没有返回有效响应。
该函数要么返回 None,要么在没有 return 语句的情况下结束。我检查了我的函数,如果是 GET 请求,return 语句必须返回预订页面,如果是 POST 请求,则必须重定向到主页。
我还在这里查看了有关此类错误的其他帖子,但有诸如“您需要添加 return 语句”之类的答案。在我的情况下,返回语句存在
这是我的函数的代码:
@app.route('/booking', methods=['POST', 'GET'])
def bookingPage():
if request.method == 'POST':
firstname = request.form['firstname']
lastname = request.form['lastname']
phone = request.form['phone']
email = request.form['email']
birthdate = request.form['birthdate']
booking_date = request.form['booking_date']
booking_time = request.form['booking_time']
guests_nr = request.form['guests_nr']
notes = request.form['notes']
reservation = Booking(CustomerFname=firstname, CustomerLname=lastname, CustomerPhone=phone, CustomerEmail=email,
CustomerBirthdate=birthdate, ReservationDate=booking_date, ReservationTime=booking_time,
NumberOfGuests=guests_nr, CustomerNotes=notes)
try:
db.session.add(reservation)
db.session.commit()
return redirect('/')
except:
return "An error has been occurred. Please, try again later"
else:
return render_template('booking.html')
这里也是html的代码
<div class="booking-container">
<form method="post">
<input type="text" name="firstname" id="firstname" class="form-control" placeholder="First Name" required>
<input type="text" name="lastname" id="lastname" class="form-control" placeholder="Last Name" required>
<input type="text" name="email" id="email" class="form-control" placeholder="Email" required>
<input type="text" name="phone" id="phone" class="form-control" placeholder="Phone Number" required>
<input type="text" name="birthdate" id="birthdate" class="form-control" placeholder="Date of Birth" required>
<input type="text" name="booking_date" id="booking_date" class="form-control" placeholder="Reservation Date" required>
<input type="text" name="booking_time" id="booking_time" class="form-control" placeholder="Reservation Time" required>
<input type="text" name="guests_nr" id="guests_nr" class="form-control" placeholder="Number of Guests" required>
<textarea name="notes" id="notes" class="form-control" placeholder="Notes"></textarea>
<input type="submit" class="btn-submit" value="Sent">
</form>
</div>
【问题讨论】:
-
设置几个
print以确保您到达return语句,即使发生任何异常都应该在服务器控制台中看到 -
是的,我试过 'try: db.session.add(reservation) db.session.commit() print('try') return redirect('/') except: print('errr' ) return "发生错误。请稍后再试" else: print('final') return render_template('booking.html')' 并显示来自异常的“errr”打印和打印“final” " 来自返回语句
-
stackoverflow.com/questions/11868143/… 是关于方法视图,但第一个答案也适用于您的情况。将重定向更改为
return redirect('/', code=303)。 -
谢谢。我尝试添加code=303,但错误并没有消失:(
标签: python python-3.x flask flask-sqlalchemy typeerror