Note: These examples use Python 3.x, not Python 2.x. Unless you're stuck with some legacy system, you shouldn't use 2.x.
Setting up ConfigParser
First, create a configuration.txt
file. (and always make sure to either globally add this to your .gitignore
file or do it in the current project!)
[example]
API_KEY=foo
Now you can use it in your programs:
import configparser
config = configparser.ConfigParser()
config.read('configuration.txt')
api_key = config['example'].get('API_KEY')
Slugify a String
Use the python-slugify
package:
$ pip install python-slugify
Now you can use it:
>>> import slugify
>>> slugify.slugify("Thé h@ppy dog went ~ and came back!")
the-h-ppy-dog-went-and-came-back
Set up Jinja2 Template Rendering
A number of configuration options need to be set and I have to look them up all the time.
import arrow
import jinja2
# Set up the template engine
template_loader = jinja2.FileSystemLoader('./templates')
template_env = jinja2.Environment(loader=template_loader)
template_env.filters['fmt_date'] = lambda v: arrow.get(v, fmt).format(fmt)
# Write the file
template = template_env.get_template('template.html')
html = template.render(data={})
pathlib.Path('index.html').write_text(html)
Combine Two Equal-Sized Lists into a Dictionary
I use this all the time when working with CSV files.
>>> list1 = ["Column A", "Column B", "Column C"]
>>> list2 = ["Value 1", "Value 2", "Value 3"]
>>> dict(zip(list1, list2))
{'Column B': 'Value 2', 'Column C': 'Value 3', 'Column A': 'Value 1'}
Configuring Argparse
import argparse
import arrow
import pathlib
def valid_date_arg(value):
""" Used by argparser to validate date arguments """
try:
return arrow.get(value, 'YYYY-MM-DD')
except arrow.parser.ParserError:
msg = f'Not a valid date in YYYY-MM-DD format: "{value}"'
raise argparse.ArgumentTypeError(msg)
def valid_filepath_arg(value):
""" Used by argparse to see if a file exists """
filepath = pathlib.Path(value)
if not filepath.exists():
msg = f'File "{arg}" does not exist'
raise argparse.ArgumentTypeError(msg)
else:
return filepath
def valid_dir_arg(value):
""" Used by argparse to see if a directory exists """
filepath = pathlib.Path(value)
if not filepath.exists() or not filepath.is_dir():
msg = f'Directory "{arg}" does not exist'
raise argparse.ArgumentTypeError(msg)
else:
return filepath
# Read command-line arguments
argparser = argparse.ArgumentParser()
argparser.add_argument('date', type=valid_date_arg)
argparser.add_argument('directory', type=valid_dir_arg)
args = argparser.parse_args()
Arrow Time Formatting
Here are all the formats you use when formatting an Arrow
object:
>>> import arrow
>>> arrow.now().format('YYYY-MM-DD')
Token | Output | |
---|---|---|
Year | YYYY | 2000, 2001, 2002 ... 2012, 2013 |
YY | 00, 01, 02 ... 12, 13 | |
Month | MMMM | January, February, March |
MMM | Jan, Feb, Mar | |
MM | 01, 02, 03 ... 11, 12 | |
M | 1, 2, 3 ... 11, 12 | |
Day of Year | DDDD | 001, 002, 003 ... 364, 365 |
DDD | 1, 2, 3 ... 364, 365 | |
Day of Month | DD | 01, 02, 03 ... 30, 31 |
D | 1, 2, 3 ... 30, 31 | |
Do | 1st, 2nd, 3rd ... 30th, 31st | |
Day of Week | dddd | Monday, Tuesday, Wednesday |
ddd | Mon, Tue, Wed | |
d | 1, 2, 3 ... 6, 7 | |
ISO week date | W | 2011-W05-4, 2019-W17 |
Hour | HH | 00, 01, 02 ... 23, 24 |
H | 0, 1, 2 ... 23, 24 | |
hh | 01, 02, 03 ... 11, 12 | |
h | 1, 2, 3 ... 11, 12 | |
AM / PM | A | AM, PM, am, pm |
a | am, pm | |
Minute | mm | 00, 01, 02 ... 58, 59 |
m | 0, 1, 2 ... 58, 59 | |
Second | ss | 00, 01, 02 ... 58, 59 |
s | 0, 1, 2 ... 58, 59 | |
Sub-second | S... | 0, 02, 003, 000006, 123123123123 |
Timezone | ZZZ | Asia/Baku, Europe/Warsaw, GMT |
ZZ | -07:00, -06:00 ... +06:00, +07:00, +08, Z | |
Z | -0700, -0600 ... +0600, +0700, +08, Z | |
Seconds Timestamp | X | 1381685817, 1381685817.915482 |
ms or µs Timestamp | x | 1569980330813, 1569980330813221 |
Simple Logging
I wrote a simple logging wrapper to simplify setting up logging in a project: https://github.com/greencoder/ezlogs
$ pip install ezlogs
Example usage:
import ezlogs
logger = ezlogs.Logger(file_name='log.txt', console_level='debug', file_level='info')
logger.info('This is an informational message')
logger.debug('This is a debugging message')