IC Improve Code Recipes

Appendix E

The Assist Library for Python

This is a .NET book, so a Python appendix needs a reason. Mine is simple: most of the teams I have worked with in the last ten years were not pure .NET shops anymore. The web application and the services were C#, but next to them sat Python: a data team's import scripts, a reporting job somebody wrote in a weekend, an integration that came with a vendor's sample code. Those scripts talked to the same SQL Server databases, read the same encrypted columns and called the same APIs, and they repeated every mistake this book describes, in a second language.

So the Assist library from Appendix D has a Python edition. It is one distribution, improvecode-assist, with one import package, assist, copyright ImproveCode.com. It mirrors the .NET packages area by area, with Python names (query_first instead of QueryFirstOrDefaultAsync), so a team that works in both languages finds the same ideas in the same places. Where the two editions store data, they store it in the same format: a password hash or an encrypted column written by one can be read by the other.

The book's C# listings have also been converted to Python, one file per listing. They are described later in this appendix. The listings show each recipe on its own; the library is the finished, tested version you reference instead of copying.

Installing it

The library needs Python 3.12 or later. Windows is the main target, and most of it also runs on Linux and macOS. Like the .NET packages, it is not on the public index. You get it from ImproveCode.com as a wheel, and either install the wheel directly or upload it to a private package index (Azure Artifacts, a self-hosted devpi or any index that pip can read).

PowerShell
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install .\improvecode_assist-1.0.0-py3-none-any.whl

import assist needs no third-party packages at all. The core, the data helper, logging and CSV run on the standard library alone, plus tzdata on Windows for time zones. Everything else is an optional extra, so a script that only reads SQL Server does not install paramiko, openpyxl and reportlab:

PowerShell
pip install "improvecode_assist-1.0.0-py3-none-any.whl[sqlserver,security]"

If you call code whose extra is missing, the ImportError names the package to install. The extras I use most:

Extra Installs For
sqlserver pyodbc assist.data.sqlserver
oracle oracledb assist.data.oracle
configuration pydantic assist.configuration
keyvault azure-identity, secrets Key Vault settings
security cryptography assist.security
email aiosmtplib the SMTP sender
sftp paramiko assist.io.sftp
excel openpyxl assist.documents.excel
pdf pypdf, reportlab assist.documents.pdf
http httpx assist.http
jobs apscheduler, pywin32 cron and Windows services
all everything development machines

Pin the version in your requirements.txt the same way you pin a NuGet package in a project file, and upgrade it on purpose.

Chapters and packages

Chapter Package What it covers
1 assist.data Db, sessions, mapping, paging, filters
1 assist.data.sqlserver SQL Server through pyodbc
1 assist.data.oracle Oracle through python-oracledb
3 assist.caching Cache-aside, typed keys, Redis
4 assist.logging Rolling files, scopes, masking, runs
5, 8, 15 assist.core Results, retry, guards, dates
6 assist.configuration Layered settings, validation
7 assist.security Passwords, AES-GCM, HMAC, tokens
7 assist.directory_services Active Directory over LDAP
9 assist.email Sender, templates, queue
10 assist.io Safe paths, atomic writes, watcher
10 assist.io.sftp SFTP with a pinned host key
11 assist.documents CSV writer, reader and importer
11 assist.documents.excel Excel export and import
11 assist.documents.pdf Merge, split, stamp, generate
11 assist.documents.word Word templates
11 assist.documents.reporting SSRS rendering over HTTP
12 assist.xml JSON, safe XML, X12, feeds
13 assist.http httpx clients, resilience, tokens
14 assist.jobs Schedules, queues, Windows services
17 assist.geography Points, distances, geocoding

