完成登录功能,用session记住用户名
Posted 曹馨文
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了完成登录功能,用session记住用户名相关的知识,希望对你有一定的参考价值。
登录功能完成:
- js:设置return
- html:设置
- form
- input
-
onclick="return fnLogin()"
- py:
- @app.route设置methods
- GET
- POST
- 读取表单数据
- 查询数据库
- 用户名密码对:
- 记住用户名
- 跳转到首页
- 用户名密码不对:
- 提示相应错误。
- 用户名密码对:
session:
- 从`flask`中导入`session`
- 设置`SECRET_KEY`
- 操作字典一样操作`session`:增加用户名`session[‘username‘]=`username
import os DEBUG = True SECRET_KEY = os.urandom(24) DIALECT = ‘mysql‘ DRIVER = ‘mysqldb‘ USERNAME = ‘root‘ PASSWORD = ‘ROOT‘ HOST = ‘127.0.0.1‘ DATABASE = ‘mytest‘ SQLALCHEMY_DATABASE_URI = ‘mysql+pymysql://root:[email protected]:3306/mytest?charset=utf8‘ SQLALCHEMY_TRACK_MODIFICATIONS = False
<!DOCTYPE html> <html lang="en"> <head> {% extends ‘test1.html‘ %} <meta charset="UTF-8"> <title>{% block title %} 登录界面 {% endblock %} </title> {% block head %} <link rel="stylesheet" type="text/css" href="../static/css/denlu.css"> <script src="../static/js/return.js"></script> {% endblock %} </head> <body> {% block body %} <div class="box"> <h1>登录</h1> <form action="{{ url_for(‘deng‘) }}" method="post"> <div class="input_box"> <input id="name" type="text" placeholder="请输入用户名" name="username"> </div> <div class="input_box"> <input id="pass" type="password" placeholder="请输入密码" name="password"> </div> <div id="error_box"><br> </div> <div class="input_box"> <button onclick="fnLogin()">登录</button> </div> </form> </div> {% endblock %} </body> </html>
function fnLogin() { var oUname = document.getElementById("name"); var oUpass = document.getElementById("pass"); var oError = document.getElementById("error_box"); var isError = true; oError.innerHTML = ‘<br>‘ // if (oUname.value.length > 20 || oUname.value.length < 6) { oError.innerHTML = "name:6-20位"; isError = false; return isError; } else if ((oUname.value.charCodeAt(0) >= 48) && (oUname.value.charCodeAt(0) <= 57)) { oError.innerHTML = "first letter."; isError = false; return isError; } else for (var i = 0; i < oUname.value.length; i++) { if ((oUname.value.charCodeAt(i) < 48) || (oUname.value.charCodeAt(i) > 57) && (oUname.value.charCodeAt(0) < 97) || (oUname.value.charCodeAt(0) > 122)) { oError.innerHTML = "only letter or number"; isError = false; return isError; } } if (oUpass.value.length > 20 || oUpass.value.length < 6) { oError.innerHTML = "password:6-20"; isError = false; return isError; } return isError; window.alert("登录成功!") }
以上是关于完成登录功能,用session记住用户名的主要内容,如果未能解决你的问题,请参考以下文章