Merge pull request #675 from prodev717/cheatsheet-flask-fastapi-htmx

created cheatsheet for flask, fastapi and htmx
This commit is contained in:
Fechin authored and GitHub committed 2025-06-09 14:15:00 +08:00
commit 6b1af2f8d2
3 files changed
+725

No files matched your search

+251
View File
@@ -0,0 +1,251 @@
---
title: FastAPI
date: 2025-06-07 18:40:00
background: bg-[#059669]
tags:
- web
- python
- backend
categories:
- Programming
intro: |
A concise cheatsheet for FastAPI, a fast and modern web framework for building APIs with Python 3.7+.
plugins:
- copyCode
---
## Getting Started {.cols-3}
### Install & Run
```bash
pip install fastapi uvicorn
uvicorn main:app --reload
```
### Hello World
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello FastAPI"}
```
### CLI Run Hint
```bash
uvicorn main:app --reload
```
## Routing & Parameters {.cols-3}
### Path Parameter
```python
@app.get("/items/{id}")
def read(id: int):
return {"id": id}
```
### Query Parameter
```python
@app.get("/search")
def find(q: str = "default"):
return {"q": q}
```
### Optional Query
```python
@app.get("/filter")
def filter_data(limit: int = 10, active: bool = True):
return {"limit": limit, "active": active}
```
## Request Body & Validation {.cols-3}
### Using Pydantic
```python
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
```
### JSON Body
```python
@app.post("/items/")
def create(item: Item):
return item
```
### Response Model
```python
@app.post("/items/", response_model=Item)
def create(item: Item):
return item
```
## Forms, Files, Headers {.cols-3}
### Form Input
```python
from fastapi import Form
@app.post("/login")
def login(user: str = Form(...)):
return {"user": user}
```
### File Upload
```python
from fastapi import UploadFile, File
@app.post("/upload")
def upload(f: UploadFile = File(...)):
return {"filename": f.filename}
```
### Headers / Cookies
```python
from fastapi import Header, Cookie
@app.get("/info")
def info(ua: str = Header(None)):
return {"UA": ua}
```
## Middleware & Dependency {.cols-2}
### Middleware
```python
@app.middleware("http")
async def log_req(req, call_next):
res = await call_next(req)
return res
```
### Dependency
```python
from fastapi import Depends
def auth(token: str = ""):
if token != "xyz": raise HTTPException(401)
return True
@app.get("/secure")
def secure(_: bool = Depends(auth)):
return {"secure": True}
```
## Errors & JSON API {.cols-2}
### HTTP Error
```python
from fastapi import HTTPException
@app.get("/err")
def error():
raise HTTPException(404, "Not Found")
```
### JSON API
```python
from fastapi import FastAPI
@app.get("/json")
def get_data():
return {"status": "ok"}
```
## Templates & Static {.cols-2}
### Mount Static
```python
from fastapi.staticfiles import StaticFiles
app.mount("/static", StaticFiles(directory="static"), name="static")
```
### Jinja2 Support
```python
from fastapi.templating import Jinja2Templates
templates = Jinja2Templates("templates")
```
## Routers & Structure {.cols-2}
### Routers (Blueprints)
```python
from fastapi import APIRouter
router = APIRouter()
@router.get("/")
def admin():
return {"admin": True}
app.include_router(router, prefix="/admin")
```
### Folder Layout
```bash
project/
├── main.py
├── static/
├── templates/
├── routers/
│ └── admin.py
└── models/
```
## Docs & Status {.cols-2}
### Built-in Docs
* Swagger: `/docs`
* ReDoc: `/redoc`
### Custom Status Code
```python
from fastapi import status
@app.post("/create", status_code=status.HTTP_201_CREATED)
def create():
return {"msg": "Created"}
```
+262
View File
@@ -0,0 +1,262 @@
---
title: Flask
date: 2025-06-07 19:05:00
background: bg-[#3598db]
tags:
- web
- python
- backend
categories:
- Programming
intro: |
A concise cheatsheet for Flask, a lightweight WSGI web application framework for Python.
plugins:
- copyCode
---
## Getting Started {.cols-3}
### Install Flask
```bash
pip install flask
```
### Hello World
```python
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, World!"
app.run(debug=True)
```
### Flask CLI
```bash
export FLASK_APP=app.py
flask run
```
## App Config & Environment {.cols-3}
### App Object
```python
from flask import Flask
app = Flask(__name__)
```
### Configuration
```python
app.config["DEBUG"] = True
app.config.from_pyfile("config.py")
```
### Common Config Keys
| Key | Description |
| | -- |
| `DEBUG` | Enable debug mode |
| `SECRET_KEY` | For sessions/cookies |
| `ENV` | Set to 'development' |
## Routing & Methods {.cols-3}
### Basic Route
```python
@app.route("/")
def home():
return "Home"
```
### Methods
```python
@app.route("/login", methods=["GET", "POST"])
def login():
return "Login"
```
### Dynamic Routes
```python
@app.route("/user/<name>")
def user(name):
return f"User: {name}"
```
## Request & Response {.cols-3}
### Request Object
```python
from flask import request
@app.route("/data", methods=["POST"])
def data():
return request.json
```
### Request Attributes
* `request.args`: Query params
* `request.form`: Form data
* `request.json`: JSON body
### Custom Response
```python
from flask import make_response
@app.route("/custom")
def custom():
res = make_response("Custom", 200)
res.headers["X-Test"] = "True"
return res
```
## Templates & Static {.cols-3}
### Render Template
```python
from flask import render_template
@app.route("/")
def page():
return render_template("index.html", name="Flask")
```
### Jinja Syntax
```html
<h1>Hello {{ name }}</h1>
{% if name %}<p>Hi!</p>{% endif %}
```
### Static Files
```html
<link href="{{ url_for('static', filename='style.css') }}">
```
## Sessions & Cookies {.cols-2}
### Using Sessions
```python
from flask import session
app.secret_key = "secret"
@app.route("/login")
def login():
session["user"] = "admin"
return "Logged in"
```
### Access Cookies
```python
from flask import request, make_response
@app.route("/cookie")
def cookie():
resp = make_response("Set cookie")
resp.set_cookie("site", "Flask")
return resp
```
## JSON API & Middleware {.cols-2}
### JSON Response
```python
from flask import jsonify
@app.route("/api")
def api():
return jsonify(message="Hello")
```
### Middleware
```python
@app.before_request
def before():
print("Before")
@app.after_request
def after(res):
print("After")
return res
```
## Error Handling & Blueprints {.cols-2}
### Error Handling
```python
@app.errorhandler(404)
def not_found(e):
return "Page not found", 404
```
### Blueprint
```python
from flask import Blueprint
admin = Blueprint("admin", __name__, url_prefix="/admin")
@admin.route("/")
def dash():
return "Admin"
app.register_blueprint(admin)
```
## Project Structure {.cols-2}
### File Structure
```bash
project/
├── app.py
├── templates/
│ └── index.html
├── static/
│ └── style.css
└── config.py
```
### Run Server
```bash
python app.py
# or using CLI
export FLASK_APP=app.py
flask run
```
+212
View File
@@ -0,0 +1,212 @@
---
title: HTMX
date: 2025-06-07 19:30:00
background: bg-[#ff5f4d]
tags:
- frontend
- javascript
- htmx
categories:
- Programming
intro: |
A modern, minimal JavaScript library that allows you to create dynamic web interfaces using HTML attributes.
plugins:
- copyCode
---
## Getting Started {.cols-3}
### CDN Import
```html
<script src="https://unpkg.com/htmx.org@1.9.2"></script>
```
### Basic Usage
```html
<button
hx-get="/hello"
hx-target="#result">
Say Hi
</button>
<div id="result"></div>
```
### Server Response
```html
<!-- /hello response -->
<p>Hello from server</p>
```
## Core Attributes {.cols-3}
### `hx-get`, `hx-post`, etc.
```html
<a hx-get="/page">Load Page</a>
<form hx-post="/submit"></form>
```
### `hx-target`
```html
<button hx-get="/data" hx-target="#box"></button>
<div id="box"></div>
```
### `hx-trigger`
```html
<input
hx-get="/search"
hx-trigger="keyup changed delay:300ms"
hx-target="#results" />
```
## Swap & Out of Band {.cols-3}
### `hx-swap`
```html
<div
hx-get="/frag"
hx-swap="innerHTML">
</div>
```
* `outerHTML`
* `innerHTML`
* `beforebegin`, `afterbegin`, etc.
### `hx-swap-oob`
```html
<div hx-swap-oob="true" id="msg"></div>
```
*Useful for global updates from partials.*
### Swap Modifiers
```html
hx-swap="outerHTML transition:true swap:1s"
```
## Forms & Events {.cols-3}
### Auto POST on Submit
```html
<form hx-post="/submit" hx-target="#status">
<input name="name" />
<button type="submit">Send</button>
</form>
<div id="status"></div>
```
### `hx-include`
```html
<input id="user-id" name="id" />
<button
hx-post="/update"
hx-include="#user-id">
Update
</button>
```
### `hx-vals`
```html
<button
hx-post="/save"
hx-vals='{"id": 42, "active": true}'>
Save
</button>
```
## Advanced Features {.cols-3}
### Loading Indicator
```html
<button
hx-get="/load"
hx-indicator="#spinner">
Load
</button>
<div id="spinner" class="htmx-indicator">Loading...</div>
```
### `hx-push-url`
```html
<a hx-get="/page" hx-push-url="true">Go</a>
```
### Polling
```html
<div hx-get="/time" hx-trigger="every 5s"></div>
```
## Events & Extensions {.cols-3}
### Listen to Events
```js
document.body.addEventListener('htmx:afterSwap', e => {
console.log("Swap complete");
});
```
### Event Hooks
* `htmx:beforeRequest`
* `htmx:afterSwap`
* `htmx:responseError`
### Extensions
```html
<script src="https://unpkg.com/htmx.org/dist/ext/json-enc.js"></script>
<form hx-post="/api" hx-ext="json-enc"></form>
```
## Example Use Case {.cols-2}
### Python Backend (Flask)
```python
@app.route("/hello")
def hello():
return "<p>Hello, HTMX!</p>"
```
### HTML Client
```html
<button
hx-get="/hello"
hx-target="#msg">
Click
</button>
<div id="msg"></div>
```