FastAPI
FastAPI database dependency that creates an AsynSession, gives it to your endpoint/service, and rolls back the transactions if an exception happens.
the function uses yield session rather than return session because yield can perform setup before the endpoint runs and cleanup after the endpoint finishes.
How Router -> Serviccce -> CRUD connect
Router only does:
- Accept request
- validate with schema
- Call service
- Return response
- Nothing else
Service:
- Check permissions(“is this user the owner?”)
- Apply business rules(“Post must be draft before publishing”)
- Call CRUD functions
- Nothing else
CRUD :
- Raw database queries
- SELECT, INSERT, UPDATE, DELETE
- No business rules
- Noo permission checks
What information should be stored inside the JWT token payload for you CMS?
=> For registering only Three fields is required:
1. sub -> users UUID- used to fetch full user data from DB when needed
2. role -> admin or user — checked on every protected route without hitting DB
3. exp -> expiry — JWT library check this automatically
Why we use dependencies.py in fast api
-> “””dependency is something your endpoint needs in order to do its job
for eg: an endpoint might need
- a database session
- the currectly logged-in user
- an authenticated admin
- pagination parameters
- a permission check
- some reusable configuration
“””
Model Dump
model dump change pydantic objects into python dictionary.
for eg. if you have the data of
if you only want a dict then you have to convert object into dictionary.
we use
post_update.model_dump(exclude_unset=True)if we want only one field
add Cloudflare Proxy
When Cloudflare Proxy is enabled for a DNS record such as api.doko.com, the DNS process and the actual HTTP/HTTPS traffic take different paths. Suppose api.doko.com points to your DOKO VPS at 203.0.113.10. If the record is DNS-only, DNS can return 203.0.113.10 to the browser, so the browser connects directly to your VPS. But if the record is Proxied through Cloudflare, Cloudflare does not normally return your origin IP to the browser; instead, DNS returns a Cloudflare IP address. The browser therefore connects to a nearby Cloudflare Edge location first. Cloudflare can then inspect the request, apply security features such as WAF and DDoS protection, potentially serve a cached response, and if the request needs your application, forward it to your origin VPS at 203.0.113.10. Your origin then handles the request through Nginx and Django. So the flow changes from Browser → VPS when DNS-only is used to Browser → Cloudflare Edge → VPS when Proxy is enabled
DNS Records
DNS isn’t just a name -> IP . Its a set of different record types, each answering a different kind of question. “what IPv4 address,” “what IPv6 address,” “what’s the real name behind this alias,” “where does mail for this domain go,” “what text does this domain want to publish for verification purposes.” Each record type is a distinct instruction in Cloudflare’s DNS zone for your domain.
TTL and DNS Caching
what is DNS caching?
-> lets say you DNS record is api.doko.com -> 203.433.10.
your computer doesn’t necessarly have to ask DNS every time. It create unncessary DNS trafic. Instead it save temporarily in local cached. so you dont have to ask again.
What is TTL?
TTL is Time To Live. This keeps you DNS answer for time period to obtain a result before it need to refresh.
A resolve can cache the DNS answer for upto about one hour before it needs to refresh it.
Why does TTL exist?
->TTL exist to provide response with in a short period of time. If million of user search for the same DNS then it might create traffic to provide unnecessarly same information.
there is Long TTL :
-Fewer DNS lookups
- more caching
- DNS changes take longer to become visible everywhere
and Short TTL:
- more frequent DNS lookups
- changes can be picked up sooner
- more DNS queries
resolver that cached that answer may continue using it until its cache entry expires.
CDN — Content Delivery Network
CDN is a network of servers distributed in different geographic locations that can deliver content closer to user.
Imagine you DOKO origin is in kathmandu and the user is in pokhara. if there is not CDN cloudflare.
User in Pokhara
↓
Internet
↓
DOKO VPS in Kathmandu
↓
Response
Now imagine cloudflare has an edge location closer to the user.
User in Pokhara
↓
Cloudflare Edge
↓
Cached content?
↓
YES
↓
Return content
The origin doesn’t need to server the same object every time.
What is an EDge location?
-> An edge location is cloudflare netwok where request can be processed
Browser Cache vs Cloudflare Cache
->Broswer cache is stored on the user’s own device/browser. if user visit the same image again, the browser will not download it again. so the request might not even reach cloudflare.
Cloudflare caches is stored on cloudflare edge infrastructure, not on the users computer. it cached at an edge locaton, it can sever the file without asking your origin every time.
if user visit the first time Cloudflare may store the image, user A browser may also store the image, there can be two copies. then user B visit does not have the image in the browser cache. The origin does not need to be contacted, that’s one of the major benifits of CDN caching.
DNS TTL
controls how long DNS resolver can cache a DNS answer.
Broswer HTTP caching
Controls how long the browswer can consider an HTTP response fresh.
Cache-control => cache control is an HTTP response header that tells browswers and caching systems how a response may be cached and reused.
SSL/TLS Fundamentals
Why do we need HTTPS?
-> With only HTTP the communication is not encrypted. if user sends a message in the middle someone can observer the network trafic could potentially read the communication.
What is TLS?
-> TLS is transport Layer Security . It is the protocol that provides secure communication. SSL is the old protocol and TLS is new.
What does TLS provide?
-> 1. Encryption
2. Authentication
3. Integrity => TLS helps detect of encrypted data was modified in transit.
What is SSL/TLS certificate?
-> A certificate is a basically a digital identity document for a domain. It tells browswer that “This public key is associated with doko.com and a trusted certificate Authority has verified this.
5.1 What are we protecting against
-> Imaging you have api.doko.com and you have POST /api/login/ , POST /api/register/ and attackers could run 1000 times. where should we stop this traffic if cloudflare allow the django server has to process all those requests. Instead
Attacker
↓
Cloudflare
│
├── suspicious → BLOCK
│
├── suspicious but uncertain → CHALLENGE
│
└── legitimate → ALLOW
↓
Nginx
↓
Django
That’s the fundamental reason Cloudflare security exists.
5.2 DDos = Distributed Denial of service.
-> the goall is to send a much traffic or work toward a service that legitimate users can’t use it reliably.
Without cloudflare:
With cloudflare
Cloudflare can absorb/filter traffic before it reaches you infrastructure.
5.3 — DDoS vs WAF
DDoS protection = Is this HTTP request look like an attack? = protect availability.
WAF = Does this HTTP request look like an attack? = A WAF can inspect HTTP requests apply and apply security rules.
5.4 WAF = web application Firewall
It is a security checkpoint for HTTP/HTTPS traffic.
{ “email”: “user@example.com”, “password”: “hello” }
But an attacker may attempt things such as:
- SQL injection
- XSS
- malicious payloads
- protocol abuse
- suspicious automated requests
- known attack patterns
A WAF can use managed security rules to detect many common attack patterns.
Get shila’s stories in your inbox
Join Medium for free to get updates from this writer.
5.5 Firewall rules
-> A firewall rule is basically a decision you tell cloudflare to make about incoming requests. Cloudflare lools at information about the request such as the IP address, country, URL path, HTTP method or other request properties and then decides what to do with it. The important point is that decision happens at Cloudflare, before the request reaches you Nginx and Django server.
5.6 Rate Limiting:
Rate Limiting is different from a firewall rule. Firewall rule usually ask “Does this request match a condition” while Rate limiting ask “How many request is this client making within a period of time?”. if someone request POST /api/login/ if they for the first time then no need to block them, instead establish a limit 20 request per min, per client. If excessive request then it can be stopped before they consume your Django resources.
5.7 Security Headers
-> Headers are another important security layer. Tells browsers to prefer HTTPS for your domain. Helps prevent browsers from MIME-sniffing certain resources and can restrict what kinds of resources a page is allowed to load.
Webhooks
one system sends an HTTP request to another system when an event happend. Webhooks create an important security problem “How do you know this request really came from the payment provider? Cloudflare can provide an additional traffic/security layer, but webhook authenticity should still be verified by your application according to the providers specification.
7.1 CLoudflare Workers
What problem do workers solve?
->
suppose someone visit https://api.doko.com/api/products/ the request reaches cloudflare first . cloudflare can do things like TLS,DDos Protections, WAF, Firewall, RateLimiting, Caching. the important question is : What if we want cloudflare itself to execute some code before sending the request to django? That’s where Workers come in.
What Exactly is a Worker?
-> A cloudflare worker is a piece of application code that cloudflare executes on its infrastructure.
The worker can decide what should happen to the request. Worker is a programmmable logic running inside Cloudflare edge network
Why is it called edge?
-> Imagine your Django server is in singapore and your user in Nepal the request might travel .
Nepal ↓ Internet ↓ Singapore ↓ Django
But cloudflare has infrastructure distributed around the world. Workers execute code at Cloudflare edge instead of requiring that code to run on VPS. Worker can inspect the incoming request.
Cloudflare
├── DDoS
├── WAF
├── Firewall
├── Rate limiting
├── Cache
└── Worker
Workers can modify responses and modify request . It also work on the response coming back. Workers can sit between client-origin and inspect/transform traffic in both direction. Database is not directly attacted to worker. Workers are compute. A worker can read/write values in KV. for eg: product:123 ↓ { “name”: “Vintage Jacket”, “price”: 1800 }. The worker could retrieve the data without contacting Django.
Worker + R2 :
R2 is object storage.
A worker could interact with those objects. This is much more appropriate for large files than trying to store images directly in KV.
Worker + Queue
A buyer places an order. You dont necessarily wan the users request to wait for every secondary task. Instead :
The queue could eventually trigger work such as:
send notification
generate event
process webhook
This is why Queues are separate from workers. A Worker perform computation. A Queue lets you put work aside for processing asynchronously.
16. Where does Wrangler come in?
-> You will eventually write Worker code locally.
my-worker/
├── src/
│ └── index.js
├── wrangler.toml
└── package.json
Then you need a way to create Worker
run Worker locally
configure Worker
deploy Worker
view Worker information
manage bindings
thats where wrangler comes in
7.2 Edge Computing
-> Suppose DOKO django server is hoster on a VPS in singapore. The path is User in Nepal
↓
Internet
↓
Singapore
↓
Django
↓
PostgreSQL
↓
Response
↓
Nepal
Your application is running in one central location. that central server is often called the origin. Now imagine cloudflare has infrastructure close to the user.
Cloudflare network
Nepal user → [nearby Cloudflare edge]
↓
Singapore origin
The edge is the infrastructure closer to the users.
2. Why we need edge computing?
-> the main problem is distance. If the requested operation can be completed at the edge, you don’t need to send the request all the way to origin. Fewer network trips can mean lower latency. Edge computing is not automatically fast for every application. The worker close to nepal doesn’t magically make Postgresql close to Nepal
3. Edge computing vs Traditional cloud computing
-> CENTRAL SERVER
Users ────────→ AWS/VPS ────────→ Database
│
├── Nepal
├── India
├── Japan
└── USA
all the users ultimately communicate with the same central infrastructure.
with edg computing:
Some computation can happen at those edge locations.
Edge computing means performing computation closer to where users or data are located, rather than sending every operation to a centralized origin. Edge is Cloudflare’s distributed infrastructure that handles traffic closer to users.
7.3 Wrangler — Cloudflares Developer CLI
Wrangler is cloudflare command-line tool for developing, configuring, testing and deploying workers and other cloudflare resources.
wrangler.Jsomc?
Wramdle.Jsons is the configuration file your worket.
7.4 KV — Key-Value Storage
why do we need KV?
->Worker can execute code: But what if it needs to remember something?
The Worker needs storage. Cloudflare KV provides globally distributed key-value storage.
KV is conceptually similar:
KEY VALUE
──────────────────────────────
maintenance_mode false
homepage_message Welcome to DOKOBut KV is a Cloudflare-managed distributed storage service, not a Python dictionary sitting in your Worker process.
What is KV good for?
-> KV is especially useful for data that is:
- relatively small
- accessed by key
- read frequently
- not dependent on relational queries
S3
=> S3 is not a cloudflare product. Amazon s3 is AWS object storage service. Cloudflare has a similar service called Cloudflare R2.
Suppose DOKO has a product : Blue denim jacket.
you need to store its images somewhere. Your django database should not store the actual image file. Instead:
S3/R2 is that object storage.
What is S3?
=> S3 stands for simple storage service. It is designed to store objects such as :
- Image
- Videos
- PDF
- Documents
-backups
- datasets
- Ml model files
- static assets
you organize these object inside buckets. For examples:
Bucket: Container for your files
Object: Individual file
Object key:File’s path/name
Storage: Where the file physically livesCD
URL: Address used to access the object
So Where does cloudflare come in?
Cloudflare offers R2, which is an object storage service designed to be compatible with the S3 API.
AWS
│
└── S3
└── Object Storage
Cloudflare
│
└── R2
└── Object Storage
└── S3-compatible API
It doesn’t neessarily mean AWS S3. It could be:
AWS S3
Cloudflare R2
MinIO
Backblaze B2
Wasabi
Why Would you use R2/S3 in your application?
=> If Django server receives: POST /products/
with product name, price, description, image
VPS
│
├── Django
├── PostgreSQL
├── React
└── media/
├── jacket1.jpg
├── dress1.jpg
└── shoes1.jpg
this can work for an MVP. But as you application grows. its better to seperate application/server storage from file storage:








