Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Cách viết chương trình Python CGI để tương tác với MySQL

Giả sử bạn muốn đăng nhập vào tài khoản bằng script Python CGI, dưới đây là chi tiết triển khai:

1. Tạo form đăng nhập (login.html)

<html>
<body>
<form action="login.py" method="get">
email: <input type="text" name="e1">
password: <input type="password" name="p1">
<input type="submit" value="register">
</form>
</body>
</html>

2. Script xử lý đăng nhập (login.py)

#!C:\Python27\python.exe
import MySQLdb
import cgi
import Cookie

# Mở kết nối database
db = MySQLdb.connect("localhost","root","","student")

# Tạo cursor
cursor = db.cursor()

# Lấy dữ liệu từ form
data = cgi.FieldStorage()
email = data.getvalue('e1')
password = data.getvalue('p1')

# Câu truy vấn SQL (lưu ý: ví dụ này dùng nối chuỗi, thực tế nên dùng parameterized query để tránh SQL injection)
sql = "select id,email,password from user where email='"+email+"' AND password='"+password+"'"

try:
    # Thực thi truy vấn
    if cursor.execute(sql):
        db.commit()
        # Tạo cookie
        c = Cookie.SimpleCookie()
        c['mou'] = email
        c['mou']['expires'] = 24*60*60
        # In header kèm cookie
        print(c)
        print("Content-type: text/html")
        print('''<html>
<head>
<title>Hello World - First CGI Program</title>
</head>
<body>
<h2>successfully login</h2>
</body>
</html>''')
    else:
        db.commit()
        print("Content-type: text/html")
        print("<html>")
        print("<body>")
        print("<h2>fail</h2>")
        print("</body>")
        print("</html>")
except Exception as e:
    # Rollback nếu lỗi
    db.rollback()
finally:
    # Đóng kết nối
    db.close()

Lưu ý quan trọng: Ví dụ trên sử dụng Python 2.7 và nối chuỗi SQL trực tiếp, dễ bị tấn công SQL Injection. Trong thực tế, hãy dùng Python 3, thư viện mysql-connector-python hoặc PyMySQL với parameterized queries (ví dụ: cursor.execute(sql, (email, password))).