创建一个多用户网站涉及多个方面的技术,包括前端、后端和数据库,以下是一个简单的示例,使用Python的Flask框架和SQLite数据库来创建一个简单的多用户网站。
1. 环境设置
确保你已经安装了以下工具和库:
Python 3.x
Flask
SQLite
你可以使用pip安装Flask:
pip install Flask FlaskSQLAlchemy
2. 项目结构
multiuser_website/ | app.py | models.py | forms.py | templates/ | base.html | index.html | register.html | login.html | profile.html | static/ | css/ | styles.css
3. 配置数据库模型 (models.py
)
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) password = db.Column(db.String(128), nullable=False)
4. 表单处理 (forms.py
)
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import DataRequired, Email, EqualTo 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')]) submit = SubmitField('Sign Up') class LoginForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()]) submit = SubmitField('Login')
5. 应用逻辑 (app.py
)
from flask import Flask, render_template, url_for, flash, redirect, request from models import db, User from forms import RegistrationForm, LoginForm from flask_bcrypt import Bcrypt app = Flask(__name__) app.config['SECRET_KEY'] = 'your_secret_key' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' db.init_app(app) bcrypt = Bcrypt(app) @app.route("/") @app.route("/home") def home(): return render_template('index.html') @app.route("/register", methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf8') user = User(username=form.username.data, 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(username=form.username.data).first() if user and bcrypt.check_password_hash(user.password, form.password.data): flash('Login Successful', 'success') return redirect(url_for('profile', username=user.username)) else: flash('Login Unsuccessful. Please check username and password', 'danger') return render_template('login.html', title='Login', form=form) @app.route("/profile/<username>") def profile(username): user = User.query.filter_by(username=username).first() if user is None: return "User not found" return f"Welcome {user.username}" if __name__ == '__main__': app.run(debug=True)
6. HTML模板 (templates/
)
base.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF8"> <meta name="viewport" content="width=devicewidth, initialscale=1.0"> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}"> </head> <body> {% with messages = get_flashed_messages() %} {% if messages %} <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} {% block content %}{% endblock %} </body> </html>
index.html
{% extends "base.html" %} {% block title %}Home{% endblock %} {% block content %} <h1>Welcome to the MultiUser Website!</h1> <a href="{{ url_for('register') }}">Register</a> / <a href="{{ url_for('login') }}">Login</a> {% endblock %}
register.html
{% extends "base.html" %} {% block title %}Register{% endblock %} {% block content %} <h1>Register</h1> <form method="POST" action="{{ url_for('register') }}"> {{ form.hidden_tag() }} <div> {{ form.username.label }}<br> {{ form.username(size=32) }}<br> {% for error in form.username.errors %} <span style="color: red;">[{{ error }}]</span> {% endfor %} </div> <div> {{ form.email.label }}<br> {{ form.email(size=32) }}<br> {% for error in form.email.errors %} <span style="color: red;">[{{ error }}]</span> {% endfor %} </div> <div> {{ form.password.label }}<br> {{ form.password(size=32) }}<br> {% for error in form.password.errors %} <span style="color: red;">[{{ error }}]</span> {% endfor %} </div> <div> {{ 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 %} </div> <div><input type="submit" value="Register"></div> </form> {% endblock %}
login.html
{% extends "base.html" %} {% block title %}Login{% endblock %} {% block content %} <h1>Login</h1> <form method="POST" action="{{ url_for('login') }}"> {{ form.hidden_tag() }} <div> {{ form.username.label }}<br> {{ form.username(size=32) }}<br> {% for error in form.username.errors %} <span style="color: red;">[{{ error }}]</span> {% endfor %} </div> <div> {{ form.password.label }}<br> {{ form.password(size=32) }}<br> {% for error in form.password.errors %} <span style="color: red;">[{{ error }}]</span> {% endfor %} </div> <div><input type="submit" value="Login"></div> </form> {% endblock %}
profile.html
{% extends "base.html" %} {% block title %}Profile{% endblock %} {% block content %} <h1>Welcome to your profile, {{ username }}!</h1> {% endblock %}
7. CSS样式 (static/css/styles.css
)
body { fontfamily: Arial, sansserif; } /* Add your custom styling here */
8. 初始化数据库和运行应用
在命令行中运行以下命令来创建数据库并加载初始数据:
$ export FLASK_APP=app $ export FLASK_ENV=development $ flask initdb # Creates a migration script file in migrations folder. $ flask dbmigrate m init # Apply the initial migration to create tables in the database. $ flask dbmigrate m create_users_table # Create users table in the DB. $ ./manage.py shell # Starts interactive shell to add initial data manually if needed. $ python app.py # Run the application server.
到此,以上就是小编对于“多用户网站源码”的问题就介绍到这了,希望介绍的几点解答对大家有用,有任何问题和不懂的,欢迎各位朋友在评论区讨论,给我留言。
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/1158711.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复