• Python操作Excel, 开发和调用接口,发送邮件


    接口开发:
    import flask
    import tools
    import json,redis
    import random
    
    server = flask.Flask(__name__)
    #新建一个服务,把当前这个python文件当做一个服务
    
    ip = '118.24.3.40'
    password='HK139bc&*'
    r = redis.Redis(host=ip,password=password,port=6379,db=10,
                    decode_responses=True)#连接redis
    
    #登录接口
    @server.route('/login',methods=['get']) 
    def hello():
        uname = flask.request.values.get('username')
        pd = flask.request.values.get('passwd')
        # sql = 'select * from app_myuser where username="%s"'%uname
        # res = tools.my_db(sql)
        key='nhy:%s'%uname
        res = r.get(key)
        if res:
            res = json.loads(res)
            if tools.my_md5(pd) == res.get('passwd'):
                res = {"code":0,"msg":"登录成功!"}
            else:
                res = {"code":1,"msg":"密码错误!"}
        else:
            res = {'code':2,"msg":"用户不存在"}
        return json.dumps(res,ensure_ascii=False,indent=4)
    
    #注册接口
    @server.route('/reg',methods=['post'])
    def reg():
        uname = flask.request.values.get('username')
        pd = flask.request.values.get('passwd')
        cpd = flask.request.values.get('cpwd')
        key='nhy:%s'%uname
        res = r.get(key)
        if res:
            res = {'code': 2, "msg": "用户已存在"}
        else:
            md5_password  = tools.my_md5(pd)
            res = {'id':random.randint(100,9999),'username':uname,'passwd':md5_password,'is_admin':1}
            r.set('nhy:%s'%uname,json.dumps(res))#
            res = {"code":0,"msg":"注册成功!"}
        return json.dumps(res,ensure_ascii=False,indent=4)
    
    #查询信息接口
    @server.route('/api/stu')
    def get_stu():
        username = flask.request.values.get('name')#默认get不到的话,返回的值就是None
        age = flask.request.values.get('age')
        if username and age:
            sql = "select * from app_student where name='%s' and age='%s'" % (username, age)
        elif not username and age:
            sql = "select * from app_student where age='%s'" % age
        elif username and not age:
            sql = "select * from app_student where name='%s'" % username
        else:
            sql = "select * from app_student"
        res = tools.my_db2(sql)
        return json.dumps(res,ensure_ascii=False,indent=4)
    
    server.run(host='0.0.0.0',port=8999,debug=True)
    #ip:8000/login
    #127.0.0.1
    牛刀小试:
    1. 传入一个数据库中的表名,然后把表里的数据导出到excel里面

    写excel xlwt
    连接数据库 pymysql

    思路:
    1、连接上数据库,写好 sql ='select * from %s;'%table_name
    2、获取到数据 [[id name passwd is_admin] [1,nhy,xdfsdfsd,1],[2,nhy2,xdfsdfsd,1] ]
    3、循环写入excel
    4、写表头 hhh

    import pymysql,xlwt
    conn = pymysql.connect(host='118.24.3.40',user='jxz',password='123456',db='jxz')
    cur = conn.cursor()
    table_name = input('请输入你要导出的表名:').strip()
    cur.execute('select * from %s;'%table_name)
    res = list(cur.fetchall())
    fields = [ field[0] for field in cur.description ]
    # cur.description获取到表结构
    res.insert(0,fields)
    book = xlwt.Workbook()
    sheet = book.add_sheet('sheet1')
    for index,value in enumerate(res):
        for index2,v2 in enumerate(value):
            sheet.write(index,index2,v2)
    book.save('%s.xls'%table_name)
    cur.close()
    conn.close()

    2. 获取到数据库里面的数据
    {'username':'lyl','password':xxx,'id':111,'addr':'xxx'}
    然后存到redis里面
    set(lyl,{'username':'lyl','password':xxx,'id':111,'addr':'xxx'})
    get(key)

    import pymysql,redis,json
    conn = pymysql.connect(host='118.24.3.40',user='jxz',password='123456',db='jxz')
    cur = conn.cursor(pymysql.cursors.DictCursor)
    cur.execute('select * from app_myuser;')
    data = cur.fetchall()
    cur.close()
    conn.close()
    ip = '118.24.3.40'
    password='HK139bc&*'
    r = redis.Redis(host=ip,password=password,port=6379,db=10,
                    decode_responses=True)#连接redis
    for d in data:
        # {'username':'lyl','password':xxx,'id':111,'addr':'xxx'}
        key = 'nhy:%s'%d.get("username")
        r.set(key,json.dumps(d))
    
    
    fw = open('a.txt','w',encoding='utf-8')
    fw.write('时代峰峻圣诞节疯狂楼上的房间考虑到双方就上课了的房间开连锁店是的范德萨')
    fw = open('b.txt','w',encoding='gbk')
    fw.write('时代峰峻圣诞节疯狂楼上的房间考虑到双方就上课了的房间开连锁店是的范德萨')
    import chardet
    f= open('b.txt','rb')
    res = f.read()
    print(chardet.detect(res))
    print(res.decode('gbk'))
    python utf-8 gbk GB2312字符集
    1121 牛

    发送邮件:需要安装,pip install yagmail
    import yagmail
    username='uitestp4p@163.com'
    password='houyafan123'#生成授权码,qq、163、126都是授权码
    
    mail_server = 'smtp.163.com'
    # mail_server = 'smtp.qq.com'
    # mail_server = 'smtp.126.com'
    
    m = yagmail.SMTP(user=username,password=password,host=mail_server)
                # smtp_ssl=True,如果邮箱使用了安全协议,就需要加这个
                #qq邮箱就是使用了安全协议
    
    to = ['1137944722@qq.com','wangmei416516@163.com','511402865@qq.com']
    cc = ['61378317@qq.com','1196842722@qq.com','1365834704@qq.com']
    
    m.send(to=to,cc=cc,subject='今天吃了吗',
           contents='今天吃鱼肉了吗,吃饱没',
           attachments=r'tools.py')

    发送网络请求:
    1. 用标准库:
    from urllib.request import urlopen #python自带的,不好用,只需了解。urllib可以发送网络请求,urlopen可以发送接口请求
    from urllib.parse import urlencode #用于post接口请求,urlencode可以把json字符串转化成k=v形式
    
    #评语:这个模块要求类型,二进制换来换去,很麻烦。
    
    #功能:get url request
    url='http://127.0.0.1:8999/api/login?username=testuser1&passwd=111111'
    res = urlopen(url) #发送接口请求
    print(res.read().decode()) #read获取请求返回内容,但返回二进制数据,所以再decode一下。
    
    #功能:post url request
    url='http://127.0.0.1:8999/api/login'
    data = {'username':'testuser1','passwd':'111111'}
    s = urlencode(data) #把字典变成k=v形式,username=testuser1,passwd=111111
    #注:‘username=testuser1,passwd=111111’,是个字符串,encode()后,变为b'username=testuser1,passwd=111111'
    res = urlopen(url,s.encode()) #post请求,第二个参数要求是二进制类型,所以再encode一下
    print(res.read().decode())

    2. pip install requests

    import requests
    import random
    url='http://127.0.0.1:8999/api/upload'
    data = {'username':'testuser1','passwd':'111111'}
    r = requests.get(url,params=data) #发get请求
    r = requests.post(url,data=data) #发post请求
    
    data = {
     "session_id":"6ab8785039dcf50fb11c53acc1db7648",
     "name":"zhouyongbo%s"%random.randint(1,99),
     "phone":"111211345%02d"%random.randint(1,99),
     "grade":"天秤座"
    }
    
    r = requests.post(url,json=data) #入参是json类型的
    
    #上传文件的
    r = requests.post(url,
                data={'session_id':'6ab8785039dcf50fb11c53acc1db7648'},
                files={'file_name':open('account.xls','rb')  }
                )
    
    # 添加header
    requests.get(url,headers={'cookie':'pt2gguin=o0511402865; RK=JQZpwBp1by; ptcz=6c30e26a9ed6be93d3de9e4c4aca3e55650cf99fcffa64729bd1d58a5fb209d9; pgv_pvi=779236352; pgv_pvid=6970909788; qb_qua=; qb_guid=818de686e29d412fa4ee9e99905ea166; Q-H5-GUID=818de686e29d412fa4ee9e99905ea166; NetType=; pgv_si=s4499960832; FTN5K=0138ca95; pgv_info=ssid=s4269564370; luin=o0511402865; uin=o0511402865; lskey=00010000efc2701412d3429029ac9366e4ba98f0e978e0ae4a9c684101a7b22df0695f534bc242c8d4ff386d; skey=@0sHtvhTsD; ptisp=cnc; p_uin=o0511402865; pt4_token=wGU2YAaM0uu7LbcNjuDcLN-TPrEy7AZw4gcL5TEcKxw_; p_skey=1zg7yvF5wr6l43mfr-BvNHxuVDtybKpR5RbCrgC8weQ_'})
    
    requests.get(url,cookies={'pt2ggui':'o0511402865','RK':'JQZpwBp1by'})
    print(r.text) #结果返回的就是字符串
    print(r.json()) #结果返回的就是字典,必须返回的是json,才能转成字典
    
    #下载文件
    url='https://q4.qlogo.cn/g?b=qq&nk=1834364415&s=140'
    url='https://qiniuuwmp3.changba.com/1127063572.mp4'
    r = requests.get(url)
     #返回的就是二进制的
    r.cookies #返回cookie
    r.status_code  #返回的状态码200
    r.content  #可以返回图片、音乐等
    
    f = open('sdfsdf.mp4','wb')
    f.write(r.content) 
    f.close()

    接口返回值处理:
    • json_dic=res.json()  #返回为json格式,直接转成字典
    • str=res.text      #返回为字符串
    • file_content=res.content  #二进制,下载图片、文件时用,可以直接新建文件再保存内容:with open('a.jpg','wb')as f: f.write(r.content)
    • r.cookies        #请求返回的cookie
    • r.status_code     #状态码

    写日志: pip install nnlog
    import nnlog
    nnlog.Logger.words='哈哈哈哈'
    log = nnlog.Logger('book_server.log','warn',when='S',backCount=5) #默认debug级别,自动清理日志,5条就删除
    # debug  打印一些调试信息,非常多
    # info   打印走到哪儿了
    # warning
    # error
    #这一个语句,可以放在需要的地方,比如登录是,将谁在登录写入日志
    log.debug('xxx值是什么')
    log.info('调用了什么xxx')
    log.warning('xx警告!')
    log.error('xxx出错!')

    代码文件:
    tools.py
    import time
    import os
    def timestampToStr(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
        #时间戳转格式化好的时间
        if timestamp:
            time1 = time.localtime(timestamp)
            res = time.strftime(format, time1)
        else:
            res = time.strftime(format)
        return res
    #20180304153958
    def strTotimestamp(str=None,format='%Y%m%d%H%M%S'):
        #格式化的时间转时间戳
        if str:
            timep = time.strptime(str, format)
            res = time.mktime(timep)
        else:
            res = time.time()
        return int(res)
    
    def clean_log(path,day=3):
        print('调用了')
        for cur_path, dirs, files in os.walk(path):
            for file in files:
                if file.endswith('log'):
                    f_time = file.split('.')[0].split('_')[-1]
                    file_timestamp = strTotimestamp(f_time,'%Y-%m-%d')
                    cur_timestamp = strTotimestamp(time.strftime('%Y-%m-%d'),'%Y-%m-%d')
                    if (cur_timestamp - file_timestamp) >= 60*60*24*day:#判断文件的时间是否大于3天
                        os.remove(os.path.join(cur_path,file))
    
    
    import pymysql
    def my_db(sql):
        conn = pymysql.connect(host='118.24.3.40',user='jxz',password='123456',
                        db='jxz',port=3306,charset='utf8',autocommit=True)
        cur = conn.cursor(pymysql.cursors.DictCursor)
        cur.execute(sql)
        res = cur.fetchone() #{'username':'nhy'}  {}
        cur.close()
        conn.close()
        return res
    
    def my_db2(sql):
        conn = pymysql.connect(host='118.24.3.40',user='jxz',password='123456',
                        db='jxz',port=3306,charset='utf8',autocommit=True)
        cur = conn.cursor(pymysql.cursors.DictCursor)
        cur.execute(sql)
        res = cur.fetchall() #{'username':'nhy'}  {}
        cur.close()
        conn.close()
        return res
    
    import hashlib
    def my_md5(s,salt=''):
        s = s+salt
        news = str(s).encode()
        m = hashlib.md5(news)
        return m.hexdigest()
    if __name__ == '__main__':
        #判断如果是在别的文件里面导入这个python文件的话,就不执行下面的代码
        print(strTotimestamp())
        print(clean_log('.'))
        print(clean_log('.',2))
    一个python项目的文件结构:

    1. book_server/: 项目名

    2. conf/:存放配置文件

    3. data/:存放sql文件

    4. lib/: 存放项目的所有源代码。

    5. logs/:存放日志文件

    6. uploads/:存放下载的文件

    7. start.py: 程序启动脚本

    8. readme.txt: 项目说明文件。

  • 相关阅读:
    JavaScript 基础,登录前端验证
    CSS实例:图片导航块
    导航,头部,CSS基础
    web基础,用html元素制作web页面
    web基础
    timestamp与timedelta,管理信息系统概念与基础
    datetime处理日期和时间
    Linux操作系统编程 实验五 块设备实验
    Linux操作系统编程 实验四 字符设备实验
    Linux操作系统编程 实验三 模块编程实验
  • 原文地址:https://www.cnblogs.com/fangfangzhang/p/10166467.html
Copyright © 2020-2023  润新知