Python基礎-練習題


一、通過讀取列表數據,寫一個登錄程序:

users=[    
      ['Amy', '123456'],
      ['Ann', '456789'],
      ['Sarah', '123456abc']   
]

1、登錄,輸入賬號和密碼,最多輸入3次,3次還沒有登錄成功,提示次數超數

2、登錄成功,提示:歡迎XXX登錄,今日的日期是XXX,程序結束

3、賬號和密碼不能為空,要提示不能為空 ---字符串方法

4、賬號和密碼輸入錯誤,提示錯誤,繼續登錄

5、輸入的賬號不存在,提示用戶,算輸錯1次

編寫程序題目分析:

 代碼如下:

import datetime
users=[
      ['Amy', '123456'],
      ['Ann', '456789'],
      ['Sarah', '123456abc']
]
usernames = []
passwords = []
for user in users:
    username,password = user
    usernames.append(username)
    passwords.append(password)
# print(usernames)
# print(passwords)
for i in range(3):
    username = input('請輸入用戶名:')
    password = input('請輸入登錄密碼:')
    if len(username) == 0 or password.strip() == '':
    #  len() 長度為0 和 空字符串,效果是一樣的
        print('用戶名或密碼不能為空!')
    elif username not in usernames:
        print('用戶名不存在')
    else:
        # index = usernames.index(username)
        # pwd = passwords[index]
        # if pwd == password:
        if [username,password] in users:
            print('歡迎%s登錄,今天是%s! '%(username,datetime.datetime.today()))
            break
        else:
            print('用戶名或密碼錯誤!')
else:
    print('錯誤次數過多!')

 

二、通過讀取文件,進行注冊用戶以及用戶登錄

1、程序用戶注冊,賬號和密碼存在文件里面:

(1)最多輸入3次

(2)輸入賬號和密碼,確認密碼,密碼長度在6-12位之間(注:密碼包含大小寫字母,數字)

(3)輸入為空要提示

(4)用戶已經存在不能注冊

(5)兩次密碼要輸入一致

編寫程序題目分析:

 

代碼如下:

f = open('users.txt','a+',encoding='utf-8')
f.seek(0)
usernames = []
for line in f.readlines():
    line = line.strip()    # 防止文件里有空行
    if line:
        username = line.split(',')[0]
        usernames.append(username)

for i in range(3):
    username = input('username:').strip()
    password = input('password:').strip()
    cpassword = input('cpassword:').strip()
    if not username or not password or not cpassword:
        print('賬號/密碼不能為空!')
    elif len(password) <6 or len(password) >12:
        print('密碼長度在6-12之間!')
    elif password != cpassword:
        print('兩次輸入的密碼不一致!')
    else:
        l,u,d = False,False,False
        for p in password:
            if p.islower():
                l = True
            elif p.isupper():
                u = True
            elif p.isdigit():
                d = True
        if not l or not u or not d :
            print('密碼必包含大小寫字母,和數字!')
        elif username in usernames:
            print('用戶已存在!')
        else:
            f.write('%s,%s\n'%(username,password))
            print('注冊成功!')
            break
else:
    print('錯誤次數過多!')
f.close()

 

2、用戶登錄程序,賬號和密碼從文件里面取

(1)最多輸入3次

(2)賬號和密碼的為空校驗

(3)不存在要提示

(4)登錄成功結束

編寫程序題目分析:

代碼如下:

f = open('users.txt',encoding='utf-8')
users = {}
for line in f.readlines():
    line = line.strip()
    if line:
        username = line.split(',')[0]
        password = line.split(',')[1]
        users[username] = password
for i in range(3):
    username = input('username:').strip()
    password = input('password:').strip()
    if not username or not password :
        print('賬號/密碼不能為空!')
    elif len(password) < 6 or len(password) > 12:
        print('密碼長度在6-12之間!')
    elif username not in users:
        print('用戶不存在!')
    elif password != users.get(username):
        print('密碼錯誤!')
    else:
        print('歡迎登錄!')
        break
else:
    print('錯誤次數超限!')
f.close()

 

三、寫一個管理商品的程序,商品文件格式在(product.json)里面(1、查看商品 2、新增商品 3、修改商品信息 4、刪除商品)

商品文件信息(product.json):

{
  "mac book":{
    "count": 50,
    "price": 8999
  },
  "礦泉水":{
    "count": 100,
    "price": 1.1
  }
}

 

