Metadata-Version: 2.4
Name: websprout
Version: 0.1.0
Summary: A small, original Python web framework with built-in WSGI support.
Author: MyFramework Authors
License-Expression: MIT
Project-URL: Homepage, https://github.com/debatra638/myframework
Project-URL: Documentation, https://github.com/debatra638/myframework#documentation
Project-URL: Source, https://github.com/debatra638/myframework
Project-URL: Changelog, https://github.com/debatra638/myframework/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/debatra638/myframework/issues
Keywords: web,framework,wsgi,http,routing,templates
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Web Environment
Classifier: Topic :: Internet :: WWW/HTTP :: WSGI
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: ruff>=0.5; extra == "dev"
Requires-Dist: mypy>=1.8; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Provides-Extra: servers
Requires-Dist: gunicorn>=21.0; sys_platform != "win32" and extra == "servers"
Requires-Dist: waitress>=2.1; extra == "servers"
Dynamic: license-file

# MyFramework

A small, complete Python web framework with **native WSGI support** and **zero runtime
dependencies**. It gives you Flask-style routing, JSON APIs, templates with inheritance,
static files, middleware and a development server in one library that you can read in an
afternoon.

```python
from myframework import App, request, Response

app = App()

@app.route("/")
def home():
    return "<h1>My Website</h1>"

@app.route("/users/<username>")
def user_profile(username):
    return f"<h1>Hello, {username}</h1>"

@app.route("/api/data", methods=["GET"])
def get_data():
    return {"message": "Hello from my framework"}

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8000)
```

```console
$ pip install myframework          # or: pip install the wheel you were given
$ myframework run --app app:app --debug
  MyFramework development server
  App:      'app'
  Debug:    on    Reloader: on
  Running:  http://127.0.0.1:8000/
```

