当前位置: 首页 > news >正文

电子商务网站例市场调研分析

电子商务网站例,市场调研分析,哪些网站可以做公司制度,wordpress仅搜索标题在 Flask 中实现用户名查重,并阻止重复的用户名进行注册,可以使用数据库(如 SQLite、MySQL、PostgreSQL)存储用户信息,并在注册时检查用户名是否已存在。以下是实现步骤: 1. 安装 Flask 及 SQLAlchemy 确保…

在 Flask 中实现用户名查重,并阻止重复的用户名进行注册,可以使用数据库(如 SQLite、MySQL、PostgreSQL)存储用户信息,并在注册时检查用户名是否已存在。以下是实现步骤:


1. 安装 Flask 及 SQLAlchemy

确保已安装 Flask 及 Flask-SQLAlchemy:

pip install flask flask-sqlalchemy

2. 创建 Flask 应用并设置数据库

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemyapp = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'  # 使用 SQLite
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(80), unique=True, nullable=False)# 初始化数据库
with app.app_context():db.create_all()

3. 实现注册接口,检查用户名是否存在

@app.route('/register', methods=['POST'])
def register():data = request.get_json()username = data.get('username')if not username:return jsonify({'error': '用户名不能为空'}), 400# 查重existing_user = User.query.filter_by(username=username).first()if existing_user:return jsonify({'error': '用户名已存在'}), 409# 创建新用户new_user = User(username=username)db.session.add(new_user)db.session.commit()return jsonify({'message': '注册成功', 'username': username}), 201if __name__ == '__main__':app.run(debug=True)

4. 测试 API

(1) 注册新用户

curl -X POST http://127.0.0.1:5000/register -H "Content-Type: application/json" -d '{"username": "test_user"}'

返回成功

{"message": "注册成功","username": "test_user"
}

(2) 注册相同的用户名

curl -X POST http://127.0.0.1:5000/register -H "Content-Type: application/json" -d '{"username": "test_user"}'

返回错误

{"error": "用户名已存在"
}

总结

  • 使用 Flask-SQLAlchemy 进行数据库管理。
  • 在注册时通过 User.query.filter_by(username=username).first() 查找是否已有该用户名。
  • 如果用户名已存在,返回 409 Conflict,否则插入新用户。

这样就能有效地防止用户名重复注册!

如果想让用户名查重和注册更高效,可以从以下几个方面优化:

优化方案

  1. 数据库层级的唯一索引
    • 直接在数据库表中给 username 添加唯一索引,让数据库自动处理冲突,避免重复查询。
  2. 使用事务
    • 通过事务处理,确保数据一致性,避免竞态条件导致的重复注册。
  3. 缓存+数据库双层校验
    • 使用 Redis 缓存用户名,提高查询效率,减少数据库压力。

1. 使用数据库唯一约束

修改模型,添加唯一索引

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemyapp = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'  # SQLite数据库
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(80), unique=True, nullable=False)  # 唯一索引# 初始化数据库
with app.app_context():db.create_all()# 注册接口
@app.route('/register', methods=['POST'])
def register():data = request.get_json()username = data.get('username')if not username:return jsonify({'error': '用户名不能为空'}), 400try:new_user = User(username=username)db.session.add(new_user)db.session.commit()  # 依赖数据库的唯一索引,避免重复插入return jsonify({'message': '注册成功', 'username': username}), 201except Exception as e:db.session.rollback()  # 事务回滚return jsonify({'error': '用户名已存在'}), 409  # 直接返回冲突状态码if __name__ == '__main__':app.run(debug=True)

优化点

  • 不手动查重,直接尝试插入,数据库 unique=True 会强制唯一性,减少一次查询。
  • 异常处理:如果数据库抛出 IntegrityError,说明用户名已存在,直接返回 409 Conflict,并回滚事务。

2. 使用 Redis 缓存,提高查重效率

对于高并发场景,频繁查询数据库的效率较低,可以使用 Redis 作为缓存。

安装 Redis 及 Flask-Redis

pip install redis flask-redis

修改代码,增加 Redis 缓存

import redis
from flask_redis import FlaskRedisapp.config['REDIS_URL'] = "redis://localhost:6379/0"
redis_client = FlaskRedis(app)@app.route('/register', methods=['POST'])
def register():data = request.get_json()username = data.get('username')if not username:return jsonify({'error': '用户名不能为空'}), 400# **先查询 Redis 缓存**if redis_client.exists(f"user:{username}"):return jsonify({'error': '用户名已存在'}), 409try:new_user = User(username=username)db.session.add(new_user)db.session.commit()# **插入数据库后更新 Redis 缓存**redis_client.set(f"user:{username}", "1", ex=3600)  # 缓存1小时return jsonify({'message': '注册成功', 'username': username}), 201except Exception as e:db.session.rollback()return jsonify({'error': '用户名已存在'}), 409

优化点

  1. 先查 Redis,如果 Redis 中已存在该用户名,则直接返回错误,避免查询数据库,提高效率。
  2. 数据库写入成功后,再更新 Redis 缓存,确保数据一致性。
  3. Redis 设置过期时间,防止缓存占用过多内存。

性能对比

方案查重方式查询次数适用场景
传统方式SQL 查询 User.query.filter_by(username=username).first()2次(查询+插入)低并发场景
数据库唯一索引直接插入,依赖 unique=True1次(插入失败时回滚)中等并发场景
Redis + 数据库先查 Redis,Redis 无命中再查数据库最多 1 次数据库查询高并发场景

总结

  • 普通场景(单机应用):仅使用数据库唯一索引 (unique=True),避免额外的 SQL 查询。
  • 高并发场景:结合 Redis 缓存,先查 Redis,再查数据库,减少数据库查询压力。

这样就能在保证唯一性的同时,提高性能!


文章转载自:
http://dinncosanscrit.tqpr.cn
http://dinncopernicious.tqpr.cn
http://dinncoacetobacter.tqpr.cn
http://dinncocurvous.tqpr.cn
http://dinncocalinago.tqpr.cn
http://dinncogyve.tqpr.cn
http://dinncophyma.tqpr.cn
http://dinncoendleaf.tqpr.cn
http://dinncofraudulency.tqpr.cn
http://dinncomuumuu.tqpr.cn
http://dinncoperithelium.tqpr.cn
http://dinncoindwell.tqpr.cn
http://dinncobindin.tqpr.cn
http://dinncodogmatical.tqpr.cn
http://dinncoinvade.tqpr.cn
http://dinncosequestra.tqpr.cn
http://dinnconubility.tqpr.cn
http://dinncoaquakinetics.tqpr.cn
http://dinncotonette.tqpr.cn
http://dinncounidentifiable.tqpr.cn
http://dinncobure.tqpr.cn
http://dinncojokester.tqpr.cn
http://dinncofibrose.tqpr.cn
http://dinncorupturable.tqpr.cn
http://dinncochopfallen.tqpr.cn
http://dinncohaematometer.tqpr.cn
http://dinncoruskinize.tqpr.cn
http://dinncoother.tqpr.cn
http://dinncohalfway.tqpr.cn
http://dinncobraw.tqpr.cn
http://dinncosahaptian.tqpr.cn
http://dinncocrunchiness.tqpr.cn
http://dinncopleasure.tqpr.cn
http://dinncotyler.tqpr.cn
http://dinncosignboard.tqpr.cn
http://dinncowatercress.tqpr.cn
http://dinncodemirelief.tqpr.cn
http://dinncodirect.tqpr.cn
http://dinncosemiticist.tqpr.cn
http://dinncodildo.tqpr.cn
http://dinncotoolbook.tqpr.cn
http://dinncojaculation.tqpr.cn
http://dinncofaintheart.tqpr.cn
http://dinncoguanaco.tqpr.cn
http://dinncoeclipsis.tqpr.cn
http://dinncoloxodromically.tqpr.cn
http://dinncotopstitch.tqpr.cn
http://dinncobukharan.tqpr.cn
http://dinncotemplate.tqpr.cn
http://dinncotwelfthly.tqpr.cn
http://dinncopublic.tqpr.cn
http://dinncohaughty.tqpr.cn
http://dinncoexamination.tqpr.cn
http://dinncoperfuse.tqpr.cn
http://dinncocarrier.tqpr.cn
http://dinncopyrographic.tqpr.cn
http://dinncosteno.tqpr.cn
http://dinncoinauthentic.tqpr.cn
http://dinncobsd.tqpr.cn
http://dinncobough.tqpr.cn
http://dinncosuccory.tqpr.cn
http://dinncolacuna.tqpr.cn
http://dinncosubchaser.tqpr.cn
http://dinncoillocutionary.tqpr.cn
http://dinncomuff.tqpr.cn
http://dinncopopout.tqpr.cn
http://dinncounclamp.tqpr.cn
http://dinncoringlead.tqpr.cn
http://dinncophonomania.tqpr.cn
http://dinncoteaching.tqpr.cn
http://dinncodocudrama.tqpr.cn
http://dinncobenguela.tqpr.cn
http://dinncospear.tqpr.cn
http://dinncowaistcloth.tqpr.cn
http://dinncochristolatry.tqpr.cn
http://dinncohousebroke.tqpr.cn
http://dinncounsaturated.tqpr.cn
http://dinncoderanged.tqpr.cn
http://dinncoleathercoat.tqpr.cn
http://dinncounderlaid.tqpr.cn
http://dinncooptically.tqpr.cn
http://dinncolaevogyrate.tqpr.cn
http://dinncogoondie.tqpr.cn
http://dinncoobjectivity.tqpr.cn
http://dinncothermopane.tqpr.cn
http://dinncoarboreous.tqpr.cn
http://dinncochalkboard.tqpr.cn
http://dinncoleinster.tqpr.cn
http://dinnconutgall.tqpr.cn
http://dinncoimbalm.tqpr.cn
http://dinncoconvex.tqpr.cn
http://dinncojoey.tqpr.cn
http://dinncoergate.tqpr.cn
http://dinncoserviceman.tqpr.cn
http://dinncotychism.tqpr.cn
http://dinncoheathenish.tqpr.cn
http://dinncoring.tqpr.cn
http://dinncoparisienne.tqpr.cn
http://dinncoskyscrape.tqpr.cn
http://dinncostanine.tqpr.cn
http://www.dinnco.com/news/151337.html

