No description
  • Python 49.7%
  • Java 26.1%
  • HTML 14.4%
  • CSS 8%
  • Shell 1.1%
  • Other 0.7%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
itc 5c6d52c716
All checks were successful
ci / unit-tests (push) Successful in 15s
ci / ui-tests (push) Successful in 1m45s
ci / build-push (push) Successful in 14s
ci / allure-report (push) Successful in 21s
ci / deploy (push) Successful in 9s
revert bc2e21f96b
revert опоздал
2026-09-29 06:47:03 +00:00
.forgejo/workflows cleanup 2026-09-29 10:17:57 +04:00
ashtray Initial commit 2026-09-29 00:00:57 +04:00
deploy opozdun check 2026-09-29 10:04:32 +04:00
static Initial commit 2026-09-29 00:00:57 +04:00
templates Initial commit 2026-09-29 00:00:57 +04:00
tests initial commit 2 2026-09-29 00:26:41 +04:00
unit_tests revert 79da511e57 2026-09-29 02:53:38 +00:00
.dockerignore initial commit 2 2026-09-29 00:26:41 +04:00
.gitignore initial commit 2 2026-09-29 00:26:41 +04:00
app.py Initial commit 2026-09-29 00:00:57 +04:00
docker-compose.yml Initial commit 2026-09-29 00:00:57 +04:00
Dockerfile Initial commit 2026-09-29 00:00:57 +04:00
opozdun.scr revert bc2e21f96b 2026-09-29 06:47:03 +00:00
pytest.ini initial commit 2 2026-09-29 00:26:41 +04:00
README.md initial commit 2 2026-09-29 00:26:41 +04:00
README.ru.md initial commit 2 2026-09-29 00:26:41 +04:00
requirements-dev.txt initial commit 2 2026-09-29 00:26:41 +04:00
requirements.txt Initial commit 2026-09-29 00:00:57 +04:00

Ashtray

Русская версия

A log of the cigarettes you have smoked: what the brand was, what you thought of it, what it cost, with photos of the pack. Entries are private unless you share them; shared ones anyone can read, no account needed. Flask, SQLite, Jinja, Bootstrap, session sign-in, dark and light mode, English and Russian.

Run it

pip install -r requirements.txt
python app.py
# http://127.0.0.1:5000 — create an account, then log your first pack

That is the whole setup. The database file, the signing key and the uploads/ folder for pictures appear under instance/ on first run.

Settings, all optional, all environment variables:

Variable Default What it does
PORT / HOST 5000 / 127.0.0.1 where to listen
ASHTRAY_DB instance/ashtray.db path to the SQLite file
ASHTRAY_INSTANCE instance/ where the generated signing key (and, by default, the database) lives
ASHTRAY_UPLOADS instance/uploads/ where attached pictures are stored
SECRET_KEY generated, kept in instance/secret.key signs the session cookie
ASHTRAY_ALLOW_SIGNUP 1 set to 0 once your own account exists
ASHTRAY_HTTPS 0 set to 1 behind TLS so the cookie is marked Secure
ASHTRAY_DEBUG 0 set to 1 for Flask's debugger and reloader, never on a shared server

Run it in Docker

The backend also runs as a container, built locally; nothing is pushed to a registry. (CI builds and publishes its own image: see CI/CD below.)

docker compose up -d --build     # http://127.0.0.1:8000
docker compose logs -f           # follow the log
docker compose down              # stop; the data stays in the ashtray-data volume
  • The image (ashtray:local, Python 3.12, about 230 MB) holds only app.py, ashtray/, templates/ and static/, and runs the app under gunicorn (one worker, four threads) as an unprivileged user.
  • The database, the signing key and uploaded pictures live in the ashtray-data volume at /data, so rebuilding or recreating the container keeps them, sessions included.
  • The port is bound to 127.0.0.1 only. It is 8000 rather than 5000 because on macOS the AirPlay receiver already listens on 5000; pick another with ASHTRAY_PORT=9000 docker compose up -d.
  • Settings from the table above go under environment: in docker-compose.yml.
  • Building needs the internet (for pip); the running container needs none.

The test suite runs against the container like against any server you started yourself: mvn test -Dashtray.baseUrl=http://127.0.0.1:8000.