**Status:** alpha (`0.1.0`). Everything documented as *implemented* below has tests; see
[Implemented vs. planned](#implemented-vs-planned) for the honest boundary.

---

## Contents

- [Why another framework?](#why-another-framework)
- [Installation](#installation)
- [Quick start](#quick-start)
- [Command line](#command-line)
- [Routing](#routing)
- [Requests](#requests)
- [Responses](#responses)
- [Templates](#templates)
- [Static files](#static-files)
- [Configuration](#configuration)
- [Middleware](#middleware)
- [Errors, logging and debug mode](#errors-logging-and-debug-mode)
- [WSGI and deployment](#wsgi-and-deployment)
- [Testing](#testing)
- [Security model](#security-model)
- [Project layout](#project-layout)
- [Design decisions](#design-decisions)
- [Implemented vs. planned](#implemented-vs-planned)
- [Development](#development)
- [License](#license)

---

## Why another framework?

The goal is a framework that you can install into a bare virtual environment and use to
build a website, an HTML app, a REST API or a backend service — without assembling three
libraries first. That constraint drives the design:

| Requirement | How MyFramework meets it |
| --- | --- |
| One library for HTTP, routing, WSGI, templates, static files | all in `myframework/`, no runtime dependencies |
| Standards compliance | a WSGI callable per PEP 3333, verified with `gunicorn`, `wsgiref` and contract tests |
| Small and readable | ~6k lines including docstrings; no metaprogramming magic |
| Safe defaults | HTML escaping on by default, request size limits, path-traversal guards |
| Real packaging | `pyproject.toml`, `myframework` console script, typed (`py.typed`), installable |

## Installation

MyFramework is a pure-Python package with **no runtime dependencies** on Python 3.10–3.13.
Pick the line that matches what you have:

```console
# 1. a wheel you were given (fastest, nothing is compiled)
$ python -m venv .venv && source .venv/bin/activate     # Windows: .venv\Scripts\activate
$ pip install ./myframework-0.1.0-py3-none-any.whl

# 2. a source distribution
$ pip install ./myframework-0.1.0.tar.gz

# 3. a checkout of this repository (editable, with the dev tools)
$ pip install -e ".[dev,servers]"

# 4. from PyPI, once the project is published there
$ pip install myframework
```

Optional extras:

```console
$ pip install "myframework[servers]"   # gunicorn (Linux/macOS) + waitress for deployment
$ pip install "myframework[dev]"       # pytest, pytest-cov, ruff, mypy, build
```

Check that it worked — no console script required:

```console
$ python -m myframework version        # myframework 0.1.0
$ python -c "import myframework; print(myframework.__file__)"
$ myframework --help                   # the console script, when it is on PATH
```

Full details (offline/air-gapped installs, type checking, uninstalling, releasing) are in
**[docs/installation.md](docs/installation.md)**. `scripts/verify_install.sh` rehearses
everything below from the built artifacts in a throwaway virtual environment.

### Documentation map

| Document | Contents |
| --- | --- |
| [docs/quickstart.md](docs/quickstart.md) | A working site in ten minutes: routes, templates, static files, JSON, tests, deploy |
| [docs/api.md](docs/api.md) | Every public class and function, generated from the source |
| [docs/architecture.md](docs/architecture.md) | Request lifecycle, module map, where to extend |
| [docs/security.md](docs/security.md) | Implemented controls, explicit non-features, deployment checklist |
| [docs/deployment.md](docs/deployment.md) | Gunicorn, Waitress, nginx, systemd, health checks |
| [docs/installation.md](docs/installation.md) | Install paths, verification, releasing |
| [CHANGELOG.md](CHANGELOG.md) | What changed, and known limitations |

## Quick start

Create a project skeleton (app, templates, static files, smoke test):

```console
$ myframework new mysite
$ cd mysite
$ python -m venv .venv && source .venv/bin/activate
$ pip install myframework     # already installed? skip this line
$ myframework run --debug     # http://127.0.0.1:8000/
$ pytest                      # after: pip install pytest
```

The generated project ships a valid `pyproject.toml`, so `pip install -e ".[dev]"` also
works when you want it installable on its own. A ten-minute walkthrough of everything it
can do is in [docs/quickstart.md](docs/quickstart.md).

The classic single file (`examples/hello_world.py`) works just as well:

```python
from myframework import App, request

app = App(__name__)

@app.route("/")
def home():
    return "<h1>My Website</h1>"

@app.route("/users/<username>")
def user_profile(username):
    return f"<h1>Hello, {username}</h1>"

@app.route("/api/data", methods=["GET"])
def get_data():
    return {"message": "Hello from my framework"}

@app.route("/greet", methods=["GET", "POST"])
def greet():
    name = request.args.get("name") or (request.json or {}).get("name") or "world"
    return {"greeting": f"Hello, {name}!"}

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8000)
```

A view can return `str`, `bytes`, `dict`/`list` (JSON), `Response`,
`(body, status)`, `(body, status, headers)` or `None`.

Runnable examples live in [`examples/`](examples):

| File | What it shows |
| --- | --- |
| `examples/hello_world.py` | smallest app, JSON + query parameters |
| `examples/blog_app.py` | templates with inheritance/partials, static files, HTML + JSON, custom error handlers, redirects |
| `examples/api_app.py` | JSON REST API with CRUD, CORS, request ids, security headers, request size limit |

```console
$ python examples/blog_app.py            # then open http://127.0.0.1:8000/
$ gunicorn -w 4 "examples.api_app:app"   # the same app on a real WSGI server
```

## Command line

```console
$ myframework run --app app:app --host 0.0.0.0 --port 8080 --debug
$ myframework run --app app:app --no-reload
$ myframework routes --app app:app     # print the URL map (debug 404s quickly)
$ myframework new myproject            # scaffold a project
$ myframework version
```

* The app may be given as `module:attribute`, `module.attribute` or plain `module`
  (then `app`, `application` or `create_app` is used). Without `--app`, `MYFRAMEWORK_APP`
  is read, and finally `app.py` / `wsgi.py` / `main.py` in the current directory are tried.
* `--debug` turns on the traceback page, verbose logs and the auto-reloader;
  `--no-reload` keeps the reloader off.
* Startup prints the routes and the URL to open. The development server is threaded, so a
  slow request does not block the next one.

## Routing

```python
@app.route("/users/<username>")                     # one path segment (str)
@app.route("/posts/<int:post_id>")                  # int
@app.route("/price/<float:amount>")                 # float
@app.route("/ids/<uuid:item_id>")                   # uuid.UUID
@app.route("/fruit/<any(apple, pear):kind>")        # enumeration
@app.route("/files/<path:filename>")                # matches across "/"
@app.get("/health")                                 # method shortcuts
@app.post("/items")
@app.delete("/items/<int:item_id>")
```

* Methods: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`, `HEAD`, `TRACE`, `CONNECT`.
  `HEAD` is served by `GET` views without a body; `OPTIONS` is answered automatically with
  an `Allow` header unless you register an `OPTIONS` view yourself.
* The most specific rule wins: fewer wildcards, then more literal characters, then
  registration order. `/users/me` beats `/users/<username>` regardless of decorator order.
* The same URL may be used by different endpoints for different methods (`GET` and `POST`
  handlers for `/api/notes`); a wrong method returns `405` with a complete `Allow` header.
* `strict_slashes` (default on) redirects `/about` ↔ `/about/` with `308` instead of `404`.
* `@app.route("/page", defaults={"page": 1})` supplies default arguments.
* Custom converters:

```python
from myframework.routing import BaseConverter

@app.converter("slug")
class SlugConverter(BaseConverter):
    regex = r"[a-z0-9]+(?:-[a-z0-9]+)*"

@app.route("/blog/<slug:slug>")
def post(slug): ...
```

### URL generation

```python
url_for("home")                                  # "/"
url_for("user_profile", username="ada")          # "/users/ada"
url_for("user_profile", username="ada", page=2)  # "/users/ada?page=2"
url_for("static", filename="style.css")          # "/static/style.css"
url_for("home", _external=True)                  # "http://localhost/"
```

`url_for` is available inside views (`from myframework import url_for`) and inside
templates (`{{ url_for('static', filename='style.css') }}`). Unknown endpoints and missing
arguments raise errors that list the known endpoints.

## Requests

The `request` object is a context-local proxy — no need to pass it around:

```python
from myframework import request

request.method                  # "POST"
request.path                    # "/api/notes" (percent-decoded)
request.args                    # MultiDict of the query string
request.args.getlist("tag")     # ["a", "b"]
request.form                    # MultiDict of a urlencoded/multipart body
request.files["document"]       # FileStorage (filename, content_type, data, save())
request.json                    # parsed JSON body (None when empty)
request.get_json(silent=True)   # never raises
request.data                    # raw body bytes
request.headers["User-Agent"]   # case-insensitive headers
request.cookies                 # dict
request.remote_addr             # client address (see ProxyFix)
request.url / base_url / host   # absolute URLs
request.endpoint / view_args    # routing results
```

Errors are precise: a JSON body with `Content-Type: text/plain` raises `415`, malformed
JSON raises `400`, `Content-Length` larger than `MAX_CONTENT_LENGTH` raises `413` **before**
the body is read, and a body without a `Content-Length` is read only up to the limit.

## Responses

```python
from myframework import Response, jsonify, redirect, abort, stream_response

return "text"                                     # HTML
return {"ok": True}, 201                          # JSON + status
return "text", 201, {"X-Trace": "abc"}            # + headers

response = Response("<h1>hi</h1>", status=201, mimetype="text/html")
response.headers["X-Custom"] = "1"
response.set_cookie("theme", "dark", httponly=True, secure=True, samesite="Lax")
response.delete_cookie("theme")
response.cache_control(max_age=60, public=True)
return response

return jsonify(items=[1, 2], count=2)             # datetimes/UUIDs/dataclasses supported
return redirect("/login", code=302)
abort(404, "No such user")                        # raises an HTTPException

def numbers():                                    # streaming
    for i in range(5):
        yield f"{i}\n".encode()
return stream_response(numbers(), mimetype="text/plain")
```

Cookies default to `Path=/` and `SameSite=Lax`; `HttpOnly` and `Secure` are explicit
opt-ins because they depend on your deployment (HTTPS? JavaScript access?).
`Set-Cookie` may be emitted several times (`headers.getlist("Set-Cookie")`).

## Templates

Enable the renderer by having a `templates/` directory next to your app module (or set
`TEMPLATE_DIR`):

```python
from myframework import render_template

@app.route("/")
def index():
    return render_template("index.html", title="Home", items=["a", "b"])
```

```htmldjango
{# templates/index.html #}
{% extends "base.html" %}
{% block title %}{{ title }}{% endblock %}
{% block content %}
  <ul>
  {% for item in items %}
    <li class="{% if loop.first %}first{% endif %}">{{ loop.index }}. {{ item }}</li>
  {% else %}
    <li>No items.</li>
  {% endfor %}
  </ul>
{% endblock %}
```

Supported: `{{ expression }}`, `{% if/elif/else %}`, `{% for/else %}` with `loop.index`,
`index0`, `revindex`, `first`, `last`, `length`, `cycle()`, `previtem`, `nextitem`,
`{% block %}` + `{{ super() }}`, `{% extends %}`, `{% include %}` (and `ignore missing`),
`{% set %}`, `{% raw %}`, `{# comments #}`, whitespace control (`{{- -}}`), and ~30 filters
(`escape`, `safe`, `upper`, `length`, `default`, `join`, `truncate`, `tojson`, `sort`, …).

Expressions are Python-like and evaluated by a **restricted interpreter** built on the
standard `ast` module — `eval`/`exec` are never used, so no lambdas, comprehensions,
imports, assignments or `__dunder__` access are reachable from a template.

```python
@app.template_filter("slug")
def slug(value):
    return re.sub(r"[^a-z0-9]+", "-", str(value).lower()).strip("-")

@app.context_processor
def inject():
    return {"site_name": "My Site"}
```

Behaviour worth knowing:

* **Autoescaping is on.** `{{ value }}` escapes `& < > " '`. Use `{{ value|safe }}` only for
  content you produced. `Markup("<b>x</b>")` is treated as already safe.
* **Undefined variables raise** (`UndefinedError` naming the template and listing known
  names) by default — typos surface immediately. Use `{{ x|default('n/a') }}` for optional
  values, or set `TEMPLATE_UNDEFINED = "lenient"` for Jinja-style empty output.
* **Filters and operators:** `|` binds like Python's `|`, so `{% if items|length > 1 %}`
  and `{{ x|default('a')|upper }}` work; inside arithmetic, parenthesise the filter:
  `{{ ('3'|int) + 1 }}`.
* Loading is sandboxed: `..`, absolute paths, backslashes and symlinks that escape the
  template directory are refused.
* Not implemented (deliberately, see below): macros, custom tags, `{% filter %}` blocks.

## Static files

`STATIC_DIR` (default `./static`) is served at `STATIC_URL_PATH` (default `/static`):

```python
app = App(__name__, static_dir="public", STATIC_URL_PATH="/assets")
```

```htmldjango
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
```

* `..`, NUL bytes, backslashes and drive letters are rejected; the resolved real path must
  stay inside `STATIC_DIR` (symlink escapes are blocked).
* Only regular files are served — no directory listings, no directory indexes.
* Executable/unknown types are sent as `application/octet-stream` (never rendered inline).
* `ETag` + `Last-Modified` are sent and `If-None-Match` / `If-Modified-Since` yield `304`.
* Cache headers follow `SEND_FILE_MAX_AGE` (default 3600s).
* `StaticFiles` is itself a WSGI app, so it can be mounted elsewhere.

## Configuration

```python
app = App(__name__, DEBUG=True, MAX_CONTENT_LENGTH=2 * 1024 * 1024)
app.config.update(STATIC_URL_PATH="/assets")
app.config.from_file("config.json")                       # .json or .toml
app.config.from_env("MYFRAMEWORK_")                       # MYFRAMEWORK_DEBUG=1
app.config.from_object("myproject.settings")              # upper-case constants
```

| Key | Default | Meaning |
| --- | --- | --- |
| `DEBUG` | `False` | traceback page, verbose logs, template auto-reload |
| `TESTING` | `False` | propagate exceptions to the test client |
| `PROPAGATE_EXCEPTIONS` | `None` | `None` = debug or testing |
| `MAX_CONTENT_LENGTH` | 16 MiB | request body limit (`413` above it) |
| `STATIC_DIR` / `STATIC_URL_PATH` | `./static` / `/static` | static files |
| `SEND_FILE_MAX_AGE` | `3600` | static cache lifetime in seconds |
| `TEMPLATE_DIR` | `./templates` | template search path |
| `TEMPLATE_UNDEFINED` | `"strict"` | `"strict"` or `"lenient"` |
| `TEMPLATES_AUTO_RELOAD` | `None` | `None` = same as `DEBUG` |
| `STRICT_SLASHES` | `True` | redirect trailing-slash mismatches |
| `PREFERRED_URL_SCHEME` | `"http"` | scheme for `_external=True` URLs |
| `SERVER_NAME` | `None` | used by `url_for(_external=True)` outside a request |
| `PREFERRED_HOST` | `None` | reject requests with a different `Host` header |
| `TRUSTED_HOSTS` | `None` | used by `TrustedHostMiddleware` |
| `LOG_LEVEL` | `"INFO"` | application log level |
| `SECRET_KEY` | `None` | *reserved for future session support; nothing uses it yet* |

Environment variables use the `MYFRAMEWORK_` prefix and are coerced to the type of the key
(`MYFRAMEWORK_MAX_CONTENT_LENGTH=1048576`). Invalid values raise `ConfigurationError` at
startup instead of failing later.

## Middleware

Two complementary mechanisms:

**WSGI middleware** wraps the whole application (`app.use(...)`); the first one added is the
outermost, i.e. it sees the request first and the response last.

```python
from myframework import CORSMiddleware, ProxyFix, SecurityHeadersMiddleware, RequestIDMiddleware

app.use(RequestIDMiddleware())                       # X-Request-ID + environ entry
app.use(SecurityHeadersMiddleware())                 # CSP, X-Frame-Options, Referrer-Policy
app.use(CORSMiddleware(allow_origins=["https://app.example.com"]))
app.use(ProxyFix(x_for=1, x_proto=1, x_host=1))      # only behind a proxy you control!
```

Also included: `AccessLogMiddleware`, `HeaderMiddleware`, `TrustedHostMiddleware`,
`HTTPSRedirectMiddleware`, and `MiddlewareStack` for composing without an app object.
Write your own by subclassing `WSGIMiddleware` and overriding `process_environ` and/or
`process_response`, or by writing a plain `app(environ, start_response)` callable.

Because WSGI middleware runs *before* the app dispatches, the `request`/`g` proxies are not
available inside it — use `environ` there.

**Application hooks** run inside the request context:

```python
@app.before_request
def load_user():            # return a response to short-circuit the view
    g.user = lookup(request.cookies.get("session_id"))

@app.after_request
def add_headers(response):  # runs in reverse registration order
    response.headers["X-Frame-Options"] = "SAMEORIGIN"
    return response

@app.teardown_request
def close(error):           # always runs, also on errors
    ...
```

## Errors, logging and debug mode

```python
@app.errorhandler(404)
def not_found(error):
    return render_template("404.html"), 404

@app.errorhandler(ValueError)
def value_error(error):
    return {"error": str(error)}, 400
```

* Unhandled exceptions are logged with a traceback and answered with a generic `500` page —
  no internals leak in production.
* `DEBUG=True` renders a traceback page (request line, traceback, exception) and sets
  `X-Debug-Mode: true`. Never enable it in production.
* `HTTPException` subclasses (`NotFound`, `BadRequest`, `MethodNotAllowed`, …) are turned
  into proper responses with the right status and headers (`Allow` for 405).
* `abort(403)` / `abort(403, "message")` raise them from anywhere in a view.
* Logging goes to `myframework.app.<import_name>`; the level comes from `LOG_LEVEL`.

## WSGI and deployment

`App` instances are WSGI callables (PEP 3333). Nothing in the request path needs an HTTP
server of our own; the development server is a separate, replaceable component.

```console
$ pip install gunicorn
$ gunicorn --workers 4 --bind 0.0.0.0:8000 "examples.api_app:app"
```

```console
$ pip install waitress
$ waitress-serve --port=8000 examples.api_app:app
```

What the WSGI layer guarantees (all covered by tests):

* `start_response(status, headers)` is called exactly once, with a `"<code> <reason>"`
  status line and a `list[tuple[str, str]]` of latin-1-safe headers, no newlines.
* The body is an iterable of `bytes`; `HEAD` responses have headers but no body;
  `Content-Length` is set for non-streaming bodies.
* Streaming bodies are wrapped so the server's `close()` releases file handles.
* Request bodies are read lazily and never beyond `MAX_CONTENT_LENGTH`.

Helpers: `myframework.wsgi.wsgi_application(app)`, `middleware_chain(app, *layers)`,
`validate_response(...)`, `serve_wsgiref(app, port=8000)` (standard-library server, for
checking the contract — not for production), and `make_environ(...)` for hand-made requests.

Every WSGI middleware you already have (WhiteNoise, `werkzeug.middleware.profiler`,
sentry SDKs, …) can wrap `app.wsgi_app` because the interface is the standard one.

## Testing

```python
from myframework import App

app = App(__name__)

@app.route("/ping")
def ping():
    return {"pong": True}

def test_ping():
    client = app.test_client()
    response = client.get("/ping")
    assert response.status_code == 200
    assert response.json == {"pong": True}
    response.assert_ok().assert_contains("pong")
```

The client builds a **real WSGI environ** and runs the **real application**, so middleware,
cookies, redirects and error handlers are all exercised:

```python
client.post("/api/items", json={"name": "x"})
client.post("/login", form={"user": "ada"})
client.post("/upload", files={"doc": ("a.txt", b"content")}, form={"title": "t"})
client.get("/", follow_redirects=True)          # .history keeps the hops
client.get("/", headers={"Accept": "text/html"})
client.cookies.clear()
```

Also available: `response.assert_redirects("/login")`, `response.assert_status(204)`,
`response.assert_content_type("application/json")`, and
`with app.test_request_context("/users/ada?x=1"): ...` for testing helpers that use
`request`/`g`.

Run the suite:

```console
$ pytest                      # 582 tests
$ pytest -m "not slow"        # skip tests that spawn real servers
$ pytest --cov=myframework    # ~84% line coverage (install pytest-cov)
```

The suite includes contract tests for the WSGI interface, integration tests against
`wsgiref` and **Gunicorn** (2 workers), a real dev-server subprocess test, traversal and
XSS tests, and CLI/scaffolding tests.

## Security model

Implemented and tested:

* **HTML escaping by default** in templates; error pages escape everything they embed.
* **Request size limits** (`MAX_CONTENT_LENGTH`) enforced before reading the body, also for
  chunked/unknown-length bodies.
* **Path traversal protection** for static files and templates (normalisation, realpath
  containment, symlink escapes, NUL/backslash rejection).
* **Safe default headers**: `X-Content-Type-Options: nosniff` on every response;
  `SecurityHeadersMiddleware` adds CSP, `X-Frame-Options`, `Referrer-Policy` (opt-in).
* **Cookie flags**: `SameSite=Lax` and `Path=/` by default; `Secure`/`HttpOnly` explicit.
* **No unsafe evaluation**: templates never call `eval`/`exec`; expressions are interpreted
  by an allow-list evaluator; private attributes are unreachable.
* **Production error pages** reveal nothing; tracebacks require `DEBUG=True`.
* **Malformed input** (bad `Content-Length`, broken JSON, multipart without boundary,
  broken cookies, bad UTF-8) produces `400`/`415` responses, never a crash or a 500.
* **Host header handling**: `PREFERRED_HOST` and `TrustedHostMiddleware` guard against
  Host-header poisoning; `ProxyFix` must be enabled explicitly.

**Not implemented — do not assume otherwise:**

* No authentication, authorization, sessions or CSRF protection. There is no session store
  and `SECRET_KEY` is unused. Add these yourself (e.g. signed cookies/`itsdangerous`,
  a CSRF token compared with `hmac.compare_digest`) before shipping anything
  authenticated.
* No rate limiting, no HTTPS termination, no TLS. Put a reverse proxy in front.
* No automatic `Content-Security-Policy` unless you enable `SecurityHeadersMiddleware`, and
  the default CSP is a starting point, not a guarantee.
* No protection against application-level bugs (SQL injection is not a framework concern;
  use parameterised queries).
* The development server is single-host, threaded and unhardened: for local development
  only.

## Project layout

```
myframework/
├── __init__.py        public API (App, request, Response, jsonify, middleware, …)
├── app.py             application object: routing, hooks, dispatch, errors
├── routing.py         rules, converters, matching, URL building
├── request.py         WSGI environ -> Request
├── response.py        Response, jsonify, redirect, abort, streaming
├── wsgi.py            PEP 3333 helpers, validation, wsgiref runner
├── devserver.py       threaded development server + auto-reloader
├── middleware.py      WSGI middleware collection
├── templates.py       template engine (lexer, parser, evaluator, filters, loaders)
├── static.py          safe static file serving, send_file, safe_join
├── config.py          defaults, env/file/object loading
├── datastructures.py  MultiDict, Headers, FileStorage
├── globals.py         request / g / current_app proxies, url_for, render_template
├── exceptions.py      HTTPException hierarchy and framework errors
├── testing.py         WSGI-level test client
├── cli.py             myframework run|routes|new|version
└── __main__.py        python -m myframework
tests/                 582 tests: unit, contract, integration, CLI, security, packaging
examples/              hello_world.py, blog_app.py (+ templates/static), api_app.py
docs/                  installation, quickstart, api (generated), architecture, security, deployment
scripts/check.sh       lint + format + types + tests + build + twine + install rehearsal
scripts/verify_install.sh  installs the built artifacts in a clean venv and uses them
scripts/build_api_docs.py  regenerates docs/api.md from the docstrings
scripts/publish_to_github.sh  create the repository, set the URLs, push, verify
pyproject.toml         metadata, extras, console script, tool configuration
MANIFEST.in            what ships in the sdist (tests, docs, examples, scripts)
.github/workflows/     CI matrix (Python 3.10–3.13) and a wheel/Gunicorn job
CHANGELOG.md           user-facing history and known limitations
LICENSE                MIT
```

## Design decisions

**Templates: original engine instead of Jinja2.** The framework must install with no runtime
dependencies, and the required feature set (interpolation, inheritance, partials,
autoescaping) is small. Writing ~700 lines gives control over escaping and sandboxing and
removes a supply-chain surface. Trade-off: no macros/custom tags, and filters bind like
Python's `|` rather than Jinja's tighter rule (documented above). If you need full Jinja2
semantics you can render with Jinja2 yourself and return the string — nothing in the
framework requires its own engine.

**Expressions via `ast`, not a grammar.** Template expressions are parsed by the standard
library `ast` module and evaluated by an allow-list interpreter. This reuses a battle-tested
parser, gives good error messages, and makes the "no arbitrary code" property easy to audit
(one `evaluate` method, no `eval`).

**`contextvars` instead of thread locals.** `request`, `g` and `current_app` are
`ContextVar`-backed proxies, so they work correctly with threaded servers, thread pools and
asyncio tasks, and they fail loudly (with an explanatory `RuntimeError`) outside a request.

**No blueprints, no ORM, no CLI generator beyond `new`.** Keeping the surface small is a
feature at this stage; blueprints and a session system are the natural next additions.

**Config is a dict.** A `dict` subclass with attribute access is easy to inspect, dump,
serialise and override in tests — no descriptor magic, no import-time side effects.

## Implemented vs. planned

**Implemented and tested (582 tests):** routing with 7 converters, all HTTP methods,
automatic `OPTIONS`/`HEAD`, trailing-slash redirects, `url_for`; JSON/urlencoded/multipart
request parsing; response types including streaming and cookies; templates with
inheritance/partials/filters/autoescape; static files with conditional requests; WSGI
compliance (verified with `wsgiref` and Gunicorn); middleware stack; configuration from
env/files/objects; error handlers; `before/after/teardown` hooks; `context_processor`;
template filters/globals; custom converters; development server with reloader; CLI with
`run`, `routes`, `new`, `version`; packaging, typing (`py.typed`), README, examples.

**Planned / deliberately not implemented yet** (each would need design work and tests):
sessions and flashes, request blueprints/modules, WebSocket/ASGI support, HTTP range
requests, template macros and custom tags, i18n helpers, an ORM/DB layer, CSRF helpers,
authentication, background tasks, multipart streaming to disk, and a `--workers` production
runner (use Gunicorn/Waitress).

## Development

```console
$ pip install -e ".[dev]"
$ ./scripts/check.sh             # lint, format, types, tests, build, twine, install rehearsal
$ ./scripts/verify_install.sh    # only the install/use rehearsal (clean venv, real HTTP)
```

The individual commands:

```console
$ ruff check .                # linting
$ ruff format --check .       # formatting
$ mypy                        # strict type checking of the myframework package
$ pytest -q                   # tests
$ python -m build             # sdist + wheel in dist/
```

`mypy` runs in `strict` mode over the package and is clean. CI configuration lives in
`.github/workflows/ci.yml` and runs the same commands on Python 3.10–3.13, plus a job that
installs the built wheel into a fresh virtual environment and serves the example app with
Gunicorn.

## License

MIT — see [LICENSE](LICENSE).