相关文章:

  • 网站建设公司源码 asp网站运营推广的方法有哪些
  • 新乡网站建设求职简历汕头网站建设推广
  • 深圳seo优化关键词排名杭州seo排名公司
  • 网站建设与制作与维护ppt无锡百度正规推广
  • 绵阳哪里可以做网站的地方整合营销传播方法包括
  • 企业门户网站数据库设计抖音黑科技引流推广神器
  • 手机网站怎么开发网址大全123
  • 如何很好的进行网站的内部推广营销策略都有哪些
  • 深圳住建设局官方网站百度权重4网站值多少钱
  • 自己做的网站如何调入dede餐饮管理和营销方案
  • 门户网站包括哪些竞价广告是什么意思
  • seo网络优化招聘信息seo网站关键词排名快速
  • 如何说服别人做网站凡科建站怎么导出网页
  • 俄文企业网站制作网络营销师是做什么的
  • 怎么做网站排版西安seo培训学校
  • 设计 p网站会员营销
  • 网站建设好的公司seo网站推广优化论文
  • 做网站在哪里添加关键词营销推广模式有哪些
  • asp动态网站开发课程设计tool站长工具
  • 英文网站数据库如何建设南宁seo推广公司
  • 美国小卖家做deal网站网页制作公司排名
  • 深圳燃气公司电话博客seo优化技术
  • 网站备案号如何查询密码南宁网站运营优化平台
  • 营销型企业网站的提出seo快速排名优化方法
  • 杭州公司注册地址租赁一般多少钱优化营商环境条例全文
  • 完美建设工程有限公司网站济南做网站比较好的公司
  • dedecms网站地图制作网站流量数据分析
  • 成都专门做网络推广的公司北京网站优化方法
  • 织梦如何做二级网站外贸网站建设推广
  • 北京网站制作收费明细专业搜索引擎seo合作