提供商品的增刪改查功能:

(1)choice = input('請輸入你的選擇:1、查看商品 2、新增商品 3、修改商品 4、刪除商品')

(2)查看商品,輸入商品名稱,print單個商品的信息,價格,數量,輸入all,查看所有商品

(3)新增商品,輸入商品名稱、數量、價格,數量是大於0的整數,價格必須是大於0的數值,如果商品存在,無法添加

(4)修改商品,輸入商品名稱、數量、價格,商品存在才可以修改,數量是大於0的整數,價格必須是大於0的數值

(5)輸入商品名稱,如果存在,刪除

編寫程序題目分析:

代碼如下:

import json

file_name = 'product.json' # 文件名稱不會發生變化,故定義常量
# 定義讀取商品函數
def read_products():
    with open(file_name,encoding='utf-8') as fr:
        return json.load(fr)
# 定義寫入商品函數
def write_products(data):
    with open(file_name,'w', encoding='utf-8') as fw:
        json.dump(data,fw,ensure_ascii=False,indent=4)

# 定義數量函數
def is_digit(number):
    s = str(number)
    if s.isdigit():
        if int(s) > 0:
            return True

# 定義價格函數
def is_price(price):   # >0的整數和小數都可以
    s = str(price)
    if is_digit(s):
            return True
    else:
        if s.count('.') == 1:    #1.3
            left,right = s.split('.')
            if left.isdigit() and right.isdigit(): # 正整數 0.0
                if float(s) > 0:
                    return True
# 定義查看商品函數
def show_product():
    # 第一種先讀取商品文件信息,然后輸入商品名稱,接下來作判斷
    # products = read_products()
    # product_name = input('請輸入商品名稱:').strip()
    # if not product_name:
    #     print('請輸入商品名稱:')
    # elif product_name == 'all':
    #     print(products)
    # elif product_name not in products:
    #     print('商品不存在!')
    # else:
    #     product = products.get(product_name)
    #     print('商品信息:',product)
    # 第二種先輸入商品名稱,然后讀取文件,接下來進行判斷(推薦使用)
    product_name = input('請輸入商品名稱:').strip
    if product_name:
        products = read_products()
        if product_name == 'all':
            print(products)
        elif product_name not in products:
            print('商品不存在!')
        else:
            product = products.get(product_name)
            print('商品信息:',product)
    else:
        print('不能為空!')

# 定義新增商品函數
def add_product():
        product_name = input('請輸入商品名稱:').strip()
        price = input('請輸入商品價格').strip()
        count = input('請輸入商品數量:').strip()
        if product_name and price and count:
            if is_price(price) and is_digit(count):
                products = read_products()
                if product_name not in products:
                    products[product_name] = {"count":count,"price":price}
                    write_products(products)
                    print('商品新增成功!')
                else:
                    print('商品已經存在!')
            else:
                print('價格/數量不合法!')
        else:
            print('不能為空!')

# 定義修改商品函數
def modify_product():
    product_name = input('請輸入商品名稱:').strip()
    price = input('請輸入商品價格').strip()
    count = input('請輸入商品數量:').strip()
    if product_name and price and count:
        if is_price(price) and is_digit(count):
            products = read_products()
            if product_name in products:
                products[product_name] = {"count": count, "price": price}
                write_products(products)
                print('商品修改成功!')
            else:
                print('商品不存在')
        else:
            print('價格/數量不合法!')
    else:
        print('不能為空!')

# 定義刪除商品函數
def del_product():
    product_name = input('請輸入商品名稱:').strip()
    if product_name:
        products = read_products()
        if product_name not in products:
            print('商品不存在!')
        else:
            products.pop(product_name)
            write_products(products)
    else:
        print('不能為空!')
# 商品管理
choice = input('1、查看商品 2、新增商品 3、修改商品 4、刪除商品')
func_map = {'1': show_product(), '2': add_product(),'3': modify_product(),'4':del_product()}
if choice in func_map:
    func_map[choice]
else:
    print('請輸入正確的選項!')

 

四、寫一個刪除日志的腳本,把三天前的日志並且為空的日志刪除

1、首先需要執行造日志的腳本文件:造日志的腳本.py

