python-linux win 写文件 zip加密 发现U盘获取路径 解压zip文件 pdf形式返回 连接sql
1. 判断当前:是 linux or windows
def is_linux(): # linux系统 if os.name == "posix": return True else: return False
2. 写文件txt
# 写文件 txt def write_content_txt(store_data_path, con_name, content): path = store_data_path + os.sep + con_name + ".txt" with open(path, mode='w', encoding="utf-8") as filename: filename.write(content)
3. 写文件zip nopass
import gzip
# 写文件 zip nopass def write_content_zip_nopasswd(store_data_path, con_name, content): path = store_data_path + os.sep + con_name + ".zip" with gzip.open(path, "wt") as f: f.write(content)
4. 写文件zip passwd 不管用
import zipfile
# 写文件 zip passwd passwd 不管用 def write_content_zip_passwd(store_data_path, con_name, content): # 先写成txt文件 write_content_txt(store_data_path, con_name, content) # 再写成zip文件 txt_path = store_data_path + os.sep + con_name + ".txt" zip_path = store_data_path + os.sep + con_name + ".zip" passwd = settings.FILE_ZIP_PASSWORD with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as myzip: myzip.write(txt_path, arcname=con_name + ".txt") # myzip.setpassword(b'sy123') myzip.setpassword(bytes(passwd, encoding="utf8")) # 不起作用 # 再删除txt文件 if os.path.exists(txt_path): os.remove(txt_path)
5. 写文件zip passwd 管用
import pyminizip
# 写文件 zip passwd passwd 管用 def write_content_zip_passwd_2(store_data_path, con_name, content): # 先写成txt文件 write_content_txt(store_data_path, con_name, content) # 再写成zip文件 txt_path = store_data_path + os.sep + con_name + ".txt" zip_path = store_data_path + os.sep + con_name + ".zip" pyminizip.compress(txt_path, "", zip_path, settings.FILE_ZIP_PASSWORD, 1) # 再删除txt文件 if os.path.exists(txt_path): os.remove(txt_path)
6. 发现U盘,获取路径
# 发现U盘,获取路径. def usb_path(): # windows系统 if os.name == "nt": disk_list = psutil.disk_partitions() print("windows:%s" % disk_list) logger.info("windows:%s" % disk_list) u_path = [disk.device for disk in disk_list if disk.opts == 'rw,removable'] if u_path: print("windows:%s" % u_path[0]) logger.info("windows:%s" % u_path[0]) return u_path[0] else: print("windows没有发现U盘.") logger.info("windows没有发现U盘.") return "" # linux系统 elif os.name == "posix": import pyudev context = pyudev.Context() print("linux:%s" % context) logger.info("linux:%s" % context) removable = [device for device in context.list_devices(subsystem='block', DEVTYPE='disk') if device.attributes.asstring('removable') == "1"] print("linux:%s" % removable) logger.info("linux:%s" % removable) for device in removable: partitions = [device.device_node for device in context.list_devices(subsystem='block', DEVTYPE='partition', parent=device)] print("linux:%s" % partitions) logger.info("linux:%s" % partitions) for p in psutil.disk_partitions(): if p.device in partitions: print("linux:%s" % p.mountpoint) logger.info("linux:%s" % p.mountpoint) return p.mountpoint + os.sep else: print("不支持除了windows linux的其它操作系统.") logger.info("不支持除了windows linux的其它操作系统.") return ""
7. 解压文件
# 解压文件 def unzip_file(store_data_path): unzip_target_path = os.path.join(store_data_path, "temp") # 先删除,在解压 if os.path.exists(unzip_target_path): shutil.rmtree(unzip_target_path) # 开始解压 if os.path.exists(store_data_path): print(store_data_path) files = os.listdir(store_data_path) print(files) for f in files: file_path = os.path.join(store_data_path, f) print("解压文件路径:%s" % file_path) logger.info("解压文件路径:%s" % file_path) if os.path.isfile(file_path): print("发现了要解压的zip文件.:%s" % file_path) logger.info("发现了要解压的zip文件.:%s" % file_path) zip_file = zipfile.ZipFile(file_path, 'r') zip_list = zip_file.namelist() print("zip_list:%s" % zip_list) logger.info("zip_list:%s" % zip_list) for file in zip_list: print("file: %s" % file) # file = file.encode('utf-8').decode('utf-8') unzip_file_path = Path( zip_file.extract(file, unzip_target_path, pwd=settings.FILE_UNZIP_PASSWORD.encode("utf-8"))) # unzip_file_path.rename(unzip_target_path + os.sep + file.encode('cp437').decode('gbk')) print("unzip_file_path: %s " % unzip_file_path) logger.info("unzip_file_path: %s " % unzip_file_path) zip_file.close() else: print("解压文件路径,不是文件.%s" % file_path) else: print("开始解压,发现没有路径. %s" % store_data_path) return unzip_target_path
8. 读取解压后的文件,pdf形式返回
# 读取解压后的文件 def read_unzip_file(unzip_target_path): if os.path.exists(unzip_target_path): print("解压文件存在:%s" % unzip_target_path) logger.info("解压文件存在:%s" % unzip_target_path) files = os.listdir(unzip_target_path) for f in files: file_path = os.path.join(unzip_target_path, f) print("要解压包的文件路径:%s" % file_path) logger.info("要解压包的文件路径:%s" % file_path) return unzip_file_down(file_path, unzip_target_path) else: print("解压后要读取的文件,没有.%s" % unzip_target_path) return HttpResponse("解压后文件不存在.") # 读取解压后的文件 def unzip_file_down(file_path, unzip_target_path): c = "" try: with open(file_path, "rb") as f: # with open(file_path, encoding="utf-8") as f: # with open(file_path, encoding="gbk") as f: # with open(file_path, encoding="gb18030", errors="ignore") as f: c = f.read() # logger.info("解压后文件内容: %s" % c) except Exception as e: print("读取解压后的文件,发生异常.%s" % e) logger.error("读取解压后的文件,发生异常.%s" % e) # 删除解压后的文件 unzip_file_delete(unzip_target_path) resp = HttpResponse(c) resp.__setitem__('Content-Type', 'application/PDF') # 设置响应头为pdf,浏览器以pdf形式展现 # resp.__setitem__("Content-Disposition", "attachment") # 相当于浏览器下载 return resp
# 删除,解压后的文件.
def unzip_file_delete(unzip_target_path):
if os.path.exists(unzip_target_path):
print("要删除的解压后的文件,存在.path:%s" % unzip_target_path)
logger.info("要删除的解压后的文件,存在.path:%s" % unzip_target_path)
shutil.rmtree(unzip_target_path)
9. 连接mysql sqlite
import pymysql import sqlite3 from django.conf import settings def connect_db(): print("连接到sqlite3服务器") # print("连接到mysql服务器") # db = pymysql.Connect(host=settings.MYSQL_HOST, # port=settings.MYSQL_PORT, # user=settings.MYSQL_USER, # password=settings.MYSQL_PASSWORD, # database=settings.MYSQL_DATABASE, # charset=settings.MYSQL_CHARSET) db = sqlite3.connect("/home/test/bj/drug_storage.db") return db # 插入数据库 def insert_drug_db(db, drug_name, approval_number, batch_number, content_name): cursor = db.cursor() sql = "insert into drug_data(drug_name,approval_number,batch_number,content_name) values ('%s','%s','%s','%s')" data = (drug_name, approval_number, batch_number, content_name) try: cursor.execute(sql % data) db.commit() print("成功插入: %s 条数据. drug_name:%s approval_number:%s batch_number:%s content_name:%s " % ( cursor.rowcount, drug_name, approval_number, batch_number, content_name)) except Exception as e: print("插入数据,失败.%s" % e) db.rollback() # 根据条件判断,药数据是否存在 def is_exist_db(db, drug_name, approval_number, batch_number, content_name): cursor = db.cursor() sql = "select count(*) from drug_data where drug_name = '%s' and approval_number = '%s' and batch_number = '%s' and content_name = '%s'" data = (drug_name, approval_number, batch_number, content_name) try: cursor.execute(sql % data) res = cursor.fetchall() for row in res: count = row[0] return count except Exception as e: print("判断是否存在,失败.%s" % e) # 根据条件判断,药数据是否存在 def is_exist_db_batch(db, drug_name, approval_number, batch_number): cursor = db.cursor() sql = "select count(*) from drug_data where drug_name = '%s' and approval_number = '%s' and batch_number = '%s'" data = (drug_name, approval_number, batch_number) try: cursor.execute(sql % data) res = cursor.fetchall() for row in res: count = row[0] return count except Exception as e: print("判断是否存在,失败.%s" % e) # 查询药数据 def query_drug_db(db, skip, take): cursor = db.cursor() sql = "select distinct drug_name, approval_number from drug_data order by create_time desc limit %d,%d " data = (skip, take) try: cursor.execute(sql % data) res = cursor.fetchall() return res except Exception as e: print("查询药品信息,失败.%s" % e) # 查询药数据,count def query_drug_count_db(db): cursor = db.cursor() sql = "select count(*) from (select distinct drug_name, approval_number from drug_data) a" try: cursor.execute(sql) res = cursor.fetchall() for row in res: count = row[0] return count except Exception as e: print("查询药品信息count,失败.%s" % e) # 关闭数据库 def close_db(db): db.close()
def main():
return
# db = connect_db()
# query_drug_like_db(db, '我', '', 0, 10)
# close_db(db)
if __name__ == '__main__':
main()