Giới thiệu
Hướng dẫn, ví dụ về đăng nhập và đăng nhập Python sẽ chỉ cho bạn cách đăng nhập và đăng xuất người dùng bằng phiên sử dụng phiên trong Python 3. Bạn có thể cần người dùng xác thực/ủy quyền bằng cách sử dụng thông tin đăng nhập khi có các khu vực được bảo vệ trong ứng dụng web. Ví dụ: bạn cần xác thực khi bạn đang truy cập chi tiết tài khoản tiết kiệm của mình bằng NetBanking.
Điều kiện tiên quyết
Python 3.6.6- 3.9.5, Cơ sở dữ liệu MySQL 5.6- 8.0.22, Flask 1.1.1- 1.1.2
Login/Logout
Vui lòng thực hiện các bước sau để thực hiện đăng nhập Python và đăng nhập ví dụ bằng Flask MySQL:
Bước 1. & nbsp; Tạo tập lệnh app.py dưới đây [PY là phần mở rộng để chỉ ra tập lệnh Python] trong đó tôi nhập mô -đun bình. Lưu ý cách tôi tạo phiên bản Flask. Ở đây bạn cần chỉ định khóa bí mật nếu không phiên sẽ không hoạt động trong Python. Create the below app.py script [py is the extension to indicate Python script] where I import the flask module. Notice how I create flask instance. Here you need to assign secret key otherwise session will not work in Python.
from flask import Flask
app = Flask[__name__]
app.secret_key = "secret key"
Bước 2. & nbsp; Tôi tạo tập lệnh bên dưới & nbsp; db_config.py & nbsp; python để thiết lập cấu hình cơ sở dữ liệu MySQL để kết nối với cơ sở dữ liệu. Tôi cần định cấu hình kết nối cơ sở dữ liệu với mô -đun Flask và đó là lý do tại sao tôi đã nhập mô -đun ứng dụng và thiết lập cấu hình MySQL với mô -đun Flask. I create the below db_config.py Python script to setup the MySQL database configurations for connecting to database. I need to configure database connection with flask module and that’s why I have imported app module and setup the MySQL configuration with flask module.
from app import app
from flaskext.mysql import MySQL
mysql = MySQL[]
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'roytuts'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app[app]
Bước 3. & nbsp; Tiếp theo tôi cần & nbsp; Main.py Script. Kịch bản này là ví dụ hoàn hảo của đăng nhập Python và ví dụ đăng xuất bằng bình và MySQL. Nó xác định tất cả các URI bắt buộc để thực hiện các hoạt động đăng nhập và đăng xuất. Nó cũng sẽ kết nối với máy chủ cơ sở dữ liệu MySQL và truy vấn cơ sở dữ liệu để đọc. Next I need main.py script. This script is the perfect instance of Python login and logout example using Flask and MySQL. It defines all required URIs for performing login and logout operations. It will also connect to MySQL database server and query the database to read.
Bài viết liên quan::
- Đăng nhập Ví dụ đăng nhập bằng cách sử dụng API REST BLEAD PYTHON
- Đăng nhập đăng nhập Python Flask với Tùy chọn Ghi nhớ tôi
- JQuery Ajax đăng nhập đăng nhập dựa trên
Tôi đã sử dụng trang đăng nhập.html để đăng nhập vào hệ thống nhưng đối với trang home hoặc index, tôi chỉ hiển thị văn bản HTML thay vì sử dụng trang mẫu. Nếu bạn muốn bạn cũng có thể sử dụng trang mẫu HTML cho trang Home hoặc Index.login.html page for log in to the system but for home or index page I have only displaying html text instead of using template page. If you want you can use html template page for home or index page also.
import pymysql
from app import app
from db_config import mysql
from flask import flash, session, render_template, request, redirect
from werkzeug import generate_password_hash, check_password_hash
@app.route['/']
def index[]:
if 'email' in session:
username = session['email']
return 'Logged in as ' + username + '
' + "click here to logout"
return "You are not logged in
" + "click here to login"
@app.route['/login']
def login[]:
return render_template['login.html']
@app.route['/submit', methods=['POST']]
def login_submit[]:
_email = request.form['inputEmail']
_password = request.form['inputPassword']
# validate the received values
if _email and _password and request.method == 'POST':
#check user exists
conn = mysql.connect[]
cursor = conn.cursor[]
sql = "SELECT * FROM tbl_user WHERE user_email=%s"
sql_where = [_email,]
cursor.execute[sql, sql_where]
row = cursor.fetchone[]
if row:
if check_password_hash[row[3], _password]:
session['email'] = row[1]
cursor.close[]
conn.close[]
return redirect['/']
else:
flash['Invalid password!']
return redirect['/login']
else:
flash['Invalid email/password!']
return redirect['/login']
@app.route['/logout']
def logout[]:
session.pop['email', None]
return redirect['/']
if __name__ == "__main__":
app.run[]
Bước 4. Dưới đây là trang HTML đăng nhập. Trong trang này, tôi hiển thị mọi lỗi hoặc tin nhắn thành công được lưu trữ trong phạm vi flash hoặc phiên. Below is the login html page. In this page I display any error or success message which are stored in flash or session scope.
User Login - Python Flask
Login
{% with messages = get_flashed_messages[] %}
{% if messages %}
{% for message in messages %}
- {{ message }}
{% endfor %}
{% endif %}
{% endwith %}
Bảng MySQL
Đối với phiên bản MySQL 5.6, bạn có thể sử dụng cấu trúc sau:
DROP TABLE IF EXISTS `tbl_user`;
CREATE TABLE `tbl_user` [
`user_id` bigint[20] NOT NULL AUTO_INCREMENT,
`user_name` varchar[45] COLLATE utf8_unicode_ci DEFAULT NULL,
`user_email` varchar[45] COLLATE utf8_unicode_ci DEFAULT NULL,
`user_password` varchar[255] COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY [`user_id`]
] ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*Data for the table `tbl_user` */
insert into `tbl_user`[`user_id`,`user_name`,`user_email`,`user_password`] values
[2,'Soumitra Roy','','pbkdf2:sha256:50000$g1GQ8Qen$7413b42b320fc47813b3188b52e08a6681be1c83d4eeec15ee6ca4b9fe8347ef'];
Đối với MySQL phiên bản 8.0.22, bạn có thể sử dụng SROFURE sau:
CREATE TABLE `tbl_user` [
`user_id` bigint COLLATE utf8mb4_unicode_ci NOT NULL AUTO_INCREMENT,
`user_name` varchar[45] COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`user_email` varchar[45] COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`user_password` varchar[255] COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY [`user_id`]
] ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
insert into `tbl_user`[`user_id`,`user_name`,`user_email`,`user_password`] values
[2,'Soumitra Roy','','pbkdf2:sha256:50000$g1GQ8Qen$7413b42b320fc47813b3188b52e08a6681be1c83d4eeec15ee6ca4b9fe8347ef'];
Đủ mã hóa, hãy để Let chuyển sang thử nghiệm
Kiểm tra ứng dụng
Bây giờ điều hướng đến Dự án & NBSP; thư mục và thực thi lệnh & nbsp; ____ ____ 6 hoặc main.py
, máy chủ của bạn sẽ bắt đầu trên cổng mặc định & nbsp; 5000. Nếu bạn muốn thay đổi cổng thì bạn có thể thay đổi dòng & nbsp; ________ 8 & nbsp; thành & nbsp; ________ 9, trong đó & nbsp; 5001 & nbsp; là cổng mới.5000. If you want to change the port then you can change the line app.run[]
to app.run[port=50001]
, where 5001 is the new port.
Lỗi trên email và mật khẩu không hợp lệ
Lỗi về mật khẩu không hợp lệ
Thành công trên email và mật khẩu hợp lệ [PWD]
Đó là tất cả. Hy vọng bạn có ý tưởng về đăng nhập Python và ví dụ đăng nhập bằng Flask và MySQL.
Mã nguồn
Tải xuống