A few .NET packages have no Python twin. There is no FTP package (use SFTP, and if a partner insists on FTPS, the standard library's ftplib covers it), no WCF package, and no Microsoft Graph package; for Entra ID use Microsoft's own msgraph-sdk. Serilog has no twin either: assist.logging builds on Python's standard logging module, and its configure_logging function does the setup job that Assist.Logging.Serilog does in .NET.

The library source also includes a PySide6 desktop application in its samples folder that uses the data, caching, configuration, logging, security, e-mail, document and job packages together.

Each subpackage has a README.md next to its code with a table that names the .NET type behind every Python name. When you know one edition, those tables are the fastest way into the other.

A nightly job, end to end

The first listing is the Python version of the nightly job from Appendix D. It reads the same appsettings.json layout, validates its settings before doing any work, runs one statement in a transaction, writes a rolling log file, and returns an exit code a scheduler can alert on. It uses SQLite so you can run it without a server.

With { "Cleanup": { "DatabasePath": "app.db" } } in appsettings.json next to the script, a run writes two lines to the console and to logs\nightly-<date>.log, both carrying the same run ID (timestamps and levels trimmed here):

Text
nightly: CloseStaleOrders run started {RunId=147e9aa8}
nightly: CloseStaleOrders run finished: 1 items in 0 ms {RunId=147e9aa8}

Run it with --Cleanup:StaleAfterDays=0 and it stops before touching the database, with a message that names the key: Cleanup:StaleAfterDays: Input should be greater than or equal to 1. Configuration keys work as they do in .NET. They are case-insensitive, sections are separated by a colon, and a PascalCase key in the file binds to the snake_case field in the model, so a C# service and a Python script can share one settings file. Environment variables use a double underscore between sections, with one catch I found while testing: Python upper-cases environment variable names on Windows, so a multi-word key needs its snake_case form there. CLEANUP__STALE_AFTER_DAYS reaches the setting; CLEANUP__STALEAFTERDAYS is silently ignored.

The SQL is written with :name markers and a dictionary of values. Values never go into the SQL text; the dialect converts the markers for the driver. To point the same code at SQL Server, install the sqlserver extra and replace the factory with SqlServerConnectionFactory from assist.data.sqlserver, which takes an ODBC connection string and brings its own dialect. Nothing else changes.

Db is synchronous, because DB-API drivers are. The listing hands the work to a worker thread with asyncio.to_thread; for code that is async throughout, AsyncDb wraps a Db and does the same for every call.

Sharing data with .NET

The part of the Python edition I care most about is the part you can't see: the formats. Both editions write the same bytes, and both test suites check the same interoperability vectors. I also checked it by hand while writing this appendix: a value encrypted in Python decrypted in C#, and the other way around, and each side verified the other's password hashes.

  • Password hashes are strings of the form pbkdf2-sha256$600000$<salt>$<hash>, with Base64 salt and hash. PBKDF2-SHA512 hashes use pbkdf2-sha512, and wrapped legacy MD5 or SHA-1 digests carry the old scheme after a plus sign, as in pbkdf2-sha256+md5-utf8. Either side can verify a hash the other wrote, and either side returns "rehash needed" for an old one.
  • Encrypted values use AES-256-GCM. The binary layout is a version byte (2), the key ID, a 12-byte nonce, the 16-byte tag and the ciphertext. String helpers store it as Base64. The context string, such as Customer:42:TaxId, is bound in as UTF-8 associated data, so both sides must use exactly the same context text.
  • Version 1 payloads, the layout of Recipe 7.2 without a key ID, still decrypt on both sides, and needs_reencryption reports them so you can upgrade them in place.
  • Keys are the same 32 bytes, kept in the same configuration shape (Encryption:CurrentKeyId and Encryption:Keys), and should come from the same secret store.

The listing shows the security calls a Python script needs to share a customer table with a C# application:

tax_id_context exists for one reason: the context must match byte for byte on both sides, so I define it once per column and never type it inline. If the C# side writes Customer:42:TaxId and the Python side writes customer:42:taxid, decryption fails, which is the correct behavior and a confusing afternoon.

The legacy path from Appendix D is here too. assist.security.legacy decrypts the old DES, RC2, TripleDES and Rijndael values, reads the old XML key files with load_legacy_key_file, and moves values to AES-GCM with LegacyDataMigrator.reencrypt_string. Every call emits a LegacyCryptoWarning, the Python counterpart of the ASSISTLEGACY001 diagnostic. Two gaps are documented: the cryptography package supports only 128-bit RC2 keys (the old default), and single DES runs as TripleDES with the key repeated three times, which gives the same result.

The converted listings

The book's companion files include a python folder with every C# listing in the book converted to Python 3.12: 281 files, one per listing. Chapter 2 has none, because its listings are T-SQL. The listings are standalone. They don't import assist, so you can read each one next to the page it came from.

The file names point back to the printed book:

Text
p144_r7_2_aes_gcm_encryptor.py
p140_r7_1_md5_password_hash_before.py
  • p144 is the printed page where the original C# listing starts.
  • r7_2 is Recipe 7.2.
  • The rest is a short topic name.
  • A name ending in _before is a "way it's often written" listing. Those files stay faithful to the flawed C#, on purpose, and are not for copying.

In the Kindle edition, where page numbers depend on the device, go by the recipe number instead. The folder's README.md indexes all 281 files by chapter, with the page, recipe, section and a one-line description of each.

Every file starts with a comment block that says what to install, which services it needs (SQL Server, Redis, an SMTP server) and how it was tested. Most files are modules rather than programs, so for most of them the test proved that they load and define what the listing defines, not that they ran against a live database. The README lists the few known issues. A docstring under the header gives the chapter, recipe, section and full page range, and notes where the Python had to differ from the C#. For example, cryptography's AES-GCM appends the tag to the ciphertext, so the converted Recipe 7.2 moves it to keep the book's byte layout. That is why a value encrypted by p144_r7_2_aes_gcm_encryptor.py decrypts with assist.security, which then reports it as a version 1 payload that needs re-encrypting.

Use the converted listings to learn a recipe or to port one piece of it into an existing script. Use the library when you want the whole recipe, tested, in more than one place.

Checklist

  • Install improvecode-assist with only the extras a script needs, and pin its version.
  • Keep one appsettings.json layout for the C# and Python sides of a system; the keys and environment variable names work the same way.
  • Validate settings with OptionsRegistry.validate_all() before a script does any work.
  • Write SQL with :name markers and a dictionary of values, never with f-strings.
  • Wrap scheduled scripts in execute_run and exit with outcome.exit_code.
  • Define each encryption context once per column, in one function, and use the same text in C# and Python.
  • Upgrade old payloads with needs_reencryption and reencrypt, and old password hashes at sign-in.
  • Read a converted listing next to its printed page, and use the library for production code.