如何有效管理App代码与数据库以提升开发效率?
我可以为您提供一个基本的应用程序代码和数据库设计,为了便于说明,我将使用Python和Flask作为后端框架,并使用SQLite作为数据库,这个示例将包括一个简单的用户注册和登录系统。
项目结构
myapp/ │ ├── app.py ├── models.py ├── templates/ │ └── login.html │ └── register.html ├── static/ │ └── styles.css └── requirements.txt
requirements.txt
我们需要安装一些依赖项:
Flask==2.0.1 Flask-WTF==0.14.3 email-validator==1.1.1
app.py
这是主应用程序文件:
from flask import Flask, render_template, redirect, url_for, request, flash from flask_sqlalchemy import SQLAlchemy from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import DataRequired, Email, Length, EqualTo, ValidationError import os app = Flask(__name__) app.config['SECRET_KEY'] = 'your_secret_key' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' db = SQLAlchemy(app) Database models class User(db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(120), unique=True, nullable=False) password = db.Column(db.String(60), nullable=False) Form classes class RegistrationForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email()]) password = PasswordField('Password', validators=[DataRequired(), Length(min=8)]) confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')]) submit = SubmitField('Sign Up') def validate_email(self, email): user = User.query.filter_by(email=email.data).first() if user: raise ValidationError('Email address already exists.') class LoginForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email()]) password = PasswordField('Password', validators=[DataRequired()]) submit = SubmitField('Log In') @app.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): hashed_password = generate_password_hash(form.password.data).decode('utf-8') user = User(email=form.email.data, password=hashed_password) db.session.add(user) db.session.commit() flash('Your account has been created! You are now able to log in', 'success') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form) @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user and check_password_hash(user.password, form.password.data): flash('Login successful!', 'success') return redirect(url_for('home')) else: flash('Login Unsuccessful. Please check email and password', 'danger') return render_template('login.html', title='Login', form=form) @app.route('/') def home(): return "Welcome to the Home Page!" if __name__ == '__main__': db.create_all() app.run(debug=True)
models.py
这个文件中定义了数据模型,但在这个例子中,我们直接在app.py
中定义了User
模型。
5. templates/login.html
这是登录页面的模板:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}"> </head> <body> <div class="container"> <h2>{{ title }}</h2> <form method="POST"> {{ form.hidden_tag() }} <p> {{ form.email.label }}<br> {{ form.email(size=32) }}<br> {% for error in form.email.errors %} <span style="color: red;">{{ error }}</span> {% endfor %} </p> <p> {{ form.password.label }}<br> {{ form.password(size=32) }}<br> {% for error in form.password.errors %} <span style="color: red;">{{ error }}</span> {% endfor %} </p> <p>{{ form.submit() }}</p> </form> </div> </body> </html>
6. templates/register.html
这是注册页面的模板:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}"> </head> <body> <div class="container"> <h2>{{ title }}</h2> <form method="POST"> {{ form.hidden_tag() }} <p> {{ form.email.label }}<br> {{ form.email(size=32) }}<br> {% for error in form.email.errors %} <span style="color: red;">{{ error }}</span> {% endfor %} </p> <p> {{ form.password.label }}<br> {{ form.password(size=32) }}<br> {% for error in form.password.errors %} <span style="color: red;">{{ error }}</span> {% endfor %} </p> <p> {{ form.confirm_password.label }}<br> {{ form.confirm_password(size=32) }}<br> {% for error in form.confirm_password.errors %} <span style="color: red;">{{ error }}</span> {% endfor %} </p> <p>{{ form.submit() }}</p> </form> </div> </body> </html>
static/styles.css
这是一个简单的CSS文件,用于美化页面:
body { background-color: #f8f9fa; font-family: Arial, sans-serif; } .container { max-width: 600px; margin: 50px auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px; background-color: #fff; } h2 { text-align: center; color: #333; } form p { margin-bottom: 15px; } input[type="text"], input[type="password"] { width: 100%; padding: 10px; margin-top: 5px; border: 1px solid #ccc; border-radius: 4px; } input[type="submit"] { background-color: #4CAF50; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; } input[type="submit"]:hover { background-color: #45a049; }
是一个基本的Flask应用程序,它实现了用户注册和登录功能,并且使用了SQLite数据库来存储用户信息,您可以根据需要进一步扩展和修改此示例。
以上内容就是解答有关“app代码和数据库”的详细内容了,我相信这篇文章可以为您解决一些疑惑,有任何问题欢迎留言反馈,谢谢阅读。
-- 展开阅读全文 --
暂无评论,1人围观