python - liamlamth/blog GitHub Wiki
Offline Python Package
- Download package and dependencies in a computer that can connect to the Internet
pip download python-dateutil - Upload to the offline server and Install
pip3 install python_dateutil-2.8.2-py2.py3-none-any.whl
Logging
import logging
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S',
filename="/home/oracle/liam/import.log"
)
try:
if True:
logging.info("Succeeded")
else:
raise Exception("invalid syntax!")
except Exception as Argument:
logging.exception("Failed")
Oracle Database
pip install oracledb-1.2.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl --no-deps-
import os import oracledb os.putenv('ORACLE_HOME','/u01/app/oracle/product/19.0.0/dbhome_1') os.putenv('LD_LIBRARY_PATH','$LD_LIBRARY_PATH:$ORACLE_HOME/lib') os.putenv('PATH','$PATH:$ORACLE_HOME/bin') oracledb.init_oracle_client() connection = oracledb.connect(user="liam", password="abcd1234", dsn="192.168.1.100/hkdb.local") connection.autocommit = False cur = connection.cursor() -
sqlTxt = 'INSERT INTO current(colA)\ values(:A1)' cur.executemany(sqlTxt, [(x,) for x in nameList]) sqlTxt = 'INSERT INTO current(colA, colB, colC)\ values(:A1, :A2, :A3)' cur.executemany(sqlTxt, [x for x in nameList]) cur.execute("""INSERT INTO current(colA) values(:A1)""", [nameList[0]]) connection.commit()
Mailbox
import smtplib import email from email.header import decode_header username = "[email protected]" password = "P@ssw0rd" imap_server = "192.168.1.200" imap = imaplib.IMAP4_SSL(imap_server) imap.login(username, password) status, messages = imap.select("INBOX") N = 10 messages = int(messages[0]) for i in range(messages, messages-N, -1): # fetch the email message by ID if i == 0: break res, msg = imap.fetch(str(i), "(RFC822)") if 'attachment_content' in globals(): del attachment_content # remove flag from message which was recovered from recycle bin imap.store(str(i).encode(), "-FLAGS", "\\Deleted") for response in msg: if isinstance(response, tuple): # parse a bytes email into a message object msg = email.message_from_bytes(response[1]) subject, encoding = decode_header(msg["Subject"])[0] if isinstance(subject, bytes): subject = subject.decode(encoding) From, encoding = decode_header(msg.get("From"))[0] if isinstance(From, bytes): From = From.decode(encoding) if any(rcpt == From for rcpt in tgt_rcpts): if msg.is_multipart(): for part in msg.walk(): content_disposition = str(part.get("Content-Disposition")) if "attachment" in content_disposition: filename = part.get_filename() if decode_header(filename)[0][1] is not None: filename = decode_header(filename)[0][0].decode(decode_header(filename)[0][1]) attachment_content = part.get_payload(decode=True) else: content_disposition = str(msg.get("Content-Disposition")) if "attachment" in content_disposition: filename = msg.get_filename() if decode_header(filename)[0][1] is not None: filename = decode_header(filename)[0][0].decode(decode_header(filename)[0][1]) attachment_content = msg.get_payload(decode=True) imap.store(str(i).encode(), "+FLAGS", "\\Deleted")
import imaplib sendserver = smtplib.SMTP(imap_server) send_msg = """\ Subject: Import Failed To: """ + <[email protected]> + """ please contact DBA for further diagnostic """ sendserver.sendmail("[email protected]", "<[email protected]>", send_msg)
If Condition
- true if match any element of the list
tgt_rcpts = ["[email protected]","[email protected]"] if any(rcpt == From for rcpt in tgt_rcpts):
import re
- extract string if match pattern
senderName = re.search('(.)@.', From).group(1).upper() - ture if match pattern
if re.compile('.csv$').search("attach.csv"): - true if match any of the patterns
if re.compile('(?:.xls|.xlsx)$').search("attach.xlsx"):