python仙修之 入門之後不放棄?
不以學習為目的的學習,那是耍流氓~所以流氓都成了有錢人。。。。。。
額,不貧了。從某天開始,次博客只談學習和感情,不談工作,不扯沒用的~
今天整個啥呢?容我思量思量~嗯,昨天不整了數據庫嗎,那就從這裏開始吧,來粘貼個小代碼,小爽一下子~
“”“數據庫の基本操作”“”
from pymysql import *
from hashlib import *
from pymongo import *
from redis import *
def register():
"""註冊"""
try:
# 1. 獲取連接對象
conn = mysql_conn()
# 2. 數據庫操作對象
cur = conn.cursor()
# 3. 編寫sql
select_params = [uname]
select_sql = ‘select upwd from momo_users where uname = %s‘
# 4.執行sql
cur.execute(select_sql, select_params)
res = cur.fetchone()
print(res)
if res is not None:
print(‘用戶名已經被註冊,註冊失敗‘)
return
# 註冊用戶 用戶一定不存在 插入數據
insert_params = [uname, sha_pwd]
insert_sql = ‘insert into momo_users (uname,upwd) values (%s,%s)‘
count = cur.execute(insert_sql, insert_params)
if count == 0:
print(‘註冊失敗‘)
else:
print(‘註冊成功‘, uname)
# 5. 如果是數據更新操作需要commit
conn.commit()
# 6.關閉cursor對象和連接對象
cur.close()
conn.close()
except Exception as e:
print(e)
def mysql_login():
"""登陸"""
try:
# 1. 獲取連接對象
conn = mysql_conn()
# 2. 數據庫操作對象
cur = conn.cursor()
# 3. 編寫sql
select_params = [uname]
select_sql = ‘select upwd from momo_users where uname = %s‘
# 4.執行sql
cur.execute(select_sql, select_params)
res = cur.fetchone()
if res is None:
# 根據用戶名沒有獲取到相關信息,此時用戶名錯誤
print(‘用戶名錯誤,登錄失敗‘)
cur.close()
conn.close()
return
# 獲取密碼信息 判斷密碼是否相等
print(res)
m_pwd = res[0]
if m_pwd == sha_pwd:
print(‘密碼正確,登錄成功‘,uname)
# 將查詢到的結果存儲到mongo/redis中
# col.insert_one({‘username‘:uname,‘password‘:sha_pwd})
r_client.set(uname,sha_pwd)
else:
print(‘密碼錯誤,登錄失敗‘)
# 6.關閉cursor對象和連接對象
cur.close()
conn.close()
except Exception as e:
print(e)
def mongo_login():
# 獲取mongo的連接對象
m_client = MongoClient(host=‘localhost‘,
port=27017)
db = m_client.QQDB
col = db.QQ_users
# 根據用戶名獲取數據 約定mongo中的數據存儲的方式 {‘username‘:uname,‘password‘:sha_pwd}
res = col.find_one({‘username‘: uname})
if res is None:
print(‘mongo中沒有獲取到任何數據,在mysql中完成登陸‘)
mysql_login()
else:
print(res)
m_password = res[‘password‘]
if m_password == sha_pwd:
print(‘密碼正確,登錄成功,mongodb‘)
else:
print(‘密碼錯誤,登錄失敗,mongodb‘)
def mysql_conn():
return connect(host=‘localhost‘,
user=‘root‘,
password=‘mysql‘,
database=‘python_restore‘,
port=3306,
charset=‘utf8‘)
if __name__ == ‘__main__‘:
uname = input(‘請輸入用戶名:‘)
upwd = input(‘請輸入密碼:‘)
# sha1
s1 = sha1()
s1.update(upwd.encode())
sha_pwd = s1.hexdigest()
print(sha_pwd)
# register()
# login()
r_client = StrictRedis(host=‘192.168.85.70‘)
# 約定好如何存儲數據 key value uname sha_pwd
res = r_client.get(uname)
print(res)
if res is None:
print(‘redis中沒有獲取到任何數據,在mysql中完成登陸‘)
mysql_login()
else:
r_pwd = res.decode()
if r_pwd == sha_pwd:
print(‘密碼正確,登錄成功,redis‘)
else:
print(‘密碼錯誤,登錄失敗,redis‘)
好了,就先到這裏吧。下一次把Python中相關的服務器這塊兒代碼搞一搞~可以的。
python仙修之 入門之後不放棄?