Layout

app.py                 entry point: reads the settings, builds the app, runs it
ashtray/
  __init__.py          create_app(): builds every object and wires them together
  config.py            Settings, read once from the environment
  database.py          the SQLite connection (one per request) and transactions
  schema.py            tables, and one Migration class per change to an older database
  domain.py            plain data passed between layers (ReviewDraft, ReviewFilter...) and errors
  repositories.py      all the SQL, one class per table
  services.py          what the app does: accounts, reading and writing reviews, brand stats,
                       who may see a picture; no Flask in here
  images.py            picture formats, upload checks, and the file store
  passwords.py         password hashing behind a small interface
  sorting.py           the whitelisted sort orders
  pagination.py        pages and the 1 … 4 5 [6] 7 8 … 20 window
  translations.py      Russian for every English UI string (data only)
  web/
    controllers/       one class per area: auth, log, feed, entries, pictures, language, errors
    forms.py           query strings and submitted forms into domain data
    session.py         who is signed in; the sign-in guard
    csrf.py            the CSRF token check
    i18n.py            choosing the language, translating
    compression.py     gzip for text responses
    templating.py      the names every template can use
templates/             base, login, register, reviews, feed, review, review_form, brands, error,
                       _review_list and _pager (shared by the log and the feed)
static/bootstrap.min.css  Bootstrap 5.3.8, a local copy (no CDN), and its .map
static/app.css         16.6 kB of layout and colour on top of Bootstrap
Dockerfile             the backend image; docker-compose.yml runs it, .dockerignore trims it
tests/                 Java + Selenide suite with Allure reports (separate Maven project)
unit_tests/            pytest unit tests; requirements-dev.txt and pytest.ini go with them
.forgejo/workflows/    CI/CD: tests, Allure report, image, deploy
deploy/                what CI copies to the deploy host: compose file and deploy.sh

How the code is organised

Four layers, each allowed to use only the ones below it:

  1. web turns HTTP into calls: a controller reads the request, asks a service, renders a template. Controllers hold no SQL and no business rules.
  2. services decide what happens: who may see what, what a valid review is, what goes into one transaction. They know nothing about HTTP or templates.
  3. repositories are the only place with SQL.
  4. database hands out the connection.

The SOLID principles, as they show up here:

  • Single responsibility. Reading reviews (ReviewReader) and writing them (ReviewWriter) are separate classes; so are the form parser, the upload checks, the CSRF check, the gzip step and each controller.
  • Open/closed. A schema change is a new Migration subclass added to MIGRATIONS; the existing ones are never edited. A new sort order is one more entry in SortOptions. A new page is a new controller with its own routes, mounted in create_app().
  • Liskov substitution. Anything that implements ImageStore (save, delete, path) can stand in for DiskImageStore, and anything that implements PasswordHasher for the Werkzeug one.
  • Interface segregation. Those interfaces are small, and each class receives only what it uses: PictureAccess gets the image repository and the store, nothing else.
  • Dependency inversion. Services depend on those interfaces, not on disk or Werkzeug, and no class builds its own collaborators: create_app() builds everything and passes it in through constructors. To keep pictures in S3 instead of on disk, write an S3ImageStore and change one line there.

Error messages in the services are English strings marked with N_("..."); the web layer translates them for the reader, so the services do not depend on the language either.

What it does

Logging. One form: brand, variant, country, rating out of ten, strength out of five, price, date, tar and nicotine in mg, and free notes. Everything except brand, rating and date is optional and stays empty rather than becoming a zero. Brands are created on the fly and offered back as autocomplete on the next entry, so "Gauloises" does not become three brands through three spellings. Each account keeps its own list of brands, and a brand is its name together with its country: Marlboro from the US and Marlboro from Russia are two brands, each with its own averages. The country is exactly what you type: left blank, the entry has none, and nothing is filled in for you. Changing the country on an entry moves just that entry.

Pictures. Up to six per entry, 5 MB each, in JPEG, PNG, GIF or WebP. The format is read from the file's first bytes, not from its name or the type the browser claims, and SVG is not accepted because it can carry script. Files are stored under random names in instance/uploads/ and served through the app, which checks on every request that the reader may see the entry: a private entry's pictures are not served to anyone but its author. Editing an entry can remove pictures or add more; deleting it deletes its files too.

Sharing. Every entry has a "Share this entry" box, ticked by default for new ones. Shared entries appear in the public feed at /feed, with their author and pictures, and each has its own page, which anyone can open without an account. A visitor who is not signed in and opens / lands on the feed. The feed has the same search, minimum rating and sorts as your log, plus a filter by author. Entries written before sharing existed stay private until you tick the box.

Reading. The log sorts by date smoked, rating, strength, price, nicotine, brand name and date added, each in both directions, and filters by free-text search across brand, variant and notes, by a single brand, and by a minimum rating. Filters and sort combine, and both survive in the URL, so a view you like is bookmarkable. The brands page rolls the same entries up per brand — count, average rating, average strength, average price, last smoked — with its own sort. Prices are only added up or averaged within one currency: the log shows a total per currency, and a brand priced in several shows "mixed" instead of an average.

Sort keys arrive from the query string but never reach SQL: they index a fixed dictionary of ORDER BY fragments, and anything unrecognised falls back to newest-first.

Accounts. Werkzeug-hashed passwords, a signed session cookie, HttpOnly and SameSite=Lax, thirty-day lifetime. Every query is scoped to the signed-in account, so two people on the same instance cannot see or edit each other's entries, except the ones an author chose to share, which everyone can read but only the author can change. Every POST carries a CSRF token checked in a before_request hook. The signing key is persisted, so restarting the server does not sign you out.

Languages. English and Russian, switched with the EN / RU buttons in the header of every page, signed in or not. The choice is kept in a lang cookie for a year, so it survives signing in and out; until you choose, the page follows your browser's language. English is written inline in the code (marked N_("...")) and in the templates (_("...")); ashtray/translations.py maps each of those strings to Russian, including the three Russian plural forms (1 запись, 2 записи, 5 записей). A string missing there shows in English rather than breaking the page.

Look. A light sheet on an ash-grey screen, with a plain one-line header: the name on the left, sections in the middle, the new-entry button, language, theme and sign-out on the right. The sheet takes almost the whole width of the screen. The log and the feed lay entries out in as many columns as fit (one on a phone, four on a wide monitor), and an entry's own page puts its photos beside the text once there is room. Forms, sign-in and the brands table stay narrow in the middle, where they read best. A rating is drawn as a cigarette smoked down as far as the score: the better it was, the longer the ash and the less paper left before the filter, so a 10 is smoked to the filter and a 2 was put out early. Titles and brand names use a condensed sans, the way pack lettering does, and the system font carries the rest.

Themes. Bootstrap 5.3 does dark mode natively through data-bs-theme. A ten-line inline script sets the attribute before the first paint — from localStorage if you have chosen, from prefers-color-scheme if you have not — so there is no flash of the wrong theme, and the choice needs no round trip to the server.

On keeping it small

  • One process, no daemons. SQLite in WAL mode, sqlite3 from the standard library, no ORM. Flask is the only dependency.
  • No requests outside the site. Bootstrap 5.3.8's stylesheet is kept in static/bootstrap.min.css (with its source map), byte for byte the file jsDelivr serves, so the site works on a network with no internet access. Bootstrap's JavaScript bundle is not loaded at all: the navbar does not collapse, alerts do not dismiss, and nothing else on the page needed it.
  • No web fonts, no icon font, no images in the interface. The system font stack and two Unicode glyphs; the only pictures are the ones you attach, loaded lazily.
  • Server-rendered HTML, gzipped in an after_request hook, and so are the stylesheets (Bootstrap goes from 232 kB to 31 kB). A log page holding a dozen entries is about 3 kB on the wire; the sign-in page is 1.5 kB. There is no JSON API and no client-side rendering, so a page costs one request.
  • Static files carry a version stamp and are served with a one-year cache lifetime.

To move to another Bootstrap version, replace the two files and check the stylesheet against the hash jsDelivr publishes for it:

