我最近尽可能完整地提交了CS50的最终项目。我花了近三天的时间来调试它,但无法使程序正常工作。现在,我想让它工作以达到我个人的满意程度。
我的问题是,该程序是一个Python / Flask网站,具有基于SQLite的成员资格数据库和blog / nes函数,它们在项目的网站端可以完美运行,但数据库端只能以有限的容量运行。
该数据库是基于我的python代码中的参数建立的,但是我无法通过命令行或Web表单填充该数据库。我可以使用SQLite GUI工具填充数据库,所以我知道数据库已正确建立。
当我尝试通过Web界面放入数据时,在命令行上通过http监视没有出现任何错误,并且没有数据发布到数据库中。
我丢失了一些东西,距离我太近了,无法看到正在发生的事情。
帮助!
以下是整个包装的相关部分:
初始化 .py:
# Imports
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
app = Flask(__name__)
# Configyuration files
# Secret key
app.config['SECRET_KEY'] = '******************************'
# Database configuration
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db/site.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # Stops overhead warning
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'join'
login_manager.login_message_category = 'info'
from application import routes
Forms.py:
# Imports
import os
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from flask_login import current_user
from wtforms import StringField, PasswordField, SubmitField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from application.models import User, Posts, News
# For to register users
class RegistrationForm(FlaskForm):
username = StringField('Username', validators = [DataRequired()])
email = StringField('Email', validators = [DataRequired(), Email()])
password = PasswordField('Password', validators = [DataRequired()])
confirm_password = PasswordField('Confirm password', validators = [DataRequired(), EqualTo('password')])
firstname = StringField('First name', validators = [DataRequired()])
lastname = StringField('Last name', validators = [DataRequired()])
street = StringField('Address 1', validators = [DataRequired()])
address = StringField('Address 2')
city = StringField('City', validators = [DataRequired()])
state = StringField('State', validators = [DataRequired()])
zipcode = StringField('Zip Code', validators = [DataRequired(), Length(min=5, max=10)])
remember = BooleanField('Remember Me')
terms = BooleanField('Terms & Conditions')
citizen = BooleanField('Citizen')
submit = SubmitField('Submit')
def validate_username(self, username):
user = User.query.filter_by(username = username.data).first()
if user:
raise ValidationError('We are sorry, that user name is already being used. Please choose another')
def validate_email(self, email):
user = User.query.filter_by(email = email.data).first()
if user:
raise ValidationError('We are sorry, that email address is already being used. Please choose another')
models.py
# Imports
import os
from datetime import datetime
from application import db, login_manager
from flask_login import UserMixin
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
# Database
# Members database
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(20), unique = True, nullable = False)
email = db.Column(db.String(120), unique = True, nullable = False)
password = db.Column(db.String(60), nullable = False)
image_file = db.Column(db.String(20), nullable = False, default = 'default.jpeg')
firstname = db.Column(db.String(20), nullable = False)
lastname = db.Column(db.String(20), nullable = False)
street = db.Column(db.String(20), nullable = False)
address = db.Column(db.String(20))
city = db.Column(db.String(20), nullable = False)
state = db.Column(db.String(2), nullable = False)
zipcode = db.Column(db.String(9), nullable = False)
donates = db.Column(db.String())
posts = db.relationship('Posts', backref = 'author', lazy = True)
news = db.relationship('News', backref = 'contributor', lazy = True)
def __repr__(self):
return f"User('{self.username}', '{self.email}', '{self.firstname}', '{self.lastname}', '{self.street}', '{self.address}', '{self.city}', '{self.state}', '{self.zipcode}',)"
routes.py:
# Membership, login/out, and account information
# Join the SBoR Project
@app.route('/join', methods = ['GET', 'POST'])
def join():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = RegistrationForm()
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
user = User(username = form.username.data, email = form.email.data, password = hashed_password,
firstname = form.firstname.data, lastname = form.firstname.data,
street = form.street.data, address = form.address.data,
city = form.city.data, state = form.state.data, zipcode = form.zipcode.data)
db.session.add(user)
db.session.commit()
flash(f'Thank you {form.firstname.data}, your account has been successfully created and you may now login.', 'success')
return redirect(url_for('signin'))
return render_template('join.html', title = 'Join', form = form)
# Signin to the SBoR Project
@app.route('/signin', methods = ['GET', 'POST'])
def signin():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email = form.email.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user, remember = form.remember.data)
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('index'))
else:
flash(f'Login was unsuccessful, please check your email and password', 'danger')
return render_template('signin.html', title = 'Sign in', form = form)
# Logout from the SBoR Project
@app.route('/signout')
def signout():
logout_user()
return redirect(url_for('index'))
这是我在Powershell中监视HTTP流量时得到的:
* Serving Flask app "application" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [12/Dec/2018 17:23:13] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [12/Dec/2018 17:23:13] "GET /static/styles.css HTTP/1.1" 200 -
127.0.0.1 - - [12/Dec/2018 17:23:21] "GET /join HTTP/1.1" 200 -
127.0.0.1 - - [12/Dec/2018 17:23:21] "GET /static/favicon.ico HTTP/1.1" 200 -
127.0.0.1 - - [12/Dec/2018 17:24:03] "POST /join HTTP/1.1" 200 -
127.0.0.1 - - [12/Dec/2018 17:24:03] "GET /static/favicon.ico HTTP/1.1" 200 -
当我尝试在Python命令行中填充数据库时,我得到了:
site.query.all()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'site' is not defined
db.session.add(username='username', firstname='First', lastname='Last', email='person@mail.com')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'db' is not defined
这是软件包树:
application
├───db
│ └─── site.db
├───static
│ ├─── downloads
│ └─── profile_pics
├───templates
│ ├─── blog
│ ├─── constitution
│ ├─── errors
│ ├─── federalist
│ ├─── includes
│ ├─── news
│ ├─── policies
│ ├─── proposals
│ ├─── sbr
│ ├─── __init__.py
│ ├─── routes.py
│ ├─── forms.py
│ ├─── models.py
│ └───
└─── run.py
任何帮助将不胜感激