Python3訪問MySQL數(shù)據(jù)庫(kù)的實(shí)現(xiàn)步驟
前言
要實(shí)現(xiàn)一個(gè)簡(jiǎn)單的IM(即時(shí)通訊)系統(tǒng),支持用戶注冊(cè)、登錄和聊天記錄存儲(chǔ),你可以使用Python和mysql數(shù)據(jù)庫(kù)。以下是一個(gè)基本的實(shí)現(xiàn)示例: 要使用MySQL創(chuàng)建表并通過Python提供一個(gè)API服務(wù),你可以使用Flask框架來(lái)實(shí)現(xiàn)API服務(wù),并使用PyMySQL庫(kù)來(lái)連接MySQL數(shù)據(jù)庫(kù)。以下是一個(gè)基本的實(shí)現(xiàn)步驟:
1. 安裝所需庫(kù)
首先,確保你安裝了Flask和PyMySQL庫(kù):
pip install flask pymysql
2. MySQL數(shù)據(jù)庫(kù)設(shè)置
docker run --hostname=a5ddc3708f2e --env=MYSQL_ROOT_PASSWORD=123456 --env=MYSQL_DATABASE=jwordpress --env=TZ=Asia/Shanghai --env=LANG=en_US.UTF-8 --env=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin --env=GOSU_VERSION=1.7 --env=MYSQL_MAJOR=5.7 --env=MYSQL_VERSION=5.7.26-1debian9 --volume=D:\IdeaProjects\Jwordpress-parent-s02-81f3dea303558f4388ef39435a52ea1cfab22904\docker\mysql\my.cnf:/etc/mysql/my.cnf:rw --volume=D:\IdeaProjects\Jwordpress-parent-s02-81f3dea303558f4388ef39435a52ea1cfab22904\docker\mysql\init-file.sql:/etc/mysql/init-file.sql:rw --volume=D:\IdeaProjects\Jwordpress-parent-s02-81f3dea303558f4388ef39435a52ea1cfab22904\docker\mysql\data:/var/lib/mysql:rw --volume=D:\IdeaProjects\Jwordpress-parent-s02-81f3dea303558f4388ef39435a52ea1cfab22904\docker\mysql\docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d:rw --volume=/var/lib/mysql --network=docker_default -p 3306:3306 --restart=unless-stopped --label='com.docker.compose.config-hash=f33622a4d32e092d39a39c3dc0bd2259df09b24ad897567bcaa7f7fa0630b019' --label='com.docker.compose.container-number=1' --label='com.docker.compose.depends_on=' --label='com.docker.compose.image=sha256:a1aa4f76fab910095dfcf4011f32fbe7acdb84c46bb685a8cf0a75e7d0da8f6b' --label='com.docker.compose.oneoff=False' --label='com.docker.compose.project=docker' --label='com.docker.compose.project.config_files=D:\IdeaProjects\Jwordpress-parent-s02-81f3dea303558f4388ef39435a52ea1cfab22904\docker\docker-compose.yml' --label='com.docker.compose.project.working_dir=D:\IdeaProjects\Jwordpress-parent-s02-81f3dea303558f4388ef39435a52ea1cfab22904\docker' --label='com.docker.compose.service=mysql' --label='com.docker.compose.version=2.21.0' --runtime=runc -d registry.cn-hangzhou.aliyuncs.com/zhengqing/mysql:5.7
假設(shè)你已經(jīng)在MySQL中創(chuàng)建了一個(gè)數(shù)據(jù)庫(kù),接下來(lái)創(chuàng)建用戶和消息表。
CREATE DATABASE chat_db; USE chat_db; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255) UNIQUE NOT NULL, password VARCHAR(255) NOT NULL ); CREATE TABLE messages ( id INT AUTO_INCREMENT PRIMARY KEY, sender VARCHAR(255) NOT NULL, receiver VARCHAR(255) NOT NULL, message TEXT NOT NULL, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP );
3. 創(chuàng)建Flask API服務(wù)
一個(gè)簡(jiǎn)單的Flask應(yīng)用,提供注冊(cè)、登錄和發(fā)送消息的API。 詳見main.py
from flask import Flask, request, jsonify import pymysql import bcrypt app = Flask(__name__) # Database connection configuration db_config = { 'host': 'localhost', 'user': 'root', 'password': '123456', 'database': 'chat_db' } def get_db_connection(): return pymysql.connect(**db_config) @app.route('/register', methods=['POST']) def register(): data = request.json username = data['username'] password = data['password'] hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) conn = get_db_connection() cursor = conn.cursor() try: cursor.execute("INSERT INTO users (username, password) VALUES (%s, %s)", (username, hashed)) conn.commit() return jsonify({'message': 'Registration successful!'}), 201 except pymysql.IntegrityError: return jsonify({'message': 'Username already exists!'}), 400 finally: cursor.close() conn.close() @app.route('/login', methods=['POST']) def login(): data = request.json username = data['username'] password = data['password'] conn = get_db_connection() cursor = conn.cursor() try: cursor.execute("SELECT password FROM users WHERE username = %s", (username,)) result = cursor.fetchone() if result and bcrypt.checkpw(password.encode('utf-8'), result[0].encode('utf-8')): return jsonify({'message': 'Login successful!'}), 200 else: return jsonify({'message': 'Incorrect username or password!'}), 401 finally: cursor.close() conn.close() @app.route('/send_message', methods=['POST']) def send_message(): data = request.json sender = data['sender'] receiver = data['receiver'] message = data['message'] conn = get_db_connection() cursor = conn.cursor() cursor.execute("INSERT INTO messages (sender, receiver, message) VALUES (%s, %s, %s)", (sender, receiver, message)) conn.commit() cursor.close() conn.close() return jsonify({'message': 'Message sent successfully!'}), 201 @app.route('/get_messages', methods=['GET']) def get_messages(): user1 = request.args.get('user1') user2 = request.args.get('user2') conn = get_db_connection() cursor = conn.cursor() cursor.execute('''SELECT sender, receiver, message, timestamp FROM messages WHERE (sender = %s AND receiver = %s) OR (sender = %s AND receiver = %s) ORDER BY timestamp''', (user1, user2, user2, user1)) messages = cursor.fetchall() cursor.close() conn.close() return jsonify(messages), 200 if __name__ == '__main__': app.run(debug=True)
4. 運(yùn)行API服務(wù)
將上述代碼保存為一個(gè)Python文件(例如main.py),然后運(yùn)行:
python main.py
這將啟動(dòng)一個(gè)Flask開發(fā)服務(wù)器,你可以通過POST請(qǐng)求來(lái)注冊(cè)和登錄用戶,通過GET請(qǐng)求來(lái)獲取聊天記錄。
5. 測(cè)試
post http://127.0.0.1:5000/register
{ "username": "alice", "password": "password123" }
post http://127.0.0.1:5000/register
{ "username": "bob", "password": "password123" }
post http://127.0.0.1:5000/send_message
{ "sender": "alice", "receiver": "bob", "message": "Hello Bob!" }
get http://127.0.0.1:5000/get_messages?user1=alice&user2=bob
[ [ "alice", "bob", "Hello Bob!", "Fri, 15 Nov 2024 16:06:33 GMT" ] ]
請(qǐng)注意,這個(gè)示例是一個(gè)基本實(shí)現(xiàn),適用于學(xué)習(xí)和測(cè)試。在生產(chǎn)環(huán)境中,你需要考慮更多的安全性和性能優(yōu)化,例如使用HTTPS、添加身份驗(yàn)證令牌等。
到此這篇關(guān)于Python3訪問MySQL數(shù)據(jù)庫(kù)的實(shí)現(xiàn)步驟的文章就介紹到這了,更多相關(guān)Python3訪問MySQL內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python3.7環(huán)境下sanic-ext未生效踩坑解析
這篇文章主要為大家介紹了python3.7環(huán)境下sanic-ext未生效踩坑解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01python模型集成知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家整理了一篇關(guān)于python模型集成知識(shí)點(diǎn)總結(jié),有需要的朋友們可以學(xué)習(xí)參考下。2021-08-08python如何將aac轉(zhuǎn)為mp3,保持原有目錄結(jié)構(gòu)
使用Python腳本實(shí)現(xiàn)AAC格式轉(zhuǎn)MP3格式的方法介紹,需要用戶輸入AAC文件所在目錄路徑和MP3輸出目錄路徑,通過調(diào)用FFmpeg工具實(shí)現(xiàn)格式轉(zhuǎn)換,該腳本簡(jiǎn)單易懂,適合需要批量處理音頻文件的用戶,使用前需確保已安裝FFmpeg環(huán)境2024-11-11echarts動(dòng)態(tài)獲取Django數(shù)據(jù)的實(shí)現(xiàn)示例
本文主要介紹了echarts動(dòng)態(tài)獲取Django數(shù)據(jù)的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08python編程-將Python程序轉(zhuǎn)化為可執(zhí)行程序[整理]
python編程-將Python程序轉(zhuǎn)化為可執(zhí)行程序[整理]...2007-04-04詳解Python利用random生成一個(gè)列表內(nèi)的隨機(jī)數(shù)
這篇文章主要介紹了詳解Python利用random生成一個(gè)列表內(nèi)的隨機(jī)數(shù),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08教你用Python創(chuàng)建微信聊天機(jī)器人
這篇文章主要手把手教你用Python創(chuàng)建微信聊天機(jī)器人,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03