def timestamp_to_str(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
    '''時間戳轉格式化好的時間,如果沒有傳時間戳,就獲取當前的格式化時間'''
    if timestamp:
        time_tuple = time.localtime(timestamp) #把時間戳轉成時間元組
        result = time.strftime(format,time_tuple) #把時間元組轉成格式化好的時間
        return result
    else:
        return time.strftime(format)


import time,os,random
l = ['ios','android','nginx','tomcat','python','blog','apache','mysql','redis']

for i in l:
    p = os.path.join('logs',i)
    os.makedirs(p)
    for j in range(30):
        t = int(time.time())-86400*j
        time_str = timestamp_to_str(t,'%Y-%m-%d')
        log_name = '%s_%s.log'%(i,time_str)
        abs_file_path = os.path.join('logs',i,log_name)
        fw = open(abs_file_path, 'w', encoding='utf-8')
        if random.randint(1,10)%2==0:
            fw.write('勝多負少防守打法雙方都')
        fw.close()

 

2、編寫程序題目分析:

 

3、代碼如下:

import os
import time

day = 60*60*24*3

def str_to_timestamp(str_time,format='%Y-%m-%d'):
    time_tuple = time.strptime(str_time,format)
    return int(time.mktime(time_tuple))

def clean_log(path):
    if os.path.isdir(path):
        for cur_path,dirs,files in os.walk(path):
            for file in files:
                if file.endswith('.log'):  # android_2020-09-04.log
                    file_time = file.split('.')[0].split('_')[-1]
                    file_time_stamp = str_to_timestamp(file_time)
                    ago_time_stamp = time.time() - day
                    file_abs_path = os.path.join(cur_path,file)
                    if file_time_stamp < ago_time_stamp or os.path.getsize(file_abs_path)==0:
                        if time.strftime('%Y-%m-%d') in file:
                            continue
                        os.remove(file_abs_path)
    else:
        print('路徑錯誤!')

clean_log('logs')

 

五、寫一個產生雙色球號碼的程序,輸入幾就產生多少條:

1、產生的里面不能有重復的

2、產生的號碼要1 2 3 4 5 6

3、紅色球號碼從1--33中選擇

4、藍色球號碼從1--16中選擇

例如:01 02 03 04 05 06 07

編寫程序題目分析:

 

代碼如下:

# 第一種方法
import random
number = input('number:').strip()
if number.isdigit() and int(number) >0:
     l = []
     while True:
         red = random.sample(range(1,34),6)
         red.sort()
         blue = random.sample(range(1,17),1)
         result = red + blue
         result = [str(ball).zfill(2) for ball in result]
         seq = ' '.join(result)
         if seq not in l:
             l.append(seq)
             print('生成的雙色球號碼是:紅球:%s 藍球:%s' %(' '.join(result[:6]),result[-1]))
         if int(number) == len(l):
             break

 

# 第二種方法
import random
reds = [str(ball).zfill(2) for ball in range(1,34)]
blues = [str(ball).zfill(2) for ball in range(1,17)]

number = input('number:').strip()
if number.isdigit() and int(number) >0:
    l = set()
    while int(number) !=len(l):
        red = random.sample(reds,6)
        red.sort()
        blue = random.sample(blues,1)
        result = red + blue
        result = [str(ball).zfill(2) for ball in result]
        seq = ' '.join(result) + '\n'
        l.add(seq)
        print('生成的雙色球號碼是:紅球:%s 藍球:%s' %(' '.join(result[:6]),result[-1]))

with open('seq.txt','w',encoding='utf-8') as fw:
    fw.writelines(l)

 

六、寫一個函數,傳入一個表名,把整個表里面的數據導出到excel

1、編寫程序題目分析

2、方法一:export_table_to_excel.py

import pymysql,xlwt
table_name = input('請輸入你要導出的表名:').strip()
conn=pymysql.connect(host='118.24.3.40',user = 'jxz',
                        password = '123456',db = 'jxz',
                        charset='utf8',autocommit=True)   #若不插入charset,有可能出現亂碼

cur = conn.cursor(pymysql.cursors.DictCursor)

#MySQL判斷表是否存在:SELECT table_name FROM information_schema.TABLES WHERE table_name ='yourname';
table_exist_sql = "SELECT table_name FROM information_schema.TABLES WHERE table_name ='%s';"% table_name
cur.execute(table_exist_sql)
if cur.fetchall(): query_sql = 'select * from %s;' % table_name cur.execute(query_sql) data = cur.fetchall() if data: book = xlwt.Workbook() #todo,沒有處理表頭 sheet = book.add_sheet('sheet1') for index,key in enumerate(data[0]): #寫表頭 sheet.write(0,index,key) for row,item in enumerate(data,1): #寫數據 for col,value in enumerate(item.values()): sheet.write(row,col,value) book.save(table_name+'.xls') print('導出完成!') else: print('表中無數據,無法導出!') else: print('表不存在!') cur.close() conn.close()

 

3、方法二:export_table_to_excel.py

(1)定義tools函數模塊:

import pymysql,xlwt
import traceback

MYSQL_INFO ={
    'host' :'118.24.3.40',
    'user' :'jxz',
    'password' : '123456',
    'db' : 'jxz',
    'charset':'utf8',
    'port' : '3306',
    'autocommit':True
}

def execute_sql(sql):
    conn =pymysql.connect(**MYSQL_INFO) # XX=XXX,XX=XX
    cur =conn.cursor(pymysql.cursors.DictCursor)
    try:
        cur.execute(sql)
    except:
        print('sql不正確')
        traceback.print_exc()
    else:
        return  cur.fetchall() # None []
    finally:
        conn.close()
        cur.close()

def write_excel(name,data):
    book = xlwt.Workbook()
    sheet = book.add_sheet('sheet1')
    for index, key in enumerate(data[0]):  # 寫表頭
        sheet.write(0, index, key)
    for row, item in enumerate(data, 1):  # 寫數據
        for col, value in enumerate(item.values()):
            sheet.write(row, col, value)
    book.save(name + '.xls')

(2)引用tools函數模塊:

import tools
def main():
    table_name = input('請輸入你要導出的表名:').strip()
    table_exist_sql = "SELECT table_name FROM information_schema.TABLES WHERE table_name ='%s';" % table_name
    if tools.execute_sql(table_exist_sql):
        query_sql = 'select * from %s;' % table_name
        data = tools.execute_sql(query_sql)
        if data:
            tools.write_excel(table_name,data)
            print('導出完成!')
        else:
            print('表中無數據,無法導出!')
    else:
        print('表不存在!')

if __name__ == '__main__':
    main()

 

七、改寫商品管理的程序,改為從數據庫里面取數據

1、方法一:商品管理:product_simple.py

import json
import tools
# 定義讀取商品函數
def read_products():
    sql = 'select * from tmz_product_xzh;'
    data = tools.execute_sql(sql)   # [{'id':1,'product_name':'XXX','count':XX,'price':XX}]
    d = {}
    for item in data:
        name = item.get('product_name')
        count = item.get('count')
        price = float(item.get('price'))
        d[name]={'count':count,'price':price}
    return d

# 定義寫入商品函數
def write_products(data):
    truncate_sql ='truncate table tmz_product_xzh'
    tools.execute_sql(truncate_sql)
    for k,value in data.items():
        count = value.get('count')
        price = value.get('price')
        insert_sql = 'insert into tmz_product_xzh(product_name,count,price) VALUES ("%s",%s,%s);'%(k,count,price)
        tools.execute_sql(insert_sql)

# 定義數量函數
def is_digit(number):
    s = str(number)
    if s.isdigit():
        if int(s) > 0:
            return True

# 定義價格函數
def is_price(price):   # >0的整數和小數都可以
    s = str(price)
    if is_digit(s):
            return True
    else:
        if s.count('.') == 1:    #1.3
            left,right = s.split('.')
            if left.isdigit() and right.isdigit(): # 正整數 0.0
                if float(s) > 0:
                    return True
# 定義查看商品函數
def show_product():
    # 第一種先讀取商品文件信息,然后輸入商品名稱,接下來作判斷
    # products = read_products()
    # product_name = input('請輸入商品名稱:').strip()
    # if not product_name:
    #     print('請輸入商品名稱:')
    # elif product_name == 'all':
    #     print(products)
    # elif product_name not in products:
    #     print('商品不存在!')
    # else:
    #     product = products.get(product_name)
    #     print('商品信息:',product)
    # 第二種先輸入商品名稱,然后讀取文件,接下來進行判斷(推薦使用)
    product_name = input('請輸入商品名稱:').strip
    if product_name:
        products = read_products()
        if product_name == 'all':
            print(products)
        elif product_name not in products:
            print('商品不存在!')
        else:
            product = products.get(product_name)
            print('商品信息:',product)
    else:
        print('不能為空!')

# 定義新增商品函數
def add_product():
        product_name = input('請輸入商品名稱:').strip()
        price = input('請輸入商品價格').strip()
        count = input('請輸入商品數量:').strip()
        if product_name and price and count:
            if is_price(price) and is_digit(count):
                products = read_products()
                if product_name not in products:
                    products[product_name] = {"count":count,"price":price}
                    write_products(products)
                    print('商品新增成功!')
                else:
                    print('商品已經存在!')
            else:
                print('價格/數量不合法!')
        else:
            print('不能為空!')

# 定義修改商品函數
def modify_product():
    product_name = input('請輸入商品名稱:').strip()
    price = input('請輸入商品價格').strip()
    count = input('請輸入商品數量:').strip()
    if product_name and price and count:
        if is_price(price) and is_digit(count):
            products = read_products()
            if product_name in products:
                products[product_name] = {"count": count, "price": price}
                write_products(products)
                print('商品修改成功!')
            else:
                print('商品不存在')
        else:
            print('價格/數量不合法!')
    else:
        print('不能為空!')

# 定義刪除商品函數
def del_product():
    product_name = input('請輸入商品名稱:').strip()
    if product_name:
        products = read_products()
        if product_name not in products:
            print('商品不存在!')
        else:
            products.pop(product_name)
            write_products(products)
    else:
        print('不能為空!')
# 商品管理
choice = input('1、查看商品 2、新增商品 3、修改商品 4、刪除商品')
func_map = {'1': show_product(), '2': add_product(),'3': modify_product(),'4':del_product()}
if choice in func_map:
    func_map[choice]
else:
    print('請輸入正確的選項!')

2、方法二:product_gooduse.py

import tools

#獲取單個商品信息的函數
def get_single_product(name):
    sql = 'select * from tmz_product_xzh where product_name = "%s";' % name
    return tools.execute_sql(sql)

# 定義數量函數
def is_digit(number):
    s = str(number)
    if s.isdigit():
        if int(s) > 0:
            return True

# 定義價格函數
def is_price(price):   # >0的整數和小數都可以
    s = str(price)
    if is_digit(s):
            return True
    else:
        if s.count('.') == 1:    #1.3
            left,right = s.split('.')
            if left.isdigit() and right.isdigit(): # 正整數 0.0
                if float(s) > 0:
                    return True
# 定義查看商品函數
def show_product():
    product_name = input('請輸入商品名稱:').strip()
    if product_name:
        if product_name == 'all':
            sql = 'select* from tmz_product_xzh;'
            print(tools.execute_sql(sql))
        else:
            product = get_single_product(product_name)
            if product:
                print('商品信息:',product)
            else:
                print('您輸入的商品不存在!')
    else:
        print('不能為空!')

# 定義新增商品函數
def add_product():
        product_name = input('請輸入商品名稱:').strip()
        price = input('請輸入商品價格:').strip()
        count = input('請輸入商品數量:').strip()
        if product_name and price and count:
            if is_price(price) and is_digit(count):
                if get_single_product(product_name):
                    print('商品已經存在!')
                else:
                    insert_sql = 'insert into tmz_product_xzh(product_name,count,price)'\
                                'VALUES ("%s",%s,%s);' % (product_name,count,price)
                    tools.execute_sql(insert_sql)
                    print('商品新增成功!')
            else:
                print('價格/數量不合法!')
        else:
            print('不能為空!')

# 定義修改商品函數
def modify_product():
    product_name = input('請輸入商品名稱:').strip()
    price = input('請輸入商品價格:').strip()
    count = input('請輸入商品數量:').strip()
    if product_name and price and count:
        if is_price(price) and is_digit(count):
            if get_single_product(product_name):
                sql = 'update tmz_product_xzh set price=%s,count=%s where product_name="%s";' %(
                    price,count,product_name
                )
                tools.execute_sql(sql)
                print('商品修改成功!')
            else:
                print('商品不存在!')

        else:
            print('價格/數量不合法!')
    else:
        print('不能為空!')

# 定義刪除商品函數
def del_product():
    product_name = input('請輸入商品名稱:').strip()
    if product_name:
        if get_single_product(product_name):
            sql= 'delete from tmz_product_xzh where product_name = "%s";' %product_name
            tools.execute_sql(sql)
            print('商品已刪除!')
        else:
            print('商品不存在!')
    else:
        print('不能為空!')
# 商品管理
choice = input('1、查看商品 2、新增商品 3、修改商品 4、刪除商品')
func_map = {'1': show_product, '2': add_product,'3': modify_product,'4':del_product}
if choice in func_map:
    func_map[choice]()
else:
    print('請輸入正確的選項!')

 

八、寫一個下載QQ群成員的QQ頭像程序,傳入一個群號,把這個群里所有人的qq頭像下載到本地,如果這個人有群備注,那么圖片的名稱就是劉海洋.jpg如果沒有就取昵稱:

1、編寫程序分析:

2、代碼如下:download_imag_to_local.py

# 寫一個程序,傳入一個群號,把這個群里所有的人的QQ頭像下載到本地
# 獲取群成員信息接口:https://qun.qq.com/cgi-bin/qun_mgr/search_group_members
# 調用接口:search_group_members(Nick昵稱,card群備注)
# 如果A同學有群備注,那么圖片的名稱就是:Bob.jpg
# 如果A同學沒有群備注,那么圖片名稱就是:28.jpg
# Form Data
# gc: 1078641913
# st: 0
# end: 20
# sort: 0
# bkn: 73612145
# cookie: pgv_pvi=328774656; RK=Bqzk3YEWb+; ptcz=4c3263932d8d5a48b929cd2283f1bde3146c1ee5c4f104796f0c8d95df45c3c8; tvfe_boss_uuid=7d887b37fe60ad85; pgv_pvid=3957380448; pgv_info=ssid=s6095095448; _qpsvr_localtk=0.3003351169111208; p_uin=o1270894070; traceid=830f93d7d9; pgv_si=s2666891264; enc_uin=LqUhmq_so7tn_55OuYQ1UA; uin=o1270894070; skey=@zAKP7lF3z; pt4_token=mxrCcJXWkoh7OkmQxzKPcGAN1wqDHNqMK0hrIJnXZhw_; p_skey=amB*w3nrfpXGRncsrH-elBWWaLZ4w4rFlYsjF0rwo2I_
# 頭像下載地址:https://q4.qlogo.cn/g?b=qq&nk=XXXXXXXXX=140
import requests,os

# 判斷該文件夾是否存在,不存在自動創建
if not os.path.exists('qq_pics'):
    os.mkdir('qq_pics')

# 進入創建的文件夾里面:
os.chdir('qq_pics')

max_count = 1000
gc = 1078641913
bkn = 73612145
# 獲取群信息
group_member_url = 'https://qun.qq.com/cgi-bin/qun_mgr/search_group_members'
size = 40
cookie = 'pgv_pvi=328774656; RK=Bqzk3YEWb+; ptcz=4c3263932d8d5a48b929cd2283f1bde3146c1ee5c4f104796f0c8d95df45c3c8; tvfe_boss_uuid=7d887b37fe60ad85; pgv_pvid=3957380448; pgv_info=ssid=s6095095448; _qpsvr_localtk=0.3003351169111208; p_uin=o1270894070; traceid=830f93d7d9; pgv_si=s2666891264; enc_uin=LqUhmq_so7tn_55OuYQ1UA; uin=o1270894070; skey=@zAKP7lF3z; pt4_token=mxrCcJXWkoh7OkmQxzKPcGAN1wqDHNqMK0hrIJnXZhw_; p_skey=amB*w3nrfpXGRncsrH-elBWWaLZ4w4rFlYsjF0rwo2I_'
count = 0
for j in range(0,max_count+1,size): # 0,20,3
    # 0,20 21,41 42,62 63,83 84,104
    # 0,20 20,40 40,60 60,80 80,100
    data = {'gc':gc,'st':j+count,'end':j+size+count,'bkn':bkn}
    headers = {'cookie':cookie}
    r = requests.post(group_member_url,data,headers=headers)
    members = r.json()
    count +=1
    if 'mems' in members:
        # QQ圖片下載的url地址
        pic_url= 'https://q4.qlogo.cn/g?b=qq&nk=%s&s=140'
        # 獲取成員信息(列表格式)
        mems = members.get('mems')
        for m in mems:
            qq = m.get('uin')
            # 使用三元表達式:若取到了card就用card名稱,取不到就取nick名稱
            name = m.get('card') if m.get('card') else m.get('nick')
            r = requests.get(pic_url % qq)
            with open(name + '.jpg','wb') as fw:
                fw.write(r.content)
            # 下載qq頭像
            print('下載完成 %s'%name)
    else:
         print('沒有獲取到群成員信息!')
         break

 

九、寫兩個接口(登錄接口和支付接口)

1、編寫程序分析:

2、代碼如下:

(1)tools.py

import hashlib

import pymysql,xlwt
import traceback

import redis

MYSQL_INFO ={
    'host' :'118.24.3.40',
    'user' :'jxz',
    'password' : '123456',
    'db' : 'jxz',
    'charset':'utf8',
    'port' : 3306,
    'autocommit':True
}

REDIS_INFO = {
    'host':'118.24.3.40',
    'password':'HK139bc&*',
    'db':0,
    'port':6379,
    'decode_responses':True
}

def execute_sql(sql,more=False):
    conn =pymysql.connect(**MYSQL_INFO) # XX=XXX,XX=XX
    cur =conn.cursor(pymysql.cursors.DictCursor)
    try:
        cur.execute(sql)
    except:
        print('sql不正確')
        traceback.print_exc()
    else:
        if more:
            return  cur.fetchall() # None [{}]
        return cur.fetchone()      # {‘XX’:'XX'}
    finally:
        conn.close()
        cur.close()

def write_excel(name,data):
    book = xlwt.Workbook()
    sheet = book.add_sheet('sheet1')
    for index, key in enumerate(data[0]):  # 寫表頭
        sheet.write(0, index, key)
    for row, item in enumerate(data, 1):  # 寫數據
        for col, value in enumerate(item.values()):
            sheet.write(row, col, value)
    book.save(name + '.xls')

def my_md5(s):
    s = str(s)
    s = s.encode()
    m = hashlib.md5(s)
    result = m.hexdigest()
    return result

def redis_str(key,value=False,expire_time=None):
    r = redis.Redis(**REDIS_INFO)
    if value:
        r.set(key,value,expire_time)
    else:
        return r.get(key)

def redis_hash():
    pass

def check_session(session_id):
    result = redis_str(session_id)
    if result:
        return result
    return False

 

(2)login_and_pay.py

import flask
import tools
import json
import time
import uuid
server = flask.Flask(__name__)

# 登錄接口
@server.route('/api/login',methods=['post','get'])
def login():
    username = flask.request.values.get('username','')
    password = flask.request.values.get('password','')
    if username.strip() and password.strip():
        p = tools.my_md5(password)
        query_sql = 'select * from app_myuser where username="%s" and password ="%s";'%(username,p)
        user_result = tools.execute_sql(query_sql)
        if user_result:
            session_str = '%s%s%s'%(username,time.time(),uuid.uuid4())
            session_id = tools.my_md5(session_str)
            user_id = user_result.get('id')
            user_result.get('username')
            tools.redis_str(session_id,'{"userid":%s,"username":"%s"}' % (user_id,username) ,600)
            return json.dumps({'code':'0','msg':'登錄成功!','sessionid':session_id},ensure_ascii=False)
        else:
            return json.dumps({'code':'-1','msg':'輸入的用戶名/密碼錯誤!'})
    else:
        return json.dumps({'code':'-1','msg':'不能為空!'})

# 支付接口
@server.route('/pay',methods=['post','get'])
def pay():
    sessionid = flask.request.values.get('sessionid','')
    money = float(flask.request.values.get('money'))
    session = tools.check_session(sessionid)
    if session:
        user = json.loads(session)
        user_id = user.get('user_id')
        sql = 'select balance from app_myuser where id = %s;' % user_id
        balance = tools.execute_sql(sql).get('balance')
        if balance >= money:
            update_money = 'update app_myuser set balance = balance - %s where id = %s;' %(money,user_id)
            tools.execute_sql(update_money)
            return json.dumps({'code':0, 'msg':'支付成功!'},ensure_ascii=False)
        else:
            return json.dumps({'code':-1, 'msg':'余額不足!'},ensure_ascii=False)
    else:
        return json.dumps({'code': -1, 'msg': '請重新登錄!'},ensure_ascii=False)

if __name__=='__main__':
    server.run(host='0.0.0.0',port=8888,debug=True)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM