python基础篇 28-flask requests redis练习例子
练习1:下载qq头像 并按照昵称保存文件
import os import requests import traceback def send_post(url,data,headers): try: res = requests.post(url=url,data=data,headers=headers) except: print('出错啦:',traceback.format_exc()) else: return res def send_get(url,params=None,): try: if params is None: res = requests.get(url) else: res = requests.get(url=url,params=params) except: print('出错啦:', traceback.format_exc()) else: return res def get_qq_info(qq_num,start_pos,end_pos): url = "https://qun.qq.com/cgi-bin/qun_mgr/search_group_members" datas = {'gc':qq_num,'st':start_pos,'end':end_pos,'sort':0,'bkn':'908067828'} headers = {'cookie': 'pgv_pvid=5284751738; pgv_pvi=7055712256; RK=9LYE+p0vXY; ptcz=6b4f7b74985e2b0503ec47e595c6f8ecd6a924750c1797519296d77daafbf4be; ptui_loginuin=710070208@qq.com; _qpsvr_localtk=0.030382900950044922; uin=o0710070208; p_uin=o0710070208; traceid=55193b3158; skey=@0EUafJQNu; pt4_token=jPC3pE9-RGBR5halSjoVvsn1Rd6zriSZIfSXmMh86Zg_; p_skey=JRWOrwSpC3rwpJR43zvKHCOZxxptpKOfCrRNiLxcgaE_'} res = send_post(url=url,data=datas,headers=headers) return res def download_pic(url,dir_name,file_name): if not os.path.exists(dir_name): os.mkdir(dir_name) file_path = os.path.join(dir_name,file_name) res = send_get(url=url) with open(file_path,'wb') as fw: fw.write(res.content) print(f"下载文件{file_name}成功!") def main(qq_num,dir_name): # start_pos = 0 # end_pos = 20 # while True: # res = get_qq_info(qq_num,start_pos,end_pos) # datas = res.json() # mems = datas.get('mems') # count = datas.get('count') # # print(count) # for mem in mems: # qq_id = mem.get('uin') # qq_name = mem.get('card') if mem.get('card') else mem.get('nick') # qq_name = '傻叉' if qq_name == '*' else qq_name # qq_name = qq_name + '.jpg' # url = f"https://q4.qlogo.cn/g?b=qq&nk={qq_id}&s=140" # download_pic(url,dir_name,qq_name) # if end_pos > count: # break # start_pos += 21 # end_pos += 21 for step in range(0,201,21): res = get_qq_info(qq_num, 0+step, 20+step) datas = res.json() if 'mems' in datas: mems = datas.get('mems') # count = datas.get('count') # # print(count) for mem in mems: qq_id = mem.get('uin') qq_name = mem.get('card') if mem.get('card') else mem.get('nick') qq_name = '傻叉' if qq_name == '*' else qq_name qq_name = qq_name + '.jpg' url = f"https://q4.qlogo.cn/g?b=qq&nk={qq_id}&s=140" download_pic(url, dir_name, qq_name) else: print("没有获取到群信息;") break if __name__ == '__main__': main('1078641913',r'D:\python高级编程\tmz2020\day7\qq_download')
练习2:
"""
需求:
2、写接口
1、登录接口,登录成功之后返回sessionid:xxx
当前时间戳+username,做md5,生成sessionid,seesion过期时间,自己定义
redis里面存进入seesionid,xxxxxxxx:userid, time
2、支付接口
table
userid money
1 200
/pay?sessionid=xxxxx&money=90
sessionid 是否失效
"""
import time import uuid import flask from flask import jsonify import tools server = flask.Flask(__name__) redis_conf ={ 'host':'192.168.64.128', 'password':'Aa123456', 'db':'0', 'port':6379, 'decode_responses':True # 自动将bytes转换为 string 类型 } op_redis = tools.Ope_Redis(redis_conf) @server.route('/login',methods=['post','get']) def login(): username = flask.request.values.get('username') password = flask.request.values.get('password') username = username.strip() password = password.strip() if username and password: sql = f"select * from subscriber where username = '{username}'and is_delete=0;" if tools.execute_sql(sql): sql_p = f"select * from subscriber where username ='{username}' and is_delete=0;" datas = tools.execute_sql(sql_p,only=True) pwd = datas.get('password') p = tools.my_md5(password) if p == pwd: userid = datas.get('id') sessionid = tools.my_md5(str(time.time()) + username +str(uuid.uuid4())) op_redis.set_key(sessionid,userid,3*60) op_redis.p_execute() return jsonify({'code': 0, 'msg': '用户%s登陆成功!' %username,'sessionid':sessionid}) else: return jsonify({'code': -1, 'msg': '密码不对!'}) else: return jsonify({'code': -1, 'msg': '用户%s不存在!' % username}) else: return jsonify({'code': -1, 'msg': '必填参数不能为空!'}) @server.route('/reg',methods=['post','get']) def reg(): username = flask.request.values.get('username').strip() password = flask.request.values.get('password').strip() cpassword = flask.request.values.get('cpassword').strip() if username and password and cpassword: if password != cpassword: return {'code':-1,'msg':'两次输出的密码不一致!'} else: query_sql = f"select * from subscriber where username ='{username}' and is_delete=0;" if tools.execute_sql(query_sql): return {'code':-1,'msg':'用户%s已经存在' %username} else: p = tools.my_md5(password) insert_sql = f"insert into subscriber(username,password) values ('{username}','{p}');" tools.execute_sql(insert_sql) if tools.execute_sql(query_sql): return {'code':0,'msg':'注册用户%s成功' %username} else: return {'code':-1,'msg':'必填参数不能为空'} @server.route('/pay',methods=['post','get']) def pay(): values = flask.request.values sessionid = values.get('sessionid','') money = values.get('money') userid = op_redis.get_key(sessionid) if userid: sql = f"select * from t_balance where userid = '{userid}';" query_datas = tools.execute_sql(sql,only=True) total_money = query_datas.get('money') balance = float(total_money) - float(money) if balance >=0: update_sql = f"update t_balance set money='{balance}' where userid = '{userid}';" tools.execute_sql(update_sql) return jsonify({'code':0,'msg':'支付成功!余额为%s' %balance}) else: return jsonify({'code':-1,'msg':'余额不足,请充值!'}) else: return jsonify({'code':-1,'msg':'登录会话超时,请重新登录!'}) server.config['JSON_AS_ASCII'] = False #配置支持返回中文 server.run(host='0.0.0.0',port=8999,debug=True)