16.12.2017 г.

Read excell file with python, validate and return defaultdict

import os
import xlrd
from collections import defaultdict
import sys
from pprint import pprint
import re

'''
Some name1     2345        someemal1@gmail.com
Some name12    23456        someemal2@gmail.com
Some name1    0            someemal1@gmail.com
Some name3    0889345        someemal1@gmail.com
'''

filename = "somefile.xls"
result = defaultdict(list)


def checkFilename(filename):
    '''Check file is excel or not '''
    if filename.endswith('xls'):
        return filename
    else:
        return 'Not valid filename'
        sys.exit()


class ReadXLS:

    def __init__(self, checkFilename):
        self.filename = checkFilename

    def realReadFilename(self):
        '''Read xls file with xlrd module '''
        try:
            workbook = xlrd.open_workbook(self.filename)
        except:
            print("some error...")
            sys.exit()
        else:
            try:
                sheet = workbook.sheet_by_index(0)
            except IndexError as ie:
                print(ie)
                sys.exit()
            else:
                for rowx in range(sheet.nrows):
                    columnmapping = sheet.row_values(rowx)
                    yield columnmapping

    def checkResult(self):
        '''add to result only what i whant'''
        for line in ReadXLS.realReadFilename(self):
            if ((line[0] in (None, '')) or (line[1] in (None, ''))
                    or (line[2] in (None, '')) or not
                    re.search(r'[\w.-]+@[\w.-]+.\w+', line[2])):
                continue
            else:
                #result[line[2].upper()].append((line[0], line[1]))
                result[line[2].upper()].append(
                    (line[1].strip().replace(' ', ''), line[0].strip())
                )

    def __repr__(self):
        ''' Why I can '''
        return "{}".format(self.filename)


if __name__ == '__main__':
    test = ReadXLS(checkFilename(filename))
    test.checkResult()
    pprint(result)

24.09.2017 г.

Python compare data from sqlite database is between two date

#import module
import sqlite3

#database path is here
database = 'test.db'

#Testing in the data
#25.09.2017 27.09.2017
#01.10.2017 03.10.2017

class db_conn:
    ''' Class connect main '''
    def __init__(self, db, Fdata=None, Sdata=None):
        self.db = db
        self.Fdata = Fdata
        self.Sdata = Sdata
        self.con = sqlite3.connect(self.db)

    def insert(self):
        ''' insert into database two value's '''
        self.con.execute("INSERT INTO praznik (Fdata, Sdata) VALUES (?, ?)", (self.Fdata, self.Sdata))
        self.con.commit()
        self.con.close()


    def show_table(self):
        ''' Use for select from database '''
        self.cur = self.con.cursor()
        self.cur.execute("SELECT * from praznik")
        for row in self.cur:
            print("First Data {fdata} - Second Data {sdata}".format(fdata=row[1], sdata=row[2]))
        self.con.close()


    def check_period(self, fdata_check, ldata_check):
        ''' check period is valid or not '''
        self.fdata_check = fdata_check
        self.ldata_check = ldata_check
        self.cur = self.con.cursor()
        self.cur.execute("SELECT * from praznik")
        for row in self.cur:
            if row[1] <= self.ldata_check and row[2] >= self.fdata_check:
                print("Problem")
                break
            else:
                print("Look Good")
                break
        self.con.close()

3.09.2017 г.

Python use picke to write json to faile and read back to dictionary

#import module
from pprint import pprint  # pretiprint
import json
import os
import pickle
# hard code param
test_file = 'test_file.json'
db = {}
dl = {}

def check_file_exists(filename):
    ''' Check file exists or not '''
    if not os.path.exists(filename):
        open(filename, 'w').close()

def write_in_json(filename, db):
    ''' Write dictionary to file with ekstension json'''
    db = json.dumps(db)
    with open(filename, 'wb') as f:
        pickle.dump(db, f)