V=5.3.8
curl -o static/bootstrap.min.css     https://cdn.jsdelivr.net/npm/bootstrap@$V/dist/css/bootstrap.min.css
curl -o static/bootstrap.min.css.map https://cdn.jsdelivr.net/npm/bootstrap@$V/dist/css/bootstrap.min.css.map
echo "sha384-$(openssl dgst -sha384 -binary static/bootstrap.min.css | openssl base64 -A)"

The page picks the new file up by itself: every static URL carries a stamp taken from the file's modification time, so browsers do not keep the old one from their cache.

For anything beyond your own laptop, put a real WSGI server in front — one worker is plenty:

pip install gunicorn
gunicorn -w 1 --threads 4 -b 127.0.0.1:8000 app:app

Keep it to one worker, or move ASHTRAY_DB somewhere every worker can lock properly; SQLite in WAL mode handles several threads in one process comfortably.

Unit tests

Fast checks of the Python code without a browser or a server, under unit_tests/: pagination, sort whitelisting, form parsing, picture checks, settings, translations and plural forms, the services against small fakes, and a few requests through Flask's test client.

.venv/bin/python -m pip install -r requirements-dev.txt   # pytest and allure-pytest
.venv/bin/pytest                                           # about a second
.venv/bin/pytest --alluredir=allure-results/unit           # also write Allure results

Tests

A separate Maven project under tests/, written in Java with Selenide over Selenium. It needs JDK 17+, Maven, Chrome, and a Python that has Flask installed.

python3 -m venv .venv && .venv/bin/python -m pip install -r requirements.txt   # once
cd tests
mvn test -Dashtray.python=../.venv/bin/python

The suite starts its own copy of the app with the Python named by -Dashtray.python. Without the switch it runs plain python3 from PATH, which only works if Flask is installed there. Each run gets a free port, a throwaway SQLite file and a folder for uploaded pictures in the temp directory; the app is stopped and both are deleted when the JVM exits. Your real log is never touched. Chrome runs headless, and Selenium Manager fetches the matching driver on the first run.

Useful switches:

mvn test -Dselenide.headless=false          # watch it work
mvn test -Dselenide.browser=firefox
mvn test -Dashtray.baseUrl=http://127.0.0.1:5000   # test a server you started yourself
mvn test -Dashtray.python=/usr/bin/python3.12     # any Python with Flask installed
mvn test -Dashtray.appDir=/path/to/ashtray        # if tests/ is not next to app.py
mvn test -Dtest=SortingAndFilteringTest

Failures leave a screenshot in tests/target/selenide-failures/, and the app's own stdout and stderr in tests/target/ashtray-server.log.

The suite runs against the English interface: BaseTest sets a lang=en cookie before every test, so a browser with a Russian locale does not break it. LanguageTest covers Russian.

What it covers:

Class Checks
AuthTest a signed-out visitor landing on the feed and being asked to sign in for private pages, sign-up, sign-in, wrong password, duplicate username, mismatched passwords, sign-out, session across reloads, and that one account cannot read or edit another's entries
ReviewLifecycleTest empty state, saving every field, blank optional fields staying blank, the edit form arriving filled in, deleting one row of several, server-side validation of brand and rating, the same brand from two countries staying two brands, brand averages
SortingAndFilteringTest date, rating, strength, price and brand sorts in both directions, an unknown sort key falling back safely, search across brand/variant/notes, brand and minimum-rating filters, filter and sort combined, brand-page sorts
PublicReviewsTest a shared entry and its picture readable without an account, a private one kept out of the feed with its picture refused to strangers, removing pictures while editing, refusing a file that is not a picture
LanguageTest switching to Russian, the choice surviving reloads, sign-in and sign-out, switching back, staying on the same page with its filters, Russian plural forms
ThemeTest a theme is always set before paint, nothing stored until you choose, the toggle flips and records the choice, it survives reloads and navigation and sign-out, it is reversible, and dark mode genuinely darkens the rendered background

Page objects live in tests/src/test/java/dev/ashtray/pages/. They address elements by the stable ids and classes in the templates — #save-btn, .review-row, .col-rating — rather than by Bootstrap's utility classes, so restyling the app does not break the suite.

Test reports (Allure)

Every run also writes Allure results to tests/target/allure-results/. To turn them into a report:

