Я делаю сайт, в нем уже есть функция регистрации, она проходит успешно. Но присутствует проблема с авторизацией, после авторизации пользователя должно перебрасывать на страницу каталога, но этого не происходит, потому что перебрасывает на страницу с адресом "/Profile?Mail=*почта*&Password=*пароль*
Код на питоне(основной запускаемый файл)
from flask import Flask, render_template, url_for, request, g, flash, redirect
import sqlite3
import os
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import LoginManager, login_user, login_required
class UserLogin():
def fromDB(self, user_id, db):
self.__user = db.getUser(user_id)
return self
def create(self, user):
self.__user = user
return self
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return str(self.__user['id'])
class FDataBase:
def __init__(self, db):
self.__db = db
self.__cur = db.cursor()
def getProduct(self):
sql = '''SELECT * FROM products'''
try:
self.__cur.execute(sql)
res = self.__cur.fetchall()
if res: return res
except:
print('Error read database')
return []
def addUser(self, name, mail, psw):
try:
self.__cur.execute(f"SELECT COUNT() as count FROM user WHERE mail LIKE '{mail}' ")
res = self.__cur.fetchone()
if res['count'] > 0:
print("A user with such an email already exists")
return False
self.__cur.execute("INSERT INTO user VALUES(NULL, ?, ?, ?)", (name, mail, psw))
self.__db.commit()
except sqlite3.Error as e:
print('Error adding a user to the database '+str(e))
return False
return True
def getUser(self, user_id):
try:
self.__cur.execute(f"SELECT * FROM user WHERE id = {user_id} LIMIT 1")
res = self.cur.fetchone()
if not res:
print('The user was not found')
return False
return res
except sqlite3.Error as e:
print('Error adding a user to the database '+str(e))
return False
def getUserByEmail(self, mail):
try:
self.__cur.execute(f"SELECT * FROM user WHERE mail = '{mail}' LIMIT 1")
res = self.__cur.fechone()
if not res:
print("User not found")
return False
return res
except sqlite3.Error as e:
print('Error adding a user to the database '+str(e))
return False
DATABASE = '/tmp/BASE.db'
DEBUG = True
SECRET_KEY = 'secret-key'
app = Flask(__name__)
app.config.from_object(__name__)
app.config.update(dict(DATABASE=os.path.join(app.root_path, 'BASE.db')))
login_manager = LoginManager(app)
@login_manager.user_loader
def load_user(user_id):
print('load_user')
return UserLogin().fromDB(user_id, dbase)
dbase = None
@app.before_request
def before_request():
global dbase
db = get_db()
dbase = FDataBase(db)
def connect_db():
conn = sqlite3.connect(app.config['DATABASE'])
conn.row_factory = sqlite3.Row
return conn
def create_db():
db = connect_db()
with app.open_resource('sq_db.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
db.close()
def get_db():
if not hasattr(g, 'link_db'):
g.link_db = connect_db()
return g.link_db
@app.teardown_appcontext
def close_db(error):
if hasattr(g, 'link_db'):
g.link_db.close()
@app.route("/")
@app.route("/Catalog")
def index():
return render_template("Catalog.html", product=dbase.getProduct())
@app.route("/Registration", methods=["POST", "GET"])
def registration():
if request.method == "POST":
if len(request.form['Username']) > 4 and len(request.form['Mail']) > 4 and len(request.form['Password']) > 4:
hash = generate_password_hash(request.form['Password'])
res = dbase.addUser(request.form['Username'], request.form['Mail'], hash)
if res:
#flash('Registration was succeful')
return redirect('/Login')
else:
pass
#flash('Error adding to the database, try again later')
else:
pass
#flash("too short username or mail")
return render_template('Registration.html')
@app.route("/Login", methods=["POST", "GET"])
def login():
if request.method == "POST":
user = dbase.getUserByEmail(request.form['Mail'])
if user and check_password_hash(user['psw'], request.form['Password']):
userlogin = UserLogin().create(user)
login_user(userLogin)
return redirect(url_for('Catalog'))
#flash("Invalid username or password")
return render_template("Login.html")
@app.route("/Basket")
@login_required
def basket():
return render_template("Basket.html")
if __name__=="__main__":
app.run(debug=True)
Файл sql
CREATE TABLE IF NOT EXISTS user (
id integer PRIMARY KEY AUTOINCREMENT,
name text NOT NULL,
mail text NOT NULL,
psw text NOT NULL
);
CREATE TABLE IF NOT EXISTS products (
id integer PRIMARY KEY AUTOINCREMENT,
name text NOT NULL,
price integer NOT NULL,
image text NOT NULL
);