大致流程如下:
- 设计数据库结构:包括用户表和会话表,用户表记录用户的账号信息和登录状态,会话表用来维护用户的登录状态;
- 编写Python后端代码:包括注册、登录、验证、登出等接口实现。具体实现过程请参考下面的示例说明;
- 编写前端页面:通过HTML、CSS、JavaScript等技术实现一个简单的注册、登录页面。
下面是两个示例:
- 示例一:实现注册接口
首先设计用户表结构,包括以下字段: id(primary key), username, password
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(100) NOT NULL
);
编写Python接口实现注册功能:
from flask import Flask, jsonify, request
from werkzeug.security import generate_password_hash
from flask_sqlalchemy import SQLAlchemy
import random
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@localhost:5432/test'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
password = db.Column(db.String(200), nullable=False)
def __repr__(self):
return '<User %r>' % self.username
@app.route('/register', methods=['POST'])
def register():
data = request.get_json()
username = data['username']
password = data['password']
check_user = User.query.filter_by(username=username).first()
if check_user:
return jsonify({'message': 'User already exists'})
new_user = User(username=username, password=generate_password_hash(password, method='sha256'))
db.session.add(new_user)
db.session.commit()
return jsonify({'message': 'User created successfully'})
上面的代码实现了/register接口,用于处理POST请求,接收username和password两个参数,判断用户是否存在,如果不存在则添加到数据库中,并返回成功信息。
- 示例二:实现登录、验证和登出
首先设计会话表结构,包括以下字段: id(primary key), user_id, session_id
CREATE TABLE sessions (
id SERIAL PRIMARY KEY,
user_id INTEGER,
session_id VARCHAR(50) UNIQUE NOT NULL
);
ALTER TABLE sessions
ADD CONSTRAINT fk_user_sessions
FOREIGN KEY (user_id)
REFERENCES users (id);
编写Python接口实现登录接口,其中在验证密码是否正确时需要使用flask-bcrypt库进行密码解密:
from flask import Flask, jsonify, request, session
from werkzeug.security import check_password_hash
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, timedelta
import uuid
import bcrypt
app = Flask(__name__)
app.secret_key = 'my_secret_key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@localhost:5432/test'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
password = db.Column(db.String(200), nullable=False)
def __repr__(self):
return '<User %r>' % self.username
class Session(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
session_id = db.Column(db.String(50), unique=True, nullable=False)
def __repr__(self):
return '<Session %r>' % self.session_id
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data['username']
password = data['password']
user = User.query.filter_by(username=username).first()
if not user:
return jsonify({'message': 'Invalid username'})
if not check_password_hash(user.password, password):
return jsonify({'message': 'Invalid password'})
session_id = str(uuid.uuid4())
db.session.add(Session(user_id=user.id, session_id=session_id))
db.session.commit()
session['session_id'] = session_id
return jsonify({'message': 'Logged in successfully'})
@app.route('/logout', methods=['POST'])
def logout():
session_id = session['session_id']
db.session.query(Session).filter_by(session_id=session_id).delete()
db.session.commit()
return jsonify({'message': 'Logged out successfully'})
@app.route('/user', methods=['GET'])
def get_user():
session_id = session['session_id']
session = Session.query.filter_by(session_id=session_id).first()
if not session:
return jsonify({'message': 'Not logged in'})
user = User.query.get(session.user_id)
return jsonify({'user': user.username})
上面的代码实现了登录、登出和验证功能。登录时,根据输入的username和password从数据库中获取user对象,如果用户名或者密码不对则返回错误信息,如果验证通过,则生成一个随机的session_id,并将其存储到数据库中和session中。验证接口获取session_id,并从数据库中查询session对象,如果不存在或者查询失败,则认为该用户没有登录,否则从用户对象中获取用户名并返回给客户端。登出时根据session_id从数据库中查询并删除session对象,同时从session中删除session_id。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python实现注册、登录小程序功能 - Python技术站