def load_from_json_file(filename, dl):
    ''' Load serial object into file to dictionary '''
    json_file = open(filename, 'rb')
    dl = pickle.load(json_file)
    dlj = json.loads(dl)
    return dlj

# Get from enywere for test
borko = {'name': 'Borko', 'ip': '192.168.168.1', 'df': 30000, 'free': 'dev'}
sue = {'name': 'Sue Somebody', 'ip': '192.168.168.2', 'df': 40000, 'free': 'hdw'}
tom = {'name': 'Tom Aks', 'ip': '192.168.168.3', 'df': 0, 'free': None}

db['bob'] = borko
db['sue'] = sue
db['tom'] = tom
if __name__ == '__main__':
    # Create file if not exists uncoment to begin
    # check_file_exists(test_file)
    # function write json to file uncoment to begin
    #write_in_json(test_file, db)
    # fuction load picke file to json object return to dictionary
    #print(load_from_json_file(test_file, dl))

14.08.2017 г.

Replace empty space in name with python script

Path = r'C:\Users\Borko - Home\Desktop\TEST\trii'
search_patter = ' '
import os
log_file = 'changes.log'

class Main:

    def __init__(self, Path, search_patter):
        self.Path = Path
        self.search_patter = search_patter
        ''' check if file exists only for me'''
        assert os.path.exists(self.Path) == True

    def search_for_file(self):
        result = []
        for root, firname, filename in os.walk(self.Path):
            for file in filename:
                if self.search_patter in file:
                    result.append(root + '\\' + file)
        return result

    def write_to_log_file(self):
        with open(log_file, 'w') as f:
            for file in Main.search_for_file(self):
                f.write(file + '\n')

    def change_fileName(self):
        for file in Main.search_for_file(self):
            new_filename = os.path.basename(file).replace(' ', '_')
            new_path_name = os.path.dirname(file)
            total_new = new_path_name + '\\' + new_filename
            os.rename(file, total_new)

if __name__ == "__main__":
    progress = Main(Path, search_patter)
    progress.change_fileName()

2.08.2017 г.

Generate random password and send to email with python

#IMOPORT MODULES
import random
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#HARDCORE NAME AND EMAIL
list_with_names = {"First Name": "first_email@abv.bg", "Second Name": "second_email@abv.bg"}
sender = 'unrealborko@gmail.com'
#FUCNTION GENERATE PASSWORD'S
def generate(name):
    choice = "a#@bcdeb1234567890ABCDFEGH"
    ask = random.sample(choice, 8)
    forma = [['@', '#', '!'], [i for i in ('abcdfegh')], [i for i in ('ABCDFEGH')], [i for i in ('1234567890')]]
    while (any(z in forma[0] for z in [i for i in ask])
         and any(z in forma[1] for z in [i for i in ask])
          and any(z in forma[2] for z in [i for i in ask])
        and any(z in forma[3] for z in [i for i in ask])) != True:
        ask = random.sample(choice, 8)
       
    return("Password for {} is {}".format(name, "".join(ask)))

#FUNCTION TO SEND PASSWORD TO NAME EMAIL
def sendmail(from_email, to_addr, subject, message, login, password, name, smtpserver = "smtp.gmail.com", smtpport = 587):
    from_email = from_email
    to_addr = to_addr
    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_addr
    msg['Subject'] = subject
    passsfare = generate(name)
    body = "{}".format(passsfare)
    msg.attach(MIMEText(body, 'plain'))
    server = smtplib.SMTP(smtpserver)
    server.starttls()
    server.login(login, password)
    text = msg.as_string()
    server.sendmail(from_email, to_addr, text)
    server.quit()
#FUNCTION APPLY PASSWORD TO NAME
def password_to_name():
    for name, email in list_with_names.items():
        sendmail(from_email = "sender email is here",
            to_addr = email,
            subject = "Password for {}".format(name),
            message = "This is a password",
            login = "borkounreal@gmail.com",
            password = "userpassword is here!!!!!1",
            name = name)
        #print(generate(name))

if __name__ == "__main__":
    password_to_name()