我正在练习来自https://www.tutorialspoint.com/flask/flask_sqlalchemy.htm的烧瓶盒。 我尝试运行代码并检查http://localshot:5000。他们在前三个步骤中工作正常。 当我尝试填写http://localhost:5000/new上的内容并点击"提交"最后一步按钮,发生错误。 我在Mac上使用python2.7和PyCharm。 THX。
代码如下:
app.py
# -*- coding: utf-8 -*-
from flask import Flask, render_template, request, flash, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'
app.config['SECRET_KEY'] = "random string"
db = SQLAlchemy(app)
class students(db.Model):
id = db.Column('student_id', db.Integer, primary_key = True)
name = db.Column(db.String(100))
city = db.Column(db.String(50))
addr = db.Column(db.String(200))
pin = db.Column(db.String(10))
def __init__(self, name, city, addr, pin):
self.name = name
self.city = city
self.addr = addr
self.pin = pin
#db.create_all()
# filter to the retrieved record set by using the filter attribute.
# For instance, in order to retrieve records with city = ’Hyderabad’
# in students table
# Students.query.filter_by(city = 'Hyderabad').all()
@app.route('/')
def show_all():
return render_template('show_all.html', students = students.query.all())
@app.route('/new', methods = ['GET', 'POST'])
def new():
if request.method == 'POST':
if not request.form['name'] or not request.form['city'] or not request.form['addr']:
flash('Please enter all the fields', 'error')
else:
student = students(request.form['name'], request.form['city'],
request.form['addr'], request.form['pin'])
db.session.add(student)
db.session.commit()
flash('Record was successfully added')
return redirect(url_for('show_all'))
return render_template('new.html')
if __name__ == '__main__':
db.create_all()
app.run(debug = True)
new.html
<!DOCTYPE html>
<html>
<body>
<h3>Students - Flask SQLAlchemy example</h3>
<hr/>
{%- for category, message in get_flashed_messages(with_categories = true) %}
<div class = "alert alert-danger">
{{ message }}
</div>
{%- endfor %}
<form action = "{{ request.path }}" method = "post">
<label for = "name">Name</label><br>
<input type = "text" name = "name" placeholder = "Name" /><br>
<label for = "email">City</label><br>
<input type = "text" name = "city" placeholder = "city" /><br>
<label for = "addr">addr</label><br>
<textarea name = "addr" placeholder = "addr"></textarea><br>
<label for = "PIN">PINCODE</label><br>
<input type = "text" name = "pin" placeholder = "pin" /><br>
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
show_all.html
<!DOCTYPE html>
<html lang = "en">
<head></head>
<body>
<h3>
<a href = "{{ url_for('show_all') }}">Comments - Flask
SQLAlchemy example</a>
</h3>
<hr/>
{%- for message in get_flashed_messages() %}
{{ message }}
{%- endfor %}
<h3>Students (<a href = "{{ url_for('new') }}">Add Student
</a>)</h3>
<table>
<thead>
<tr>
<th>Name</th>
<th>City</th>
<th>Address</th>
<th>Pin</th>
</tr>
</thead>
<tbody>
{% for student in students %}
<tr>
<td>{{ student.name }}</td>
<td>{{ student.city }}</td>
<td>{{ student.addr }}</td>
<td>{{ student.pin }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
以下是错误的详细信息:
类型错误 TypeError: init ()只需1个参数(给定5个)
Traceback (most recent call last)
File "/Applications/anaconda3/envs/SimpleFlaskExample1/lib/python2.7/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/Applications/anaconda3/envs/SimpleFlaskExample1/lib/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/Applications/anaconda3/envs/SimpleFlaskExample1/lib/python2.7/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Applications/anaconda3/envs/SimpleFlaskExample1/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/Applications/anaconda3/envs/SimpleFlaskExample1/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Applications/anaconda3/envs/SimpleFlaskExample1/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Applications/anaconda3/envs/SimpleFlaskExample1/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/Applications/anaconda3/envs/SimpleFlaskExample1/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/chenneyhuang/PycharmProjects/SimpleFlaskExample1/app.py", line 50, in new
request.form['addr'], request.form['pin'])
TypeError: __init__() takes exactly 1 argument (5 given)
答案 0 :(得分:0)
我得到了解决方案#我按照与https://www.tutorialspoint.com/flask/flask_sqlalchemy.htm相同的方式进行操作 但我在这里找到了解决方案
from flask import Flask, request, flash, url_for, redirect, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'
app.config['SECRET_KEY'] = "random string"
db = SQLAlchemy(app)
class students(db.Model):
id = db.Column('student_id', db.Integer, primary_key = True)
name = db.Column(db.String(100))
city = db.Column(db.String(50))
addr = db.Column(db.String(200))
pin = db.Column(db.String(10))
#bro you don't have to pass more than 1 argument
def __init__(self):
self.name = name
self.city = city
self.addr = addr
self.pin = pin
@app.route('/')
def show_all():
return render_template('show_all.html', students = students.query.all() )
@app.route('/new', methods = ['GET', 'POST'])
def new():
if request.method == 'POST':
student=students()
if not request.form['name'] or not request.form['city'] or not request.form['addr']:
flash('Please enter all the fields', 'error')
else:
student.name = request.form['name']
student.city = request.form['city']
student.addr = request.form['addr']
student.pin = request.form['pin']
db.session.add(student)
db.session.commit()
flash('Record was successfully added')
return redirect(url_for('show_all'))
return render_template('new.html')
if __name__ == '__main__':
db.create_all()
app.run(debug = True)
答案 1 :(得分:-1)
Python使用缩进来标记代码块的范围。由于你的__init__
没有缩进,python结束了类的编译并编译了一个名为__init__
的模块级函数。那个类已经有了一个不需要额外参数的init,因为你没有覆盖它,那就是你得到的那个。