# Fix "AttributeError: module 'cgi' has no attribute 'escape'" on Python 3.8 and Later

Yes. An agent moves cgi.escape() to html.escape(), and checks each call for the quote default that changes what the escaped text contains.

[Run this on Rush](https://cloud.getrush.ai/run/fix-cgi-escape-attribute-error/cgi/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

`cgi.escape` was deprecated in Python 3.2 and removed in 3.8. The documented replacement is `html.escape`, and the names are close enough that most fixes are a rename. The two functions do not have the same default. `cgi.escape(s)` converted `&`, `<` and `>` and left quotation marks alone unless the caller passed `quote=True`, and even then it converted only the double quote. `html.escape(s)` converts both kinds of quote unless the caller passes `quote=False`: a double quote becomes `&quot;` and an apostrophe becomes `&#x27;`. A rename therefore changes the output for every string that contains a quote. Usually that is an improvement. Sometimes it corrupts data. The agent decides call by call.

seecloud/rci, a small CI service built on aiohttp, has the pattern where it matters. `rci/task.py` imports `cgi` and, in `Task.to_dict`, returns `"subject": cgi.escape(self.event.subject)` and `"project": cgi.escape(self.event.project)`. The subject comes from the change that triggered the build, set in `rci/services/gerrit.py` from the event's `change.subject`, so it is text written by whoever pushed the commit. `rci/services/monitor/service.py` then sends the dictionary to browsers as JSON over a websocket in `taskUpdate` messages. The escaping is applied to the data itself, on the server, and not at the point where a page renders it.

That decides what the agent does. With `html.escape` and its default, a commit titled `Don't retry "flaky" jobs` is sent as `Don&#x27;t retry &quot;flaky&quot; jobs`. A client that inserts the field as markup shows it correctly, and is now also safe inside an attribute. A client that sets it as text, or anything else that reads the same JSON, shows the entities literally. The agent reads the consumer to see which it is. When it cannot tell, it keeps the old output exactly with `html.escape(s, quote=False)` and reports the stricter form as a separate, recommended change with the reason. It never switches the default without saying so.

It also checks what else the import needs. The whole `cgi` module was removed in Python 3.13, so `import cgi` fails there before any function is called, and the agent deletes the import once the last use is gone. rci's `tox.ini` lists `py34,py35` and its `.travis.yml` tests Python 3.5, so nothing in the project's own automation would have shown the removal. The agent runs `python -m unittest discover tests/unit`, the command `tox.ini` uses, on a current interpreter. Since `tests/unit/test_task.py` has no test for `to_dict`, it adds one that passes a subject containing `<`, `&`, a double quote and an apostrophe and pins the result.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "This project fails with \"AttributeError: module 'cgi' has no attribute 'escape'\" on Python 3.8 or later. Find every call to cgi.escape and every import of cgi in the repository. For each call, record whether it passes quote=True, where the escaped value goes next (an HTML text node, an HTML attribute, JSON sent to a client, a log line, a database column, an email body) and where the input comes from, noting any value an outside user controls. Replace each call with html.escape. Remember that the defaults differ: cgi.escape left quotes alone unless quote=True and never converted apostrophes, while html.escape converts both quote characters unless quote=False. For every call, state whether the output changes for an input containing a double quote or an apostrophe. Where the value ends up in an HTML attribute, use the default and say that this closes an injection hole. Where you cannot prove how the consumer treats the value, preserve the old output with quote=False and list the stricter form as a recommended follow-up. If escaped text is stored or compared with previously stored text, say so. Remove the cgi import when nothing else uses it, and check whether the code uses any other part of the cgi module, which Python 3.13 removed entirely. Add a test for each changed call with an input containing <, >, &, a double quote and an apostrophe. Run the tests on a current Python and include the commands and output. Open a pull request with a table of the calls and what changed for each.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request with a table that has one row per call: where the input comes from, where the output goes, the old result and the new result for the same test string, and which `quote` setting was chosen. For rci that is two rows, both feeding the websocket payload. The diff replaces the import and the two calls and adds the test. If a value reaches an HTML attribute, the row says the change fixes an attribute injection, and the description puts that row first.

A reviewer checks the rows where the output changed. Escaped text that is stored, cached, hashed or compared with older values is the case to watch, because old rows hold `'` and new ones hold `&#x27;` for the same input. The description names any such place. The reviewer also decides the follow-ups: moving escaping from the server's data to the template or client that renders it is the better design, and it is a larger change than this fix should carry.

## Run it on every Linear issue labelled python-upgrade

A team moving a service to a newer Python usually tracks each breakage as an issue. Add an automation on the Project with a `linear` trigger on `linear.issue.labeled`, the label your team uses for upgrade work, and the prompt above. The issue is added after the saved prompt as event text; it fills in no placeholder. The trigger needs a Linear connection for the automation's runner, made in the console under Settings → Connections, and fires only when the person adding the label is in your Rush org.

Keep one issue per repository, each in the Project that holds that repository. The automation's max runs per hour bounds how many start when someone labels a batch at once.

## Why run it on Rush?

Deciding each call means running the old function and the new one on the same inputs, and the old function no longer exists on a current interpreter. The agent installs a Python from before the removal next to a current one in its sandbox, feeds both the same strings, and the two outputs are kept in the session record. The table in the pull request is built from those outputs.

This is also a change where the quick fix and the careful fix produce the same diff size, so nothing in the diff shows which one was done. What separates them is the trace of each value from its source to the place it is displayed. A run writes that trace down for every call, including the ones it left unchanged, so a reviewer can check the reasoning without redoing the search.

## Frequently asked questions

### What is the exact replacement for cgi.escape(s)?

`html.escape(s, quote=False)` produces the same output for every input. `html.escape(s)` with no second argument is what the Python documentation points to, and it additionally converts double quotes to `&quot;` and apostrophes to `&#x27;`.

### What about cgi.escape(s, quote=True)?

`html.escape(s)` is the closest match, with one difference: the old function converted only the double quote, and the new one converts the apostrophe as well. That matters only if something downstream compares or stores the escaped text.

### Does this affect Python 3.13?

More so. Python 3.13 removed the entire `cgi` module, so the import line itself raises `ModuleNotFoundError`. A file that imports `cgi` only for `escape` needs the import removed as part of this fix, which the agent does.

### Will the agent change how my templates escape values?

No. It changes the calls that fail and adds tests for them. If it finds that values are escaped on the server and again in a template, or escaped in data that a client renders as text, it reports that as a finding with the affected fields.

### Does html.escape work on bytes?

No, it expects `str`. Code written for Python 2 that passes a byte string fails with a `TypeError`. The agent checks the type at each call and decodes where the encoding is known.

## More jobs like this: Turn a Linear label into a PR

- [Fix "Deprecated: Creation of dynamic property is deprecated" in PHP 8.2](https://getrush.ai/run/fix-creation-of-dynamic-property-deprecated/php/)
- [Fix "DeprecationWarning: datetime.datetime.utcnow() is deprecated" on Python 3.12](https://getrush.ai/run/fix-datetime-utcnow-deprecation-warning/datetime/)
- [Fix "[DEP0147] DeprecationWarning: fs.rmdir(path, { recursive: true }) will be removed" in Node.js](https://getrush.ai/run/fix-fs-rmdir-recursive-deprecation-warning/nodejs/)
- [Fix "AttributeError: 'HTMLParser' object has no attribute 'unescape'" in Python 3.9+](https://getrush.ai/run/fix-htmlparser-unescape-attribute-error/html-parser/)
- [Fix "AttributeError: module 'platform' has no attribute 'linux_distribution'"](https://getrush.ai/run/fix-platform-linux-distribution-attribute-error/platform/)
- [Fix "AttributeError: module 'plistlib' has no attribute 'readPlist'" in Python 3.9+](https://getrush.ai/run/fix-plistlib-readplist-attribute-error/plistlib/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
