Python code snippets

CLI input selection for an option

# select option in cli
print("1 - pass")
print("2 - fail")
print("3 - converted")
 
selection = input("Please select an option:- ")
print(selection)

Case statement

# path = 'pass'
path = 'fail'
 
match path:
    case 'pass':
        route = 'pass'
    case 'fail':
        route = 'fail'
    case _:
        route = 'not defined'
 
print(route)

Dictionary.get method

table_name = {'Parameter': {'Name': 'DynamoTableName', 'Type': 'String', 'Value': 'DB-development', 'ARN': 'arn:aws:ssm:eu-west-2:123456789:DynamoTableName', 'DataType': 'text'}}
 
# Just reference the Dictionary Value
value = table_name['Parameter']['Value']
print("Value is:- ", value)
 
 
# Use two .get methods to dig into nested dictionary
testval = table_name.get('Parameter').get('Value')
print("Test Val:-", testval)

Gives:-

Value is:- DB-development
Test Val:- DB-development

Read in file, line by line

Read in the first line to set line to a true value, then iterate until line is false:-

with open('mytext.txt') as file:
    line = file.readline()
    while line:
        print(line, end='')
        line = file.readline()
        

Copy Binary file

Text mode (t) is the default, use b to do a binary (bytes) copy:-

with open('logo.jpg', 'rb') as readf:
    with open('logo_new.jpg', 'wb') as writef:
        for b in readf:
            writef.write(b)

Working with Datetime

Rounding to seconds by replacing microseconds and adding integer to datetime with timedelta:-

app.config['SESSION_COOKIE_LIFETIME'] = 120
 
cookie_expiry = datetime.now().replace(microsecond=0) + timedelta(seconds=app.config['SESSION_COOKIE_LIFETIME'])
> DESCRIBE user_model;
+------------------+--------------+------+-----+---------------------+----------------+
| FIELD            | TYPE         | NULL | KEY | DEFAULT             | Extra          |
+------------------+--------------+------+-----+---------------------+----------------+
| id               | INT(11)      | NO   | PRI | NULL                | AUTO_INCREMENT |
| user_id          | VARCHAR(255) | NO   | UNI | NULL                |                |
| date_last_update | TIMESTAMP    | YES  |     | CURRENT_TIMESTAMP() |                |
| login_status     | tinyint(1)   | NO   |     | NULL                |                |
| cookie_expiry    | TIMESTAMP    | NO   |     | 0000-00-00 00:00:00 |                |
+------------------+--------------+------+-----+---------------------+----------------+
5 ROWS IN SET (0.001 sec)

Select rows where timestamp is in the past:-

SELECT * FROM `user_model` WHERE `cookie_expiry` < NOW();
 
python/python-code.txt · Last modified: 10/07/2023 21:22 by andrew