diff --git a/source/_posts/fastapi.md b/source/_posts/fastapi.md new file mode 100644 index 0000000..faca64f --- /dev/null +++ b/source/_posts/fastapi.md @@ -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"} +``` + diff --git a/source/_posts/flask.md b/source/_posts/flask.md new file mode 100644 index 0000000..c63797e --- /dev/null +++ b/source/_posts/flask.md @@ -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/") +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 +

Hello {{ name }}

+{% if name %}

Hi!

{% endif %} +``` + +### Static Files + +```html + +``` + + + +## 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 +``` diff --git a/source/_posts/htmx.md b/source/_posts/htmx.md new file mode 100644 index 0000000..08b452e --- /dev/null +++ b/source/_posts/htmx.md @@ -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 + +``` + +### Basic Usage + +```html + +
+``` + +### Server Response + +```html + +

Hello from server

+``` + + + +## Core Attributes {.cols-3} + +### `hx-get`, `hx-post`, etc. + +```html +Load Page +
+``` + +### `hx-target` + +```html + +
+``` + +### `hx-trigger` + +```html + +``` + + + +## Swap & Out of Band {.cols-3} + +### `hx-swap` + +```html +
+
+``` + +* `outerHTML` +* `innerHTML` +* `beforebegin`, `afterbegin`, etc. + +### `hx-swap-oob` + +```html +
+``` + +*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 +
+ + +
+
+``` + +### `hx-include` + +```html + + +``` + +### `hx-vals` + +```html + +``` + + + +## Advanced Features {.cols-3} + +### Loading Indicator + +```html + +
Loading...
+``` + +### `hx-push-url` + +```html +Go +``` + +### Polling + +```html +
+``` + + + +## 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 + +
+``` + + + +## Example Use Case {.cols-2} + +### Python Backend (Flask) + +```python +@app.route("/hello") +def hello(): + return "

Hello, HTMX!

" +``` + +### HTML Client + +```html + +
+``` +