Home / Cheat sheets / MAD1
Code patterns and facts collected automatically from the lessons. Print it, or read it the night before an exam or viva.
n workers multiply by npython -m http.server 8000request.args.get("k") (query), <int:id> (path), abort(404), jsonify(x) gives 200 and application/jsoncurl -i URL, curl -X POST URL -H "Content-Type: application/json" -d '{"a": 1}'<!DOCTYPE html><html><head><title></title></head><body></body></html><link rel="stylesheet" href="s.css">, <script src="a.js"></script>, <a href="">, <img src="" alt="">#id 100, .class [attr] :pseudo-class 10, tag ::pseudo-element 1display: flex; justify-content: ...; align-items: ...; gap: ...https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.cssrender_template("page.html", name=value)href="{{ url_for('static', filename='style.css') }}"{% for x in xs %}...{{ loop.index }}...{% else %}empty{% endfor %}{% if a %}..{% elif b %}..{% else %}..{% endif %}{% extends "base.html" %} and {% block content %}...{{ super() }}{% endblock %}{% macro name(arg, opt='x') %}...{% endmacro %} then {{ name(1) }}{%- ... -%}; comment: {# ... #}request.form.get("k"), request.args.get("k"), request.method{{ items|length }}; default: {{ x|default('n/a') }}string.Template: $name, substitute() (KeyError) / safe_substitute()CREATE TABLE t(id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, n INTEGER DEFAULT 0 CHECK(n>=0));SELECT cols FROM t JOIN u ON t.id=u.t_id WHERE ... GROUP BY ... HAVING ... ORDER BY ... LIMIT n;COUNT SUM AVG MIN MAX; NULL test: IS NULLsqlite:///name.sqlite3; memory: sqlite:///:memory:db = SQLAlchemy(app); models extend db.Model; db.Column(db.String(80), nullable=False, unique=True)db.relationship("Child", backref="parent") plus db.ForeignKey("parent.id") on the childdb.session.add(obj), db.session.commit(), db.session.rollback(), db.session.delete(obj)Model.query.all() / .first() / .filter_by(a=1) / .filter(Model.a > 1) / .order_by(...) / .count()db.session.query(func.max(M.col)).scalar()with app.app_context(): db.create_all()@app.route("/x/<int:id>", methods=["GET", "POST"])request.args.get("q"), request.form.get("f"), request.json, request.methodreturn "text", 201; return {"a": 1}; return jsonify(list)redirect(url_for("endpoint", arg=1)); abort(404)@app.errorhandler(404); flash("msg"); get_flashed_messages()app.secret_key = "..."; session["k"] = v; session.get("k"); session.pop("k", None)Blueprint("name", __name__, url_prefix="/p"); app.register_blueprint(bp)db.init_app(app); def create_app(): ...; return apppython -m venv venv; pip install -r requirements.txt; pip freeze > requirements.txtapi = Api(app); api.add_resource(Cls, "/x", "/x/<int:id>")class Cls(Resource): def get(self, id): return {...}, 200parser = reqparse.RequestParser(); parser.add_argument("n", type=int, required=True, location="json"); args = parser.parse_args()@marshal_with({"id": fields.Integer, "name": fields.String})abort(404, message="...") from flask_restfulcurl -X POST URL -H "Content-Type: application/json" -d "{\"a\":1}"; curl -v URLrequests.post(URL, json={...}), .status_code, .json()openapi: 3.0.3, info, paths: /x: get: parameters/responses, components: schemaslogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')breakpoint(); pdb: n, s, c, p x, l, q; flask --app app shellCREATE INDEX idx ON t(col); EXPLAIN QUERY PLAN SELECT ...; SCAN vs SEARCH USING INDEXCREATE VIRTUAL TABLE t USING fts5(a, b); WHERE t MATCH 'word OR pre*'@cache.cached(timeout=60), @cache.memoize(), cache.delete(key), cache.clear()Cache-Control: public, max-age=60, ETag and If-None-Match give 304<script src="app.js" defer></script>document.getElementById("id"), document.querySelector("#id .cls"), querySelectorAll("li")el.textContent, el.innerHTML, el.style.fontWeight = "bold", el.classList.add("x")const li = document.createElement("li"); ul.appendChild(li)el.addEventListener("click", e => { e.preventDefault(); })JSON.parse(text), JSON.stringify(obj)const res = await fetch(url, {method:"POST", headers:{"Content-Type":"application/json"}, body: JSON.stringify(data)}), res.ok, res.status, await res.json()localStorage.setItem(k, v), getItem(k), removeItem(k)display: block, inline, inline-block (side by side), flex (row)generate_password_hash(pw) and check_password_hash(stored, pw) from werkzeug.securitylogin_user(user), logout_user(), @login_required, current_user, @login_manager.user_loader@roles_required('admin') (all), @roles_accepted('a','b') (any)session['k'] = v, session.pop('k', None), app.config['SECRET_KEY'] = os.environ['SECRET_KEY']SESSION_COOKIE_HTTPONLY = True, SESSION_COOKIE_SECURE = True, SESSION_COOKIE_SAMESITE = "Lax"Set-Cookie: session=...; HttpOnly; Secure; SameSite=Laxcur.execute("select * from u where name=?", (n,)){{ x }} escapes; {{ x|safe }} does notpip install pytest pytest-cov; run: pytest, pytest -v, pytest -x, pytest file.py::test_name-k name_part, -m marker, -m "not slow", -m "a and b"@pytest.fixture (use yield for teardown); parametrize: @pytest.mark.parametrize("a,b", [(1,2),(3,4)])assert x == y, pytest.approx(0.3), with pytest.raises(Err):, tmp_pathapp.test_client(); client.get("/"); client.post("/x", data={...}); client.post("/api", json={...}).status_code, .data (bytes), .get_json(), .headers["Location"]{"TESTING": True, "SQLALCHEMY_DATABASE_URI": "sqlite:///:memory:"}from unittest.mock import patch, MagicMock; @patch("module.name")pytest --cov=app --cov-branch --cov-report=term-missing<meta charset="utf-8"> and <meta name="viewport" content="width=device-width, initial-scale=1">localStorage.setItem(k, v), getItem(k), removeItem(k); use JSON.stringify / JSON.parserole, aria-label, aria-livews:// / wss:// WebSocket; new EventSource(url) for SSE; navigator.serviceWorker.register("/sw.js")customElements.define("my-tag", Class) (name has a hyphen)git config --global user.name "N", git config --global user.email "e"git init, git status, git add ., git commit -m "msg", git log --oneline, git diffgit branch, git branch x, git checkout x or git switch x, git checkout -b x, git merge x, git branch -d xgit clone URL, git remote add origin URL, git push -u origin main, git pullgit rm --cached file; ignore: .gitignorepython -m venv venv, pip freeze > requirements.txt, pip install -r requirements.txtos.environ.get("NAME", "default")gunicorn -w 4 -b 127.0.0.1:8000 app:app; nginx proxy_pass http://127.0.0.1:8000;docker build -t myapp ., docker run -p 8000:8000 myapp, docker compose upflask db init, flask db migrate -m "msg", flask db upgrade, flask db downgrade