1. 设置环境
确保你已经安装了Python和Flask。你可以使用pip来安装Flask:
pip install Flask
2. 创建项目文件夹
创建一个文件夹来存放你的项目文件。在项目文件夹中,创建以下文件:
-
app.py
:Flask应用程序的主要代码 -
templates
文件夹:用于存放HTML模板 -
static
文件夹:用于存放CSS样式表等静态文件
3. 编写HTML模板
在templates
文件夹中,创建以下HTML文件:
-
register.html
:用于用户注册页面 -
login.html
:用于用户登录页面 -
home.html
:用于用户登录后的主页
4. 编写HTML模板
<!-- register.html -->
<!DOCTYPE html>
<html>
<head>
<title>注册</title>
</head>
<body>
<h2>注册</h2>
<form method="POST" action="/register">
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="注册">
</form>
</body>
</html>
<!-- login.html -->
<!DOCTYPE html>
<html>
<head>
<title>登录</title>
</head>
<body>
<h2>登录</h2>
<form method="POST" action="/login">
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="登录">
</form>
</body>
</html>
<!-- home.html -->
<!DOCTYPE html>
<html>
<head>
<title>主页</title>
</head>
<body>
<h2>欢迎,{{ username }}</h2>
<a href="//www.greatytc.com/logout">登出</a>
</body>
</html>
5. 编写Flask应用程序
在app.py
中,编写以下代码:
from flask import Flask, render_template, request, redirect, url_for, session
app = Flask(__name__)
app.secret_key = 'your_secret_key' # 替换为一个安全的密钥
# 假设这里用一个字典来存储用户信息,实际应用中应该使用数据库
users = {'user1': 'password1', 'user2': 'password2'}
@app.route('/')
def index():
return '首页'
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if username in users:
return '用户名已存在'
users[username] = password
return '注册成功!<a href="/login">点击登录</a>'
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if username in users and users[username] == password:
session['username'] = username
return redirect(url_for('home'))
return '登录失败,请检查用户名和密码'
return render_template('login.html')
@app.route('/home')
def home():
if 'username' in session:
username = session['username']
return render_template('home.html', username=username)
return redirect(url_for('login'))
@app.route('//www.greatytc.com/logout')
def logout():
session.pop('username', None)
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True)
6. 启动应用程序
在终端中,进入项目文件夹,然后运行以下命令启动应用程序:
python app.py