cd tests
mvn clean test -Dashtray.python=../.venv/bin/python
ALLURE_NO_ANALYTICS=true mvn allure:report   # target/site/allure-maven-plugin/index.html
ALLURE_NO_ANALYTICS=true mvn allure:serve    # or: build it and open it in the browser

The report is a single index.html that opens straight from disk, with no server and no internet. ALLURE_NO_ANALYTICS=true leaves out the Google Analytics tag Allure otherwise puts in the page (it has to be true; 1 does not count). Run clean first, or results from earlier runs pile up and show as retries.

What is in it:

  • tests grouped by area (Accounts, Writing entries, Sorting and filtering, Public reviews and pictures, Languages, Themes), each a readable scenario: "Sign up as a new user", "Brand: Marlboro", "Country: US", "Save the entry", with Selenide's own actions nested under each step;
  • for a failed test, a screenshot, the page's HTML and the last 200 lines of the Flask app's log, so a server error shows up next to what the browser saw;
  • an Environment panel with the base URL, browser, Java and OS.

The first allure:report downloads the report generator (Allure 2.46.1, plain Java) into tests/.allure/ and reuses it afterwards; on a machine with no internet, copy that folder over.

CI/CD (Forgejo Actions)

.forgejo/workflows/ci.yml runs on every push to main, on pull requests and by hand:

Job What it does
unit-tests pytest over unit_tests/, Allure results kept as the allure-results-unit artifact
ui-tests the Java suite on Debian's Chromium and chromedriver, results kept as allure-results-ui; on failure, the app's log and the screenshots as ui-tests-debug
allure-report runs even when tests failed; merges both results into one report, the allure-report artifact (a single index.html)
build-push main only, after both test jobs pass: builds the Dockerfile and pushes <registry>/<owner>/ashtray:<commit> and :latest to Forgejo's container registry
deploy copies deploy/docker-compose.yml and deploy/deploy.sh to the Debian host over SSH, pulls that exact commit's image, restarts the container and waits for its health check

Every job runs in node:20-bookworm on a runner with the docker label, and installs what it needs with apt. Actions come from https://data.forgejo.org (GitHub's upload-artifact@v4 refuses to run anywhere but github.com, hence Forgejo's fork).

Runner. A Forgejo runner with the docker label. build-push builds on the host's Docker daemon through its socket, so the runner's config.yml has to let jobs mount it:

container:
  valid_volumes:
    - /var/run/docker.sock

The image is pushed by that host daemon, so it has to reach the registry. If Forgejo is served over plain HTTP, add it to insecure-registries in /etc/docker/daemon.json there, and on the deploy host too.

Secrets and variables (repository → Settings → Actions):

Name Kind What it is
REGISTRY_TOKEN secret an access token with write:package scope, for pushing the image
REGISTRY_USER variable that token's user; defaults to the repository owner
REGISTRY variable registry host, forgejo.lan:3000; defaults to the host of Forgejo's own URL, set it when the runner knows Forgejo by another name
DEPLOY_HOST, DEPLOY_USER secret the Debian host and the account CI logs in as
DEPLOY_SSH_KEY secret that account's private key (the public one in its ~/.ssh/authorized_keys)
DEPLOY_PORT secret SSH port, 22 if not set
DEPLOY_KNOWN_HOSTS secret the host's line from ssh-keyscan; without it the key is trusted on first sight every run
DEPLOY_REGISTRY_TOKEN secret optional read-only (read:package) token for the host to pull with; REGISTRY_TOKEN otherwise
DEPLOY_PATH variable folder on the host, relative to the user's home; ashtray if not set

Deploy host. Debian with Docker and either docker compose or docker-compose; the deploy user must be in the docker group. The app listens on port 8000 on every interface. To change that, or any setting from the table at the top, add lines to ~/ashtray/.env on the host (ASHTRAY_PORT=9000, ASHTRAY_BIND=127.0.0.1, ASHTRAY_ALLOW_SIGNUP=0...): each deploy rewrites only the ASHTRAY_IMAGE line. Data lives in the ashtray_ashtray-data volume and survives deploys. To roll back, put an older commit's tag in ASHTRAY_IMAGE and run docker compose -p ashtray up -d in that folder.