[英]how to validate credentials in flask/python with mysql?
登錄的燒瓶/ python驗證對我來說不適用於mysql,我正在搜索谷歌和文檔,我已經看到幾個關於堆棧溢出的問題同樣的事情但尚未得到答復。
from flask import Flask, render_template, flash, request, url_for, redirect, session
from content_management import Content
#form validations
from wtforms import Form, BooleanField, TextField, PasswordField, validators
#to encrypt the password
from passlib.hash import sha256_crypt
#for SQL injection
from MySQLdb import escape_string as thwart
import gc
from functools import wraps
from mysql_connect import connection
app = Flask(__name__)
@app.route('/login/', methods=['GET','POST'])
def login_page():
error = ''
try:
c, conn = connection()
if request.method == "POST":
d = c.execute("SELECT * FROM clients WHERE email = (%s)", (thwart(request.form['email']),))
d = c.fetchone()[2]
if request.form['password'] == d:
email = request.form['email']
c.execute("SELECT * FROM clients WHERE email = (%s)", (thwart(email),))
clients_table = c.fetchall()
clientcid = clients_table[0]
flash(clientcid)
phone = clients_table[1]
rating = clients_table[4]
conn.commit()
c.execute("SELECT * FROM cpersonals WHERE cid = (%s)", (clientcid,))
cpersonals_table = c.fetchall()
first_name = cpersonals_table[1]
last_name = cpersonals_table[2]
address = cpersonals_table[3]
czip = cpersonals_table[4]
reg_date = cpersonals_table[5]
conn.commit()
c.close()
conn.close()
session['logged_in'] = 'client'
session['clientcid'] = clientcid
session['email'] = email
session['phone'] = phone
session['rating'] = rating
session['first_name'] = first_name
session['last_name'] = last_name
session['address'] = address
session['czip'] = czip
session['reg_date'] = reg_date
flash("You are now logged in.")
return redirect(url_for("dashborad"))
else:
error = "Invalid credentials, try again."
return render_template("login.html")
有一種簡單的方法可以在沒有框架的情況下驗證MySQL中的憑據
這不是一個完整的答案(提供了解決問題應該做的代碼示例),而是一些建議:
您正在使用帶有數據庫的燒瓶,但沒有使用燒瓶擴展,例如flask-sqlalchemmy ,這是一個使SQLAlchemy (數據庫工具包)更易於與python一起使用的庫。 有了像flask-login (處理登錄和退出以及常見的“記住我”功能)之類的東西,你嘗試做的事情非常簡單。 如果您希望通過使用flask-sqlalchemy和flask-login從數據庫檢查其憑據來處理用戶登錄的示例文件,我可以創建一個,但是有很多應用程序使用這些工具的示例。
使用我提到的數據庫工具包還有許多其他優點,其中最少的是數據庫系統的可移植性(使用sqlalchemy的代碼通常可以在多個數據庫后端工作,如mysql,postgreSQL,sqlite等)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.