美文网首页Pythoner集中营PythonPython Web
用python web框架 bottle 开发网站(三)

用python web框架 bottle 开发网站(三)

作者: firewt | 来源:发表于2018-04-05 17:24 被阅读299次

上一节我们判断登录逻辑的处理方式是把用户名(username)和密码(password)直接硬编码到代码中,接下来,我们使用文本文档作为用户名和密码的保存方式,我们首先实现明文用户名和密码保存。注意:在实际的用户系统中,我们绝对不能明文保存用户密码,这是对用户的不负责。

新建user.py文件,写登录逻辑处理函数

#user.py
import os

if not os.path.exists('./userinfo.txt'):
    open('./userinfo.txt', 'w', encoding = 'utf-8').close()
    
def read_user(username, password):
    userinfo = dict()
    with open('./userinfo.txt', 'r') as fob:
        for line in fob.readlines():
            uname = line.strip().split('=>')[0]
            try:
                pwd = line.strip().split('=>')[1]
                userinfo[uname] = pwd
            except:
                print('\033[1;31;40m  严重:用户信息文件格式错误,系统无法运行 \033[0m')
                exit(1)
    if username not in userinfo:
        return False
    if userinfo[username] == password:
        return True
    return False

总结一下read_user函数的功能就是根据传入的用户名和密码,判断是否和userinfo.txt中的账号密码匹配,如果正确返回True,反之。
在userinfo.txt使用=>标识分割用户名和密码。

#main.py
from bottle import run,route,template,request
from user import read_user

@route("/login", method = 'get')
def index():
    return template('login')

@route('/login', method = 'post')
def index():
    username = request.forms.get('username')
    password = request.forms.get('password')
    if read_user(username, password):
        return '登录成功'
    return '账号密码错误'
    
run(host = 'localhost', port = 80, debug = True, reloader = True)

我们在main.py中导入user Module,然后修改判断逻辑if username == 'admin' and password == 'root'if read_user(username, password)

先手动在userinfo.txt中写入一些测试的账号和密码


userinfo.txt 然后模拟登陆系统, image.png

console中看提交的网络请求


image.png

当然,目前为止还是一个玩具,还有很多要完善的东西。

  • 前端传输用户信息加密
  • 后端加密保存用户密码
  • 更友好的用户登录界面
  • 螺丝帽验证码
  • 注册用户
  • 识别用户登录状态
  • 退出登录
  • 修改密码
  • ………………

接下来我们首先实现完善系统,实现注册,登录,状态保持,退出等功能。

相关文章

网友评论

本文标题:用python web框架 bottle 开发网站(三)

本文链接:https://www.haomeiwen.com/subject/dicdhftx.html