flask认证模块

flask认证模块

这两天特别忙,一直没更新博客,实验室的任务也一直没做,感觉还是挺抱歉的,昨天也总算是把认证模块写完并测试了。终于可以好好的准备考试了。

app.py

from flask import Flask,render_template,session,redirect,url_for,flash,request,make_response,jsonify,escape
from flask_sqlalchemy import SQLAlchemy
import configparser
import mysql.connector
from flask_login import LoginManager,UserMixin,login_required,login_user,logout_user
import login
import os
import flask_login
from wtforms import StringField,SubmitField,PasswordField,Form
from wtforms.validators import  Required,DataRequired
from flask_wtf import FlaskForm
 

class Login_Form(FlaskForm):
    username=StringField('username',validators=[DataRequired()])
    password=PasswordField('password',validators=[DataRequired()])
    submit=SubmitField('Login')
    def mcc_validate(self):
        if self.username and self.password:
            return True
        else:
            return False
        

cf=configparser.ConfigParser()
cf.read('conf.ini文件地址',encoding='utf-8')                      	
NAME=cf.get('db','NAME')
PASSWORD = cf.get('db','PASSWORD')
IPADDR = cf.get('db','IPADDR')
DATABASE = cf.get('db','DATABASE')

app=Flask(__name__)

app.config['SECRET_KEY'] = os.urandom(24)
app.config['SQLALCHEMY_DATABASE_URI']='mysql+mysqlconnector://%s:%s@%s/%s' %(NAME,PASSWORD,IPADDR,DATABASE)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

db=SQLAlchemy(app)


class User(UserMixin,db.Model):
    __tablename__ = 'user'
    __table_args__ = {'mysql_charset': 'utf8'}
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(30),unique=True)
    password = db.Column(db.String(30),unique=True)
    email = db.Column(db.String(30),unique=True)
    def __init__(self,name,password,email):
        self.name = name
        self.password = password
        self.email = email
    


def db_init():
    db.create_all()
    app.logger.info("database is init success")
    
db_init()


def auth():
    form=Login_Form()
    if form.mcc_validate():
        user=User.query.filter_by(name=form.username.data).first()
        if user is not  None and form.password.data==user.password:
            flash('登录成功')
            return  True
        else:
            flash('用户或密码错误')
            return False
    else:
        return False

@app.route('/test')
def test():
    return render_template('ForWindowsIndex.html')

@app.route('/login',methods=('POST','GET'))
def login():
    app.logger.info("you have gone into the login html")
    form=Login_Form()
    if form.mcc_validate():
        if request.method=='POST':
            username=form.username.data
            password=form.password.data
            app.logger.info("the form user is ",username,'the form password is ',password)
            user=User.query.filter_by(name=username).first()
            app.logger.info(' the database name is ',user.name,'the database password is ',user.password)
            app.logger.info("you have passed the validate")
            user=User.query.filter_by(name=username).first()
            if user is not  None and password==user.password:
                session["username"]=username
                session["password"]=password           
                return render_template('ForWindowsIndex.html')               
            else:
                app.logger.info("you are  the not validate user")
                return render_template('login.html')
        else:
            app.logger.info("validate fail")
            return render_template('login.html')
           
    else:
        return render_template('login.html')




@app.route('/', methods=['GET', 'POST'])
def index():
    app.logger.info("index page")
    app.logger.info("cookie name %s" % request.cookies.get('username'))
    if 'username' in session:
        app.logger.info("login user is %s" % flask_login.current_user)
        app.logger.info('Logged in as %s' % escape(session['username']))
        url=url_for('templates','ForWindowsIndex.html')
        return render_template('ForWindowsIndex.html',url=url)
    else:
        app.logger.info("you are not logged in")
        return render_template('login.html')


if __name__ == '__main__':
    app.run(debug = True)
    

requirements.txt

这里也分享一个导出已安装pip包的方法,在支持linux语法的shell上使用 echo `pip list` > 文件名
这句话是将pip list 显示的内容输出到指定的文件

 alembic 0.9.3 
 asn1crypto 0.24.0 
 bleach 2.0.0 
 blinker 1.4 
 cffi 1.11.5 
 click 6.7 
 cryptography 2.4.1 
 DateTime 4.3 
 dominate 2.3.1 
 Flask 0.12.2 
 Flask-Bootstrap 3.3.7.1 
 Flask-HTTPAuth 3.2.3 
 Flask-Login 0.4.0 
 Flask-Mail 0.9.1 
 Flask-Migrate 2.0.4 
 Flask-Moment 0.5.1 
 Flask-PageDown 0.2.2 
 Flask-Script 2.0.6 
 Flask-SQLAlchemy 2.2 
 Flask-SSLify 0.1.5 
 Flask-WTF 0.14.2 
 gunicorn 19.7.1 
 html5lib 0.999999999
 idna 2.7 
 itsdangerous 0.24 
 Jinja2 2.9.6 
 Mako 1.0.7 
 Markdown 2.6.8 
 MarkupSafe 1.0 
 mysql-connector 2.1.6 
 mysql-connector-python 8.0.13 
 MySQL-python 1.2.5 
 pip 10.0.1 
 protobuf 3.6.1 
 psycopg2 2.7.3 
 pycparser 2.19 
 PyMySQL 0.9.2 
 python-dateutil 2.6.1 
 python-dotenv 0.6.5 
 python-editor 1.0.3 
 pytz 2018.7 
 setuptools 39.1.0 
 six 1.10.0 
 SQLAlchemy 1.2.12 
 start 0.2 
 visitor 0.1.3 
 webencodings 0.5.1 
 Werkzeug 0.12.2 
 WTForms 2.1 
 zope.interface 4.6.0

填坑:
首先存储mysql认证信息在conf.ini文件里,格式
[db]
NAME=root
PASSWORD=xxx
IPADDR=127.0.0.1
PORT=xxx
DATABASE=xxx
然后定义定义数据库中的表,程序启动时会自动在指定的数据库创建表,最后写login处理路由。

其中有特别多坑:
1.flask_sqlalchemy是一个方面,需要指定版本,不然会报编码错误
2.第二便是前端的表单action属性中要填写处理的路由,以我的本地环境为例是(http://127.0.0.1/login)
3.用app.logger.info(“xxx”)打印信息,debug,在路由时,print函数时不起作用的

总结:
最明显的一点感受便是其实博客只是参考的一个方面,很多东西还是看书来的深刻,而且并非所有的博客都是对的,环境不同,时间不同,存在坑很正常。我也遇到了各种各样奇葩的问题,还是一个一个的解决,浪费了特别多时间。但debug时参考博文还是特别好的

你可能感兴趣的:(Flask学习,flask,认证模块)