<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by İnan DELİBAŞ on Medium]]></title>
        <description><![CDATA[Stories by İnan DELİBAŞ on Medium]]></description>
        <link>https://medium.com/@inandelibas?source=rss-4b3036116dc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KP1k0wsMHc4pcnpckF0q1A.jpeg</url>
            <title>Stories by İnan DELİBAŞ on Medium</title>
            <link>https://medium.com/@inandelibas?source=rss-4b3036116dc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 22:33:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@inandelibas/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Deploy a FastAPI App to FastAPI Cloud with the CLI]]></title>
            <link>https://medium.com/@inandelibas/how-to-deploy-a-fastapi-app-to-fastapi-cloud-with-the-cli-e0a06e1ea6e8?source=rss-4b3036116dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0a06e1ea6e8</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[deploy-fastapi]]></category>
            <category><![CDATA[fastapicloud]]></category>
            <dc:creator><![CDATA[İnan DELİBAŞ]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 14:46:38 GMT</pubDate>
            <atom:updated>2026-11-04T14:46:38.234Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNQVZMP-44xpWef11vxKTg.png" /></figure><p>FastAPI Cloud is now generally available. If your FastAPI app already runs locally, you can start the deployment with one command.<br>More details: <a href="https://fastapicloud.com/">FastAPI Cloud</a></p><p>Let’s create a small FastAPI app and deploy it to FastAPI Cloud via CLI. So, we need a <strong>/health</strong> endpoint that we can call locally and again after deployment.</p><h4><strong>1. Create a FastAPI app</strong></h4><blockquote>I will call the project <strong>fastapi-cloud-demo</strong>. If you’re starting from scratch, <br>install uv and run the commands below. <a href="https://docs.astral.sh/uv/getting-started/installation/">uv installation guide</a></blockquote><pre>uv init fastapi-cloud-demo --bare<br>cd fastapi-cloud-demo<br>uv add &quot;fastapi[standard]&quot;</pre><blockquote>The —bare flag creates a minimal <strong>pyproject.toml</strong>. <br>The <strong>fastapi[standard]</strong> install includes the CLI we’ll use to deploy.<br>More details: <a href="https://fastapi.tiangolo.com/tutorial/#install-fastapi">FastAPI installation guide</a></blockquote><p>Create <strong>main.py</strong> in the project directory and add this health endpoint:</p><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.get(&quot;/health&quot;)<br>def health():<br>    return {&quot;status&quot;: &quot;ok&quot;}</pre><p>This app is enough to follow the login and deployment steps.</p><h4>2. Run the app locally</h4><p>Check the app before deploying, run:</p><pre>uv run fastapi dev main.py</pre><p>Open <a href="http://127.0.0.1:8000/health">http://127.0.0.1:8000/health</a> in your browser. You should see {&quot;status&quot;:&quot;ok&quot;}.</p><h4>3. Deploy with the FastAPI CLI</h4><p>From the project directory, run:</p><pre>uv run fastapi login</pre><figure><img alt="FastAPI Cloud CLI Authorize Screen" src="https://cdn-images-1.medium.com/max/1024/1*oK-JLKjk4PM-XnzW-6Cf-g.png" /><figcaption>FastAPI CLI authorization screen</figcaption></figure><p>The CLI opens the browser. Sign in to FastAPI Cloud and review the CLI authorization request. If you identify it, click Authorize and return to your terminal.</p><blockquote>It stores credentials locally, so you don&#39;t need to copy a token into your project.</blockquote><p>When you return to your terminal, you will see:</p><pre>  FastAPI Cloud<br><br> 🔐 Login to FastAPI Cloud<br><br>    Opening<br>    https://dashboard.fastapicloud.com/device?code=******************<br><br>    Now you are logged in! 🚀</pre><p>Now it&#39;s time to deploy (if it&#39;s Friday, no deploy, please)!</p><pre>uv run fastapi deploy</pre><p>Select the team you want to deploy to:</p><pre><br>  FastAPI Cloud<br><br> 📁 Setting up and deploying /Users/xxxx/Documents/project/fastapi-cloud-demo<br><br> 🏢 Select the team you want to deploy to:<br>    Filter:<br><br>    ● John Doe</pre><p>This is our first deployment, so we will create a new app.</p><pre> 📦 Do you want to create a new app?<br>    ● Yes  ○ No</pre><p>Write the app name or press Enter to use the suggested name:</p><pre> ✏️ What&#39;s your app name?<br>    fastapi-cloud-demo</pre><p>The CLI asks where pyproject.toml lives. In our demo project, it is in the root. So, we will leave the field blank and press Enter.</p><pre> 📂 Directory where your app&#39;s pyproject.toml file lives (e.g. src, backend):<br>    Leave empty if pyproject.toml is in the current directory</pre><p>Review the deployment summary</p><pre> 📋 Deployment configuration:<br><br>    Team: John Doe<br>    App name: fastapi-cloud-demo<br>    Directory: .<br><br> 👀 Does everything look right?<br>    ● Yes, start the deployment!<br>    ○ No, let me start over</pre><p>Build complete!</p><pre><br> 🐔 App created successfully! App slug: fastapi-cloud-demo-xxxxxx<br><br> 🚀 Deploying app...<br><br> 🚀 Build complete!<br><br> ✅ Ready the chicken! 🐔<br><br>    Your app is ready at https://fastapi-cloud-demo-xxxxxx.fastapicloud.dev</pre><h4>4. Verify the deployed app</h4><p>I used the same <strong>/health</strong> check from earlier, this time with the URL FastAPI Cloud printed in my terminal. Replace DEPLOYED_APP_URL with yours.</p><pre>curl -fsS DEPLOYED_APP_URL/health</pre><blockquote>You should get {&quot;status&quot;:&quot;ok&quot;} back. Also, you can open /docs at the same URL to try the API in your browser.</blockquote><blockquote>If the build fails, check the terminal output.<br>If the deploy finishes but /health fails, check the runtime logs in the FastAPI Cloud dashboard.</blockquote><h4>5. After the first deploy</h4><p>The app is live, and I’m happy to stop here for a demo. If I keep it running, here’s what I’d look at next.</p><p><strong>Continuous deployment (CD): </strong>How do I ship the next change without running the deploy command by hand? <a href="https://fastapicloud.com/docs/source-control/github-integration/">GitHub integration</a></p><p><strong>Environment variables</strong>: I’d set the database host and credentials through the app’s environment variables. <a href="https://fastapicloud.com/docs/builds-and-deployments/environment-variables/">Environment variables</a></p><p><strong>Scaling: </strong>I’d check how the app scales up when traffic picks up and back down when things get quiet. <a href="https://fastapicloud.com/docs/advanced-features/autoscaling/">Autoscaling</a></p><p><strong>Custom domains: </strong>I’d give the API an address of its own, like api.example.com.<a href="https://fastapicloud.com/docs/advanced-features/custom-domains/">Custom domains</a></p><p><strong>Observability: </strong>Once people start using the API, I’d watch request volume, response times, and errors. <a href="https://fastapicloud.com/docs/monitoring-and-performance/metrics/">Metrics</a></p><p><strong>Logs: </strong>If a build fails, I’d open the build logs. If a request fails after deploy, I’d start with the runtime logs. <a href="https://fastapicloud.com/docs/monitoring-and-performance/logs/">Build and runtime logs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0a06e1ea6e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Benchmarked FastAPI With and Without the GIL]]></title>
            <link>https://medium.com/@inandelibas/i-benchmarked-fastapi-with-and-without-the-gil-360291494420?source=rss-4b3036116dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/360291494420</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[global-interpreter-lock]]></category>
            <dc:creator><![CDATA[İnan DELİBAŞ]]></dc:creator>
            <pubDate>Mon, 04 May 2026 22:25:48 GMT</pubDate>
            <atom:updated>2026-05-04T22:25:48.798Z</atom:updated>
            <content:encoded><![CDATA[<h4>FastAPI 0.136.0 now supports free-threaded Python, but does it actually change API performance in real workloads?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5Z3Gx6unLk5MI0BQNIivQ.png" /></figure><p>As soon as I realized that <strong>FastAPI 0.136.0 </strong>would be using free-threaded Python, I thought this could potentially be a game changer.</p><p>It is very common for people to choose <strong>FastAPI</strong> for its speed/performance and therefore any potential changes to its concurrent processing are well worth exploring.</p><p>However, backend applications do not care about “<strong>looks</strong>”; they only care about <strong>results</strong>. Therefore, if the results show little or no measurable difference then regardless of how it may look, it simply does not matter.</p><p>Therefore, rather than speculate on what the results might look like, I decided to test it.</p><p>The application was the same (FastAPI) and the endpoints were the same. Only the Python build was different. One instance ran with the standard build with the <strong>GIL</strong>, while the second instance ran with a <strong>free-threaded</strong> build. Everything else remained exactly the same.</p><p>My objective was simply to determine where free-threaded <strong>Python</strong> truly improves performance and where it has little to no effect.</p><h4>What is the Global Interpreter Lock (GIL)?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*303EW_6NOjV0IgKfx2qsYA.jpeg" /></figure><p>Before understanding the recent change in the GIL, it is important to first understand how it works.</p><p>The Global Interpreter Lock (<strong>GIL</strong>) is a locking mechanism used for synchronizing execution in <strong>CPython</strong>. The Purpose of the <strong>GIL</strong> is to ensure that no more than one thread executes <strong>Python</strong> bytecode at the same time.</p><p>Therefore, regardless of whether an application <strong>spawns</strong> many <strong>threads</strong>, these threads will never execute <strong>Python</strong> bytecode in <strong>parallel</strong> as long as the <strong>GIL</strong> is in effect. Threading in <strong>Python</strong> works well for <strong>I/O bound</strong> workloads, but not for <strong>CPU-heavy</strong> tasks.</p><h4>What changed ?</h4><p>Now that we understand how the GIL works, let’s look at what actually changed.</p><p>It’s helpful to consider the<strong> Global Interpreter Lock (GIL)</strong> when determining how this upgrade will affect your specific app.</p><p><strong>Python</strong>, by default, does not allow more than one thread of execution to execute <strong>Python</strong> <strong>bytecodes</strong> at any given time. Therefore, while you may be able to run many threads, they cannot all process their respective Python code simultaneously; i.e., there is no true <strong>multi-processing</strong> with threads in <strong>regular Python</strong>.</p><p>Therefore, threads in <strong>Python</strong> have always been most beneficial for applications that are I/O bound. They’ve never really worked well for applications that are <strong>CPU</strong> heavy.</p><p>So long as the <strong>GIL</strong> exists in standard <strong>Python</strong>, we’ll see the same limitations with threading as we do today.</p><p>Free-threaded <strong>Python</strong> removes the <strong>GIL</strong> allowing multiple threads to execute Python code concurrently.</p><p>In theory, this should increase <strong>CPU</strong> utilization and give developers the ability to achieve greater efficiency through <strong>multithreading</strong>.</p><p>That said, this doesn’t necessarily mean every single application will be faster. If an application is <strong>I/O bound</strong>, then <strong>FastAPI</strong> already provides <strong>high performance</strong> due to its asynchronous design. So, removing the <strong>GIL</strong> won’t provide much benefit for these types of applications.</p><p>On the flip side, CPU bound applications, particularly ones that utilize threads, would likely experience significant improvements with <strong>Free-threaded Python</strong>. That was my primary goal when testing the release.</p><h4>Testing Environment</h4><pre># Test Environment Details<br>- Machine: Apple Mac Mini (M-series)<br>- CPU: (M4/16GB)<br>- OS: macOS (Sequoia)<br>- Python versions:<br>  - CPython 3.14.4 (standard build)<br>  - CPython 3.14.4 (free-threaded build)<br>- Server:<br>  - Uvicorn<br>  - Single worker (intentionally)<br>- Load testing tool:<br>  - wrk<br>- Endpoints<br>  - /io-bound<br>  - /cpu-single<br>  - /cpu-threaded<br>- Query Params<br>  - limit # Controls the size of the CPU workload.<br>  - delay # Simulates I/O latency.<br>  - workers # Defines the number of threads used in the threaded CPU endpoint.</pre><p>To verify the behavior, I tested both environments directly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUYYbBBzZFFERZ_XG-ZOow.png" /><figcaption>Running Python with and without GIL support using two different builds. The free-threaded build allows disabling the GIL, while the standard build does not.</figcaption></figure><p>I tried to keep the testing conditions as uniform as possible so that we can compare them fairly.</p><p>All test scenarios were executed using the exact same <strong>FastAPI</strong> application, the same APIs and the same system. The only thing I changed was how <strong>Python is built</strong>.</p><p>In one case I used a standard <strong>CPython</strong> build that includes the <strong>Global Interpreter Lock (GIL)</strong> for threading, in another scenario I use a free-threaded version of <strong>CPython without GIL</strong>.</p><p>Server configuration in this instance will be the same too. In terms of servers, the same <strong>ASGI</strong> server (Uvicorn) will be used along with the same configuration settings.</p><p>It’s important that there are an equal amount of workers for all of our testing. I have deliberately set up all testing with a <strong>single worker</strong>. Therefore if I see any performance differences it will be due to how <strong>Python threads run</strong>, not by how many processes scale.</p><h4>Test Cases</h4><p>I’m going to test the effects of taking away the <strong>Global Interpreter Lock (GIL)</strong>, with three common types of real world <strong>application</strong> workloads.</p><p><strong>First: I/O Bound Endpoint</strong></p><p>This endpoint models an <strong>I/O bound</strong> process (e.g., when you call an outside service, or wait for a database query).</p><p>As <strong>FastAPI</strong> has been heavily optimized for these types of workloads, because it’s fully asynchronous, the removal of the GIL should have no performance enhancements here.</p><p><strong>Second: CPU Bound Endpoint (single-threaded)</strong></p><p>This endpoint does <strong>CPU bound</strong> calculations. The calculation itself is written solely in <strong>Python</strong>.</p><p>Asynchronous execution does not help at all with <strong>CPU bound</strong> workloads. In addition, the <strong>GIL</strong> may limit how much CPU bounded workloads can be performed, since they run in one thread. Thusly, the removal of the <strong>GIL</strong> <strong>would not</strong> improve performance in this type of workload either.</p><p><strong>Third: CPU Bound Endpoint (multi-threaded)</strong></p><p>With this endpoint we are using the exact same <strong>CPU</strong> intensive work load as the previous example however we have now split the computation of that load into multiple “<strong>threads</strong>” through the use of a <strong>thread pool</strong>.</p><p>Now you may be asking yourself why <strong>fre-threaded Python</strong> is relevant here?</p><p>The answer lies in how both <strong>single</strong> and <strong>multi-threaded</strong> Python programs are executed by the CPU.</p><p>When the <strong>Global Interpreter Lock (GIL) is enabled</strong> in an application, no two threads in that application can run at exactly the same time. As such, regardless of how many threads your program has running, they will always run one after another, thus limiting your potential for performance gain.</p><p>However when the <strong>GIL is disabled</strong>, each thread can be executing at the very same time, resulting in greater <strong>CPU</strong> usage and potentially better throughput.</p><pre># Benchmark Setup<br><br># t = Thread, c = concurrency, d = duration<br><br>All benchmarks were executed using `wrk` with the following commands:<br><br>### I/O-bound<br><br>wrk -t4 -c50 -d20s &quot;http://127.0.0.1:8000/io-bound?delay=0.05&quot;<br><br>### CPU-bound (single-threaded)<br><br>wrk -t4 -c20 -d20s &quot;http://127.0.0.1:8000/cpu-single?limit=300000&quot;<br><br>### CPU-bound (multi-threaded)<br><br>wrk -t4 -c20 -d20s &quot;http://127.0.0.1:8000/cpu-threaded?limit=300000&amp;workers=4&quot;</pre><h4>Benchmark Results</h4><p>To compare the impact of the GIL, I ran the same benchmarks under both environments and measured throughput (Req/Sec).</p><pre>| Test Case     | GIL (req/sec) | No-GIL (req/sec) | Observation            |<br><br>|---------------|--------------|------------------|-------------------------|<br><br>| I/O-bound     | ~919         | ~918             | No difference           |<br><br>| CPU single    | ~8.56        | ~7.77            | No meaningful difference|<br><br>| CPU threaded  | ~8.56        | ~21.01           | Significant improvement |</pre><blockquote>The slightly lower no GIL result is within normal benchmark variance and not a meaningful performance regression for the CPU single test.</blockquote><p><strong>I/O bound: </strong>As expected, there is no meaningful difference. <strong>FastAPI</strong> already handles I/O bound workloads efficiently using async execution. <strong>Removing the GIL does not improve this.</strong></p><p><strong>CPU bound (single-threaded): </strong>Again, no real difference. Even <strong>without the GIL</strong>, the computation still runs on a single thread,<strong> so performance remains the same</strong>.</p><p><strong>CPU bound (multi-threaded): </strong>This is where things change. <strong>With the GIL enabled</strong>, multiple threads provide no benefit. <strong>With the GIL disabled</strong>, threads can run <strong>concurrently</strong>, resulting in higher throughput.</p><p>However, the improvement is not linear due to thread overhead and scheduling costs.</p><blockquote>Removing the GIL does not make FastAPI faster, it enables parallelism where it was previously impossible.</blockquote><h4>Implications of These Results</h4><p>The data clearly show that there are<strong> two different</strong> situations.</p><p>When running <strong>IO bound</strong> workloads, removing the GIL does not provide any meaningful benefit from Python because <strong>FastAPI (async)</strong> has already made a good job in handling such cases as fast as possible by executing them asynchronously.</p><p>When dealing with<strong> CPU bound</strong> workloads, we have a completely opposite behavior. With the <strong>GIL</strong> when you run your code <strong>threaded</strong>, it will never be faster than if you had run your code <strong>sequentially</strong> (because all threads wait each other when they need to access the same resource), so it will give you no advantage. If however you allow multiple threads to access <strong>Python</strong> resources simultaneously (removing GIL), then you can use concurrent execution of threads which enables <strong>multi-threaded</strong> programming.</p><h4>Limitations</h4><p>These are all run <strong>locally</strong> therefore your results could differ when running in <strong>production</strong>.</p><p><strong>Python</strong> was used to implement the CPU intensive tests. Many real world apps use <strong>C-extensions</strong> (cffi, ctypes etc) or other programs that could act different from P<strong>ython</strong>.</p><p>This test was made with simplicity in mind to allow us to see the effects of the <strong>GIL</strong>, this test should be seen as directionally indicative but should never be considered definitively conclusive.</p><h4><strong>Conclusion</strong></h4><p>Removing the <strong>GIL</strong> can provide significant benefits for many applications, but like anything else with regard to improving application performance, it depends on what your application or service does.</p><p>Applications that are<strong> I/O bound</strong> typically do not benefit from being free-threaded. That’s because <strong>FastAPI</strong> uses an async model to handle those types of workloads.</p><p>When you remove the <strong>GIL</strong> from your code, and then use CPU bound workloads, you now can run threads in parallel and thus get better throughput.</p><p>But again, it is not going to speed up every application. It will be no substitute for multi-processors or other forms of scaling.</p><p>What it will give you is another <strong>potential solution</strong> (tool) to help you solve some problems. The trick to making it useful is to understand where it may be beneficial, and where it won’t.</p><h4>Source code</h4><p>The full implementation, benchmark setup, and test scenarios used in this article are available here:</p><p><a href="https://github.com/inanpy/fastapi-gil-vs-nogil">https://github.com/inanpy/fastapi-gil-vs-nogil</a></p><p>You can run the benchmarks locally and compare the results on your own system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=360291494420" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Getting Started with FastAPI: A Step-by-Step Beginner’s Guide]]></title>
            <link>https://medium.com/@inandelibas/getting-started-with-fastapi-a-step-by-step-beginners-guide-c2c5b35014e9?source=rss-4b3036116dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2c5b35014e9</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi-tutorials]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[İnan DELİBAŞ]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 18:04:00 GMT</pubDate>
            <atom:updated>2025-07-13T18:22:28.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zaejYgdtWUosCrd1FRyuw.jpeg" /></figure><h3>❓<strong>What is FastAPI?</strong></h3><p><strong>FastAPI</strong> is a modern, high-performance Python web framework for building APIs, designed around Python type hints. It is built on ASGI (async) and utilizes Pydantic for data validation, making it both fast (on par with NodeJS and Go) and reliable. Key features include automatic request/response validation based on type hints, built-in interactive documentation (Swagger UI and ReDoc), and excellent editor support (autocompletion, type checking). FastAPI aims to help you write <strong>less code with fewer bugs</strong> while delivering high performance and developer productivity.</p><ul><li><strong>High performance:</strong> Very fast, thanks to Starlette and Pydantic, which handle many requests concurrently.</li><li><strong>Based on type hints:</strong> Data validation and parsing come for free using Python types.</li><li><strong>Automatic docs:</strong> Built-in Swagger UI (/docs) and ReDoc (/redoc) for interactive API exploration.</li></ul><p>📌 GitHub Project: <br>This guide comes with a complete example repository. <br>👉 <a href="https://github.com/inanpy/fastapi-getting-started-guide">View on GitHub</a></p><h3>🛠️ <strong>Installing FastAPI and Uvicorn:</strong></h3><pre># Create and activate a virtual environment<br>python3 -m venv .venv<br>source .venv/bin/activate<br><br># Install FastAPI and Uvicorn with recommended extras<br>pip install &quot;fastapi[standard]&quot; &quot;uvicorn[standard]&quot;<br><br># Alternatively, without optional extras:<br># pip install fastapi uvicorn</pre><p>This installs <strong>FastAPI</strong> along with useful defaults (like pydantic, uvicorn, python-multipart, etc.). Uvicorn is a lightweight, high-performance ASGI server for running <strong>FastAPI</strong> apps. During development, you can use <strong>uvicorn <em>main:app — reload</em></strong> to auto-reload on code changes.</p><blockquote><strong>Note</strong> that reload is intended for development purposes only and should not be used in production environments.</blockquote><h3>🧪 <strong>Creating your first FastAPI app:</strong></h3><p>Create a new file, main.py, and start with:</p><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.get(&quot;/&quot;)<br>async def read_root():<br>    return {&quot;message&quot;: &quot;Hello!!!&quot;}</pre><p>This defines a <strong>FastAPI</strong> application object (<strong>app = FastAPI()</strong>) and a single GET endpoint at / that returns a JSON message. Each route is represented by a decorator (<strong>@app.get(“/”)</strong>) above an async function.</p><p>To run the app, use Uvicorn:</p><pre>uvicorn main:app --reload</pre><p>The server starts on <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a> by default. Visit <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a> in your browser (<strong>or use curl</strong>), and you should see the JSON response:</p><pre>{&quot;message&quot;: &quot;Hello!!!&quot;}</pre><p>This demonstrates how little code is needed to get a running API. <strong>FastAPI</strong>’s interactive docs (<strong>next section</strong>) will also automatically pick up this route. Writing code in an editor now provides auto-completion for all FastAPI features and your models, thanks to type hints.</p><h3>🧭 <strong>Path and Query Parameters:</strong></h3><p>FastAPI makes it easy to declare dynamic parameters in your routes. Curly<em> brace</em>s indicate a path parameter in the path.</p><p>For example:</p><pre>@app.get(&quot;/items/{item_id}&quot;)<br>async def read_item(item_id: int):<br>    # &#39;item_id&#39; is taken from the path and converted to int<br>    return {&quot;item_id&quot;: item_id}</pre><p>“<strong>item_id</strong>” is a path parameter: visiting /<strong>items/123</strong> will call <strong>read_item(item_id=123)</strong>. <strong>FastAPI</strong> infers item_id: int from the function signature and automatically converts the path segment to an <strong>integer</strong> (returning a 400 error if conversion fails). You get automatic validation (and helpful error messages) and editor support from this.</p><p>In contrast, <em>query parameters</em> come after<strong> the question mark.</strong> In the URL, they are defined as function arguments with defaults.</p><p>For example:</p><pre>from typing import List<br><br>fake_items_db = [{&quot;item_name&quot;: &quot;Foo&quot;}, {&quot;item_name&quot;: &quot;Bar&quot;}, {&quot;item_name&quot;: &quot;Baz&quot;}]<br><br>@app.get(&quot;/items/&quot;)<br>async def list_items(skip: int = 0, limit: int = 10):<br>    # &#39;skip&#39; and &#39;limit&#39; become query params: ?skip=...&amp;limit=...<br>    return fake_items_db[skip : skip + limit]<br>    # Return a slice of the fake DB list using skip and limit values</pre><p>Calling <strong>/items/?skip=1&amp;limit=2</strong> would set skip=1, limit=2; omitting them uses the default values (0 and 10) . Query parameters with a None default become optional (if you declare <strong>q: str | None = None</strong>, then q is optional). <strong>FastAPI</strong> automatically documents both path and query parameters in the interactive docs.</p><p>Key points: declare your path params in the decorator string and as function args (with types), and use normal function parameters (with defaults) for query params.</p><h3>📦 <strong>Request Bodies and Pydantic Models:</strong></h3><p>For routes that accept JSON bodies (e.g., POST, PUT), FastAPI utilizes Pydantic models to define and validate the data. First, import BaseModel from Pydantic and create a class:</p><pre>from pydantic import BaseModel<br><br>class Item(BaseModel):<br>    name: str<br>    price: float<br>    description: str | None = None  # Optional field</pre><p>Each attribute is a field in the expected <strong>JSON</strong>. Then, declare a route taking this model:</p><pre>@app.post(&quot;/items/&quot;)<br>async def create_item(item: Item):<br>    # &#39;item&#39; is an instance of Item with validated data<br>    return {&quot;item_name&quot;: item.name, &quot;item_price&quot;: item.price}</pre><p><strong>FastAPI</strong> will read the JSON request, convert it to an Item, and validate each field (e.g., checking types). If any field is missing or of the wrong kind, FastAPI automatically returns a <strong>clear 422 validation error</strong>. By using BaseModel, you also get editor auto-completion for items.name, item.price, etc.. The response here (a dict) is also converted to JSON.</p><p>Under the hood, <strong>FastAPI</strong> generates a JSON Schema for your model and includes it in the docs. This means that clients see exactly what the expected JSON shape is.</p><pre># Example: Send JSON {&quot;name&quot;: &quot;Foo&quot;, &quot;price&quot;: 45.2}<br># and receive the same data back with validation.</pre><h3>📤 <strong>Response Handling and Status Codes:</strong></h3><p><strong>FastAPI’</strong>s default behavior is to return JSON responses. If your function returns a dictionary, list, or <strong>Pydantic</strong> model, <strong>FastAPI</strong> automatically converts it to JSON (<strong>using jsonable_encoder</strong>) and sends it with a <strong>200 OK</strong> status. You can customize the status code of the response by using the <strong>status_code</strong> parameter in the decorator or by raising an <strong>HTTPException</strong>.</p><blockquote><strong><em>jsonable_encoder</em></strong><em> is used internally by </em><strong><em>FastAPI</em></strong><em> to convert complex Python objects (e.g., datetime, Pydantic models) into JSON-serializable formats.</em></blockquote><p>For example:</p><pre>from fastapi import status<br><br>@app.post(&quot;/items/&quot;, status_code=status.HTTP_201_CREATED)<br>async def create_item(item: Item):<br>    # Returns a 201 Created status instead of 200<br>    return {&quot;message&quot;: f&quot;Item &#39;{item.name}&#39; created&quot;}</pre><p>This will return a status code <strong>201 (Created)</strong> in the response. <strong>FastAPI</strong> also provides convenient constants (<strong>e.g., status.HTTP_404_NOT_FOUND</strong>) for readability.</p><p>To return an error, you can raise HTTPException:</p><pre>from fastapi import HTTPException<br><br>@app.get(&quot;/items/{item_id}&quot;)<br>async def read_item(item_id: int):<br>    if item_id not in fake_items_db:<br>        raise HTTPException(status_code=404, detail=&quot;Item not found&quot;)<br>    return fake_items_db[item_id]</pre><p>This sends a JSON error with your status code and details.</p><h3>⚡<strong>Async Endpoints and Concurrency:</strong></h3><p><strong>FastAPI</strong> supports asynchronous endpoints using<strong> the async def keyword</strong>. This allows your API to handle many requests efficiently, especially if they involve I/O operations<strong> (such as database calls or network requests</strong>).</p><p>Example:</p><pre>import asyncio<br><br>@app.get(&quot;/delay&quot;)<br>async def delayed_response():<br>    await asyncio.sleep(5)  # Simulate an async task or I/O<br>    return {&quot;message&quot;: &quot;Response after delay&quot;}</pre><blockquote>def functions are also supported, but you lose async benefits.</blockquote><p>While this function is waiting on sleep, <strong>FastAPI</strong> can switch to handling <strong>other requests</strong>, improving throughput. In practice, using async def with await on I/O-bound operations (<strong>such as databases and HTTP calls</strong>) makes <strong>FastAPI</strong> highly scalable. Benchmarks show that <strong>FastAPI</strong> can handle significantly more <strong>concurrent</strong> requests than a typical synchronous framework (like Flask) under high load. If you do not need to await anything, you may also use <strong>regular def</strong> functions; <strong>FastAPI</strong> will still run the server asynchronously and efficiently.</p><h3>📚 <strong>Automatic Interactive API Documentation:</strong></h3><p>One of <strong>FastAPI</strong>’s killer features is the <strong>auto-generated API docs</strong>. Once your app is running, you can visit <a href="http://127.0.0.1:8000/docs"><strong>http://127.0.0.1:8000/docs</strong></a> for a <strong>Swagger</strong> UI interface (interactive and <strong>allowing you to test endpoints) or http://127.0.0.1:8000/redoc</strong> for a ReDoc interface.</p><figure><img alt="FastAPI Swagger UI Docs" src="https://cdn-images-1.medium.com/max/1024/1*D1-sr2sh4tlp94lJvWBttA.png" /></figure><p><em>Swagger UI interface for a sample FastAPI app.</em> FastAPI generates the Swagger UI automatically at <strong>/docs</strong>. This interface lists all your <strong>routes</strong>, <strong>parameters</strong>, and <strong>schemas</strong> and lets you “Try it out” with sample requests. It’s updated in real time as you change your code (<strong>after a reload</strong>).</p><p><em>ReDoc interface for the same API.</em> Similarly, visiting <strong>/redoc</strong> shows an alternative documentation style provided by ReDoc. Both docs are based on the <strong>OpenAPI</strong> standard and require <strong>no extra work</strong> from you — they are <strong>automatically provided by FastAPI</strong> for every API, making exploration and testing very easy.</p><h3>🗂️ <strong>Project Folder Structure:</strong></h3><p>As your FastAPI app grows, organizing your code into separate files and folders becomes essential for maintainability.</p><p>Here’s a simple structure to start with:</p><pre>project_root/<br>└── app/<br>    ├── __init__.py<br>    ├── main.py          # creates FastAPI app<br>    ├── database.py      # (DB connection/session)<br>    ├── models.py        # ORM models<br>    ├── schemas.py       # Pydantic models (requestresponse schemas)<br>    ├── crud.py          # optional: database utility functions<br>    └── routers/         # API route modules (each with an APIRouter)<br>        ├── __init__.py<br>        ├── users.py<br>        └── items.py</pre><blockquote><em>How do you plug different routers into your main.py? Like this 👇</em></blockquote><pre># app/main.py<br>from fastapi import FastAPI<br>from app.routers import users<br><br>app = FastAPI()<br># 👇 Include the user-related routes into the main app<br>app.include_router(users.router, prefix=&quot;/users&quot;, tags=[&quot;users&quot;])</pre><pre># app/routers/users.py<br>from fastapi import APIRouter<br><br>router = APIRouter()<br><br>@router.get(&quot;/&quot;)<br>async def get_users():<br>    return [{&quot;username&quot;: &quot;alice&quot;}]</pre><p>By splitting code into these modules, the project stays clear and maintainable. Beginners can start with a single-file main.py but are encouraged to evolve into this structure as they add models, routes, and other components.</p><p>The official <strong>FastAPI</strong> tutorials and best-practice guides all use variations of this layout.</p><blockquote>🧑‍💻 Want to see the full working example?<br>👉 <a href="https://github.com/inanpy/fastapi-getting-started-guide">Click Here</a></blockquote><h3>⚔️ <strong>Django vs. FastAPI (Why FastAPI?):</strong></h3><p><strong>FastAPI</strong> offers several advantages over <strong>Django</strong> for API development. FastAPI is built on ASGI and is asynchronous by design, whereas Django has traditionally been synchronous. This means FastAPI can handle high concurrency, for example, benchmarks report that FastAPI handles over <strong>21,000 requests per second</strong> (about six times more than Django) under heavy load. FastAPI also relies on Python-type hints and utilizes <strong>Pydantic</strong> for automatic data validation and serialization, thereby catching bugs early and enhancing code quality. Additionally, FastAPI automatically generates interactive OpenAPI documentation (Swagger UI/ReDoc) out of the box, whereas Django requires extra setup for similar API docs. In summary, FastAPI is a faster and more modern framework (async, type-driven, auto-docs) for APIs. At the same time, Django is a mature, full-stack framework (with ORM, templating, admin, etc.) geared toward larger applications.</p><h3>🔭 What’s Next?:</h3><p>You’ve built your first <strong>FastAPI</strong> app and learned the core concepts. Here are a few directions you can explore next:</p><ul><li><strong>Database Integration</strong>: Learn how to connect <strong>FastAPI</strong> with databases using libraries like SQLAlchemy or Tortoise ORM. You can also try SQLModel (from the creator of FastAPI).</li><li><strong>Authentication &amp; Authorization</strong>: Dive into OAuth2, JWT tokens, and FastAPI’s built-in security utilities.</li><li><strong>Background Tasks</strong>: Use <strong>FastAPI</strong>’s `BackgroundTasks` for async jobs like sending emails or logging.</li><li><strong>Testing</strong>: Explore how to write automated tests using “<strong>TestClient”</strong> and “<strong>pytest”</strong>.</li><li><strong>Deployment</strong>: Deploy your app using Docker, Gunicorn, or on cloud platforms like Heroku, Render, or DigitalOcean.</li></ul><h3>🧠 <strong>Tips and Common Pitfalls:</strong></h3><ul><li><strong>Use Virtual Environments:</strong> Always activate a virtualenv (venv or similar) before installing FastAPI/Uvicorn to <strong>isolate</strong> dependencies</li><li><strong>Define Pydantic Models:</strong> Don’t bypass Pydantic by using raw dict parameters — define BaseModel classes for request bodies to get automatic validation.</li><li><strong>Parameter Order Matters:</strong> If you have overlapping routes, such as <strong>users/me and /users/{user_id}</strong>, define the static path (/users/me) <em>before</em> the dynamic one to avoid conflicts.</li><li><strong>Return Errors Properly:</strong> Use raise HTTPException(…) for error cases (e.g., 404 Not Found) instead of returning None. This ensures that clients receive meaningful status codes and messages.</li><li><strong>Use <em>— reload</em>. Only in Development:</strong> The —reload option restarts Uvicorn on code changes, which is excellent for development, but it uses more resources and is unstable, so omit it in production.</li><li><strong>Test Your API:</strong> Use FastAPI’s built-in TestClient (based on Starlette’s TestClient) to write tests for your endpoints. Testing early helps catch mistakes before they go live.</li><li><strong>Read the Docs:</strong> The official FastAPI documentation is extensive. Refer to it for advanced topics (such as security and databases) once you have the basics working.</li></ul><h3>💬 <strong>Final Thoughts:</strong></h3><p><strong>FastAPI</strong> is genuinely a joy to work with — it’s fast, clean, and developer-friendly. If you’ve made it this far, you’re officially ready to build something incredible. And if you’re curious to go deeper, check out the <a href="https://fastapi.tiangolo.com/">official documentation</a>; it’s top-notch.</p><p>If this guide helped you out, go ahead and <strong>smash that 👏 clap button — not just once, but like… a hundred times, or a thousand.</strong> Seriously, Medium lets you.</p><p>And feel free to share the post if someone else finds it helpful as well.</p><p><strong>Thanks for reading, and happy building! 🚀</strong></p><h3>📘Additional Resources:</h3><p>For more information and learning materials, check out:</p><ul><li><strong>FastAPI Official Documentation:</strong> <a href="https://fastapi.tiangolo.com/tutorial/">https://fastapi.tiangolo.com/tutorial/</a></li><li><strong>Pydantic Documentation:</strong> <a href="https://docs.pydantic.dev/">https://docs.pydantic.dev</a></li><li><strong>Uvicorn Documentation:</strong> <a href="https://www.uvicorn.org/">https://www.uvicorn.org</a></li><li><strong>FastAPI GitHub:</strong> <a href="https://github.com/fastapi/fastapi">https://github.com/fastapi/fastapi</a></li></ul><p>These resources will help you deepen your understanding and explore more advanced <strong>FastAPI</strong> features (security, databases, background tasks, etc.) as you progress.</p><blockquote>References: Based on FastAPI and Uvicorn official documentation.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2c5b35014e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Notifications in Python: Using SSE with FastAPI]]></title>
            <link>https://medium.com/@inandelibas/real-time-notifications-in-python-using-sse-with-fastapi-1c8c54746eb7?source=rss-4b3036116dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c8c54746eb7</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[sse]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[İnan DELİBAŞ]]></dc:creator>
            <pubDate>Thu, 19 Jun 2025 19:27:04 GMT</pubDate>
            <atom:updated>2025-06-19T19:27:04.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmUX86awAwNKOsSFxj6hcA.png" /></figure><p>Modern web applications increasingly rely on real-time updates, such as live chat, dashboards, and notifications. Users expect instantaneous feedback (such as new messages, alerts, and data streams) without having to refresh manually. Traditional request/response isn’t sufficient for this, so “push” technologies are crucial. Server-Sent Events (SSE) offer one such solution, enabling the server to push updates to the client over HTTP, thereby eliminating the need for the client to poll.</p><blockquote><em>✨ </em><a href="https://github.com/inanpy/fastapi-sse-example"><em>See full project on GitHub</em></a></blockquote><h3>What Are Server-Sent Events (SSE)?</h3><p>Server-Sent Events (SSE) is a <strong>browser-native</strong> API (part of HTML5) for unidirectional server→client streaming. In SSE, the client opens a persistent HTTP connection (with Accept: <strong>text/event-stream</strong>), and the server continues to send text messages over that channel. Unlike WebSockets, the channel is <strong><em>one-way</em></strong>: the server pushes data, and the client listens. The EventSource API in JavaScript handles the connection and parses incoming events. Each message is sent as plain text, e.g., data: …\n\n, and the browser dispatches it as an event. SSE also supports optional fields (e.g., event:, id:) to label events or resume streams.</p><p>For example:</p><pre>event: ping<br>id: 123<br>data: {&quot;time&quot;: &quot;2025-06-12T11:30:00Z&quot;}</pre><h3>SSE vs WebSockets vs Polling: What Should You Use?</h3><ul><li><strong>Long-Polling:</strong> The client repeatedly sends requests asking for new data. It’s inefficient but straightforward: most requests return no new data. It adds latency (each poll waits) and loads the server with constant new connections.</li><li><strong>SSE:</strong> Ideal for <em>one-way</em> streaming from the server to many clients. It’s easy to implement (just set Content-Type: text/event-stream and stream chunks), works over HTTP/1.1 or HTTP/2, and auto-reconnects if dropped. SSE saves bandwidth by using a single long-lived connection rather than making frequent polls. However, it can’t send messages from the client to the server.</li><li><strong>WebSockets</strong> provide full-duplex, bidirectional communication over a single TCP connection. It’s best for chat apps, multiplayer games, or any scenario where both the client and server need to send messages. However, WebSockets require more setup and specialized server support, and may not traverse proxies as easily. They also maintain more overhead per connection (though still efficient). In practice, choose SSE for simple <strong>server→client updates</strong> (notifications, live feeds) and WebSockets when you need client→server streaming or lower latency two-way communication.</li></ul><blockquote><em>SSE is ideal for low-frequency, one-way updates like notifications or status changes. It’s lightweight and easy to implement. For high-frequency or bidirectional communication, WebSockets provide better scalability and lower latency under load.</em></blockquote><h3>How Server-Sent Events Work Under the Hood</h3><p>Underneath, SSE is just <strong>chunked HTTP streaming</strong>. The client makes a standard HTTP GET with Accept: text/event-stream, and the server responds with headers like:</p><pre>HTTP/1.1 200 OK  <br>Content-Type: text/event-stream  <br>Cache-Control: no-cache  <br>Connection: keep-alive  </pre><p>Then <strong>keeps the connection open</strong> indefinitely. Each event is sent as UTF-8 text. Single newlines separate fields in an event (such as data or event), and a <strong>blank line (\n\n) ends each event</strong>. For example:</p><pre>data: {&quot;price&quot;: 123.45}<br>data: USD<br>id: 42</pre><p>Here \n\n after the id: 42 signals the event is complete. The TCP connection remains open (no final 0-length chunk is sent), and the server can later write more chunks as new events occur. Because HTTP/1.1 supports <em>persistent connections</em> and <em>chunked transfer encoding</em>, the server doesn’t need to know the content length in advance. SSE runs entirely over standard HTTP ports (80/443), allowing it to pass through firewalls without special configuration.</p><p>The browser uses the EventSource interface to parse these chunks into message events. It also handles <strong>automatic reconnection</strong>: if the connection drops, the browser retries by default, even sending the Last-Event-ID header if the last message had an ID. This lets the server resume the stream without duplicating messages. In short, SSE cleverly transforms HTTP’s request-response model into a continuous one-way data stream.</p><h3>SSE in Python: The Benefits and the Challenges</h3><p>In Python, <strong>SSE’s</strong> HTTP-based nature is both a benefit and a challenge. On the plus side, you can use any web framework to stream <strong>text responses</strong> and set the Content-Type header to <strong>text/event-stream</strong>. No special protocol (such as WebSocket) is required, and existing HTTP servers (including ASGI frameworks like <strong>FastAPI</strong> or even <strong>WSGI</strong> with some adjustments) can handle it. SSE is lightweight, stateless, and typically easier to test than WebSockets. Libraries like <strong>sse-starlette</strong> provide helpers, and Python’s async features (asyncio, FastAPI/Starlette) make streaming straightforward.</p><p>On the <strong>downside</strong>, SSE is unidirectional (server→client only), so it can’t replace cases where the client must push data (like chat input). Python’s typical WSGI servers (e.g., Gunicorn in sync mode) may not stream well, so you often need ASGI servers (Uvicorn, Daphne) or disable buffering. Additionally, maintaining multiple HTTP connections open consumes resources (although SSE is more efficient than polling, each open connection still utilizes a socket and memory). Concurrency must be managed; for example, in a multi-process server, one process may not see updates from another unless shared storage (such as Redis or a database) is used. The client-side reconnection and “Last-Event-ID” logic must also be handled: if events have an “id” field, the browser will automatically include it on reconnect. Overall, SSE in Python works best when you structure your app asynchronously or dedicate a worker to the SSE stream.</p><h3>When to Use SSE Instead of WebSockets</h3><p>Use SSE when your application primarily needs <strong>server→client push</strong> of events, and the client doesn’t need to send frequent data back. Typical scenarios include live notifications, news feeds, real-time dashboards, or any situation where the server initiates updates. SSE is simpler to implement in these cases (no handshake, uses HTTP) and integrates easily with HTTP caching and authentication. For instance, a notifications service where the server tells the client, “You have a new alert,” is a perfect SSE use-case.</p><blockquote>In contrast, if you need full <strong>bi-directional</strong> streaming (where the client sends data back, such as in chat or gaming) or extremely <strong>low latency</strong>, WebSockets may be a <strong>better</strong> option. In summary, <strong>SSE excels for “one-way” real-time streams</strong>, while WebSockets are better suited for<strong> two-way </strong>or <strong>high-throughput</strong> needs.</blockquote><h3>Use Case: Live Notifications</h3><h4>Building a Real-Time Notification System in FastAPI</h4><p>A typical SSE use case is a push <strong>notification system</strong>. For example, when a significant event occurs on the backend (such as a new message, system alert, or status change), you want all connected clients to be notified immediately. One approach is to have clients connect to an SSE endpoint (e.g., /notifications/) and have backend processes publish events to that endpoint’s stream.</p><p>In FastAPI, you might write an endpoint like<strong> /subscribe/{user_id} </strong>that keeps a stream open for that user. Meanwhile, whenever something happens (e.g., a background task completes or a database record updates), you publish an event to a shared broker (such as Redis). The SSE endpoint’s async generator listens on that broker and yields incoming messages. A simplified sketch:</p><pre>from fastapi import FastAPI<br>from fastapi.responses import StreamingResponse<br>import aioredis, asyncio, json<br><br>app = FastAPI()<br>redis = await aioredis.from_url(https://medium.com/&quot;redis://localhost&quot;)<br><br>async def notification_stream(user_id: str):<br>    pubsub = redis.pubsub()<br>    await pubsub.subscribe(&quot;notifications&quot;)<br>    while True:<br>        msg = await pubsub.get_message(ignore_subscribe_messages=True)<br>        if msg and msg[&quot;type&quot;] == &quot;message&quot;:<br>            event = json.loads(msg[&quot;data&quot;])<br>            # filter by user_id if needed...<br>            yield f&quot;data: {json.dumps(event)}\n\n&quot;<br>        await asyncio.sleep(0.01)<br><br>@app.get(&quot;/notifications/{user_id}&quot;)<br>async def notifications(user_id: str):<br>    return StreamingResponse(notification_stream(user_id), media_type=&quot;text/event-stream&quot;)</pre><p>On the backend, any part of the app (or a Celery task) can publish to Redis:</p><pre>await redis.publish(&quot;notifications&quot;, json.dumps({&quot;user&quot;: user_id, &quot;text&quot;: &quot;New alert!&quot;}))</pre><p>Then all clients subscribed via SSE will immediately receive that JSON. This pub/sub pattern is familiar; one guide notes using Redis pub/sub for precisely this purpose. You can also push events via other brokers (RabbitMQ, Kafka) or use a task queue (Celery) that, upon completion, calls redis.publish().</p><blockquote><em>💻 You can find a complete working example of this structure on GitHub:</em></blockquote><blockquote><em>👉 </em><a href="https://github.com/inanpy/fastapi-sse-example"><em>https://github.com/inanpy/fastapi-sse-example</em></a></blockquote><h3>SSE Performance Tips for High-Traffic Apps</h3><ul><li><strong>Compression:</strong> SSE streams are text-based, so you can (and should) enable gzip/deflate compression on your HTTP response. This can cut bandwidth by 70–90% for typical JSON payloads. Most web servers (e.g., nginx, uvicorn) support HTTP compression; ensure that the Content-Type: text/event-stream is compressible according to your configuration.</li><li><strong>Minimal Data:</strong> Keep SSE messages small. Only send the data the client needs. Since each event uses one HTTP packet over TCP, minimizing payload improves throughput.</li><li><strong>Batching Events:</strong> If events occur rapidly, consider batching multiple data items into a single SSE event (as a JSON array) rather than sending many back-to-back events. This reduces overhead (each event has some framing bytes).</li><li><strong>Disable Buffering:</strong> Many reverse proxies (nginx, UWSGI) buffer responses by default, which defeats streaming. Disable buffering for SSE endpoints. For example, send the header X-Accel-Buffering: no (nginx) or configure proxy_buffering off. This ensures each yield is flushed to the client immediately.</li><li><strong>Close Idle Streams:</strong> Always close SSE connections on the client side when they are no longer in use (to free server resources). On the server side, if you detect the client disconnect (e.g., GeneratorExit in Python), stop sending—unused open connections waste memory and file descriptors. Many examples explicitly check for broken clients and break the loop, or rely on async frameworks to cancel the generator.</li><li><strong>Connection Limits (HTTP/1.1 vs HTTP/2):</strong> In HTTP/1.1, browsers typically allow only ~6 concurrent connections per origin. If your app must serve many SSE clients, use HTTP/2. With HTTP/2, a single TCP connection can multiplex dozens or hundreds of streams. Deploying your app on a server (or proxy) that supports HTTP/2 will greatly increase scalability.</li></ul><h3>Handling Multiple Clients and Scaling with ASGI Servers</h3><p>To serve <strong>multiple</strong> concurrent SSE clients, use an ASGI server such as Uvicorn. This can handle asynchronous I/O efficiently. You can run multiple worker processes (or threads), but remember that each SSE stream lives in one process. If your application uses multiple processes (e.g., via Gunicorn workers), ensure that the event source (Redis or whatever) is shared; otherwise, one process won’t see events published in another. A good approach is to maintain a single central Pub/Sub (e.g., Redis, Kafka) that all processes subscribe to. Then, each instance streams to its clients independently.</p><p>If you need to broadcast to <strong>all clients</strong>, consider a pub/sub or message queue: publish an event once, have every server instance send it to its connected clients. Libraries like <strong>sse-starlette</strong> help manage multiple channels. Also, ensure you test your deployment. For high-scale applications, you may need <strong>load balancers</strong> or<strong> sticky sessions</strong> if clients are pinned to particular servers, or use <strong>global pub/sub</strong> so that any instance can serve any client.</p><h3>What to Watch Out for in Production (Timeouts, Keep-Alive, CORS)</h3><ul><li><strong>Proxy Timeouts:</strong> Be aware of reverse proxy settings. Many proxies (nginx, AWS ELB, etc.) will terminate idle streams after a timeout (often 60 seconds). To prevent this, either send periodic comment heartbeats (e.g., “: heartbeat\n\n”) or adjust the proxy’s keepalive/timeout settings. For nginx, you can set proxy_read_timeout to a high value or use X-Accel-Buffering: no as above.</li><li><strong>CORS and Authentication:</strong> If your SSE endpoint is on a different origin or requires auth, configure CORS and credentials properly. In JS, you can create a new EventSource(url, { withCredentials: true }) to send cookies. On the server, set allow_origins and allow_credentials if using middleware (e.g., FastAPI’s CORSMiddleware). Ensure TLS (HTTPS) is used if credentials are involved.</li><li><strong>Connection Limits:</strong> As noted, browsers limit the number of concurrent connections per domain. Avoid using too many SSE connections on a single page; instead, consider splitting them across subdomains or using HTTP/2. Test in all target browsers.</li><li><strong>DNS/IP Blocking:</strong> Some CDNs or firewalls may treat long-lived HTTP connections unusually. Ensure your hosting environment supports streaming responses (some servers that buffer or require Content-Length may not work).</li><li><strong>Resource Usage:</strong> Each SSE client uses one server thread or coroutine. For a large-scale system, monitor the open connection count and memory usage. It may be necessary to run on servers optimized for I/O (async) and to increase limits on file descriptors.</li></ul><h3>In Conclusion;</h3><p><strong>SSE</strong> remains a <strong>simple and effective</strong> tool for <strong>real-time notifications</strong>. It’s built on standard <strong>HTTP</strong>, widely supported, and ideal for unidirectional data streams. For many use cases, such as live alerts, feeds, and dashboards, SSE provides a lightweight alternative to more complex WebSocket setups. The trade-offs are now well understood: SSE excels at server→client updates with automatic reconnection, but isn’t bidirectional. When you need a <strong>straightforward push mechanism</strong> (and especially when you can leverage Python’s async frameworks), SSE is still a very relevant choice.</p><p>We have mature tooling: <strong>FastAPI</strong> and libraries like <strong>sse-starlette</strong> make building SSE streams easy. And for developers, SSE means handling real-time without leaving the comfort of HTTP. In short, SSE’s <strong>one-way streaming model</strong> remains useful, bridging classic web protocols and modern real-time user experiences.</p><h3>Final Thoughts</h3><p>Real-time capabilities are no longer a luxury — they’re a <strong>core expectation</strong> in modern web experiences. Whether you’re building a live dashboard, sending instant alerts, or updating a user’s feed, the ability to push updates seamlessly can transform how users interact with your application.</p><p><strong>Server-Sent Events (SSE)</strong> offers a <strong>robust, elegant, and underrated</strong> approach to real-time communication. It’s easy to implement with <strong>FastAPI</strong>, integrates smoothly into existing HTTP infrastructures, and shines in scenarios where the data flow is<strong> one-way </strong>from server to client.</p><p>If your use case doesn’t demand bidirectional communication, <strong>SSE should be your default starting point</strong>, before jumping into the complexity of <strong>WebSockets</strong>.</p><p>Have you implemented real-time features using <strong>SSE</strong> in your projects?</p><p>I’d love to hear your thoughts, lessons, or questions in the comments.</p><p>If this article helped you, consider sharing it with your developer network or giving it a <strong>few claps</strong> 👏</p><p>Thanks for reading!</p><p>Inan Delibas<br>Python Team Lead &amp; Architect <br><a href="https://www.linkedin.com/in/inandelibas/">Linkedin</a> | <a href="https://github.com/inanpy">Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c8c54746eb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hashing: An Overview of Concepts and Applications in Python]]></title>
            <link>https://medium.com/@inandelibas/hashing-an-overview-of-concepts-and-applications-in-python-be3a6d85a5a4?source=rss-4b3036116dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/be3a6d85a5a4</guid>
            <category><![CDATA[hash]]></category>
            <category><![CDATA[passwords]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[hashing]]></category>
            <dc:creator><![CDATA[İnan DELİBAŞ]]></dc:creator>
            <pubDate>Thu, 18 May 2023 13:54:22 GMT</pubDate>
            <atom:updated>2023-05-18T14:07:19.991Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*CzrAmW9ip5l9WswEw_RwLQ.jpeg" /></figure><p>As a Python developer with around 10 years of experience, I would like to delve into the concept of hashing, its underlying principles, and practical applications in this article. We will explore various hashing algorithms and demonstrate their implementation in Python code examples.</p><h3># Understanding Hashing</h3><p>Hashing involves transforming input data of arbitrary size into a fixed-size value called a hash code or hash value. A hash function performs this transformation using a specific algorithm. It is important to note that different inputs should ideally produce different hash values to maintain data integrity and identification.</p><h3># Applications of Hashing</h3><h3>Data Integrity and Verification</h3><p>Hashing plays a critical role in ensuring data integrity and verification. By generating hash codes for files or messages, we can easily verify if the data has been tampered with. Even a small change in the input data will result in a significantly different hash value. Let’s see an example of calculating the MD5 hash of a string in Python:</p><pre>import hashlib<br><br>data = &quot;Hello, World!&quot;<br># don&#39;t recommend using md5.<br>hash_object = hashlib.md5(data.encode())<br>hash_value = hash_object.hexdigest()<br><br>print(hash_value)<br># 65a8e27d8879283831b664bd8b7f0ad4</pre><h3>Password Storage</h3><p>Securely storing passwords is a critical aspect of application security. In Python, we can leverage the hashlib module to hash passwords using various algorithms. By storing the hashed version of passwords instead of the plain text, we can enhance the security of user credentials.</p><p>Let’s see an example of password storage using hashlib and the SHA-256 hashing algorithm:</p><pre>import hashlib<br><br># our pass<br>password = &quot;mysecretpassword&quot;.encode()<br><br># Hashing the password using SHA-256 algorithm<br>hash_object = hashlib.sha256(password)<br>hashed_password = hash_object.hexdigest()<br><br># Store the hashed password in the database or file<br><br># Later, when verifying the password<br>input_password = input(&quot;Enter your password: &quot;).encode()<br><br># Hashing the input password for comparison<br>input_hash_object = hashlib.sha256(input_password)<br>input_hashed_password = input_hash_object.hexdigest()<br><br># Compare the hashed passwords for authentication<br>if hashed_password == input_hashed_password:<br>    print(&quot;Password is correct.&quot;)<br>else:<br>    print(&quot;Password is incorrect.&quot;)</pre><p>In this example, we hash the original password using the SHA-256 algorithm and store the hashed password in the database or file. When a user enters their password for authentication, we hash the input password and compare it with the stored hashed password. If the hashed passwords match, we consider the password as correct.</p><p>Remember to use a salt (a random value added to the password before hashing) to enhance the security of the hashed passwords. Additionally, consider using more advanced hashing algorithms like bcrypt or scrypt for stronger security.</p><p>By implementing password storage with hashlib, we can protect user passwords and ensure the confidentiality of sensitive information.</p><p>Feel free to customize and expand upon this example according to your specific requirements and security considerations.</p><h3>Password Storage Using Hashlib</h3><p>Securely storing passwords is a critical aspect of application security. In Python, we can leverage the hashlib module to hash passwords using various algorithms. By storing the hashed version of passwords instead of the plain text, we can enhance the security of user credentials.</p><p>Let’s see an example of password storage using hashlib and the SHA-256 hashing algorithm with a salt:</p><pre>import hashlib<br>import os<br><br>password = &quot;mysecretpassword&quot;.encode()<br>salt = os.urandom(16)  # Generate a random salt<br><br># Combine the password and salt<br>salted_password = password + salt<br><br># Hash the salted password using SHA-256 algorithm<br>hash_object = hashlib.sha256(salted_password)<br>hashed_password = hash_object.hexdigest()<br><br># Store the hashed password and salt in the database or file<br><br># Later, when verifying the password<br>input_password = input(&quot;Enter your password: &quot;).encode()<br><br># Retrieve the stored salt associated with the user<br>stored_salt = ...  # Retrieve the salt from the database or file<br><br># Combine the input password and stored salt<br>salted_input_password = input_password + stored_salt<br><br># Hash the salted input password for comparison<br>input_hash_object = hashlib.sha256(salted_input_password)<br>input_hashed_password = input_hash_object.hexdigest()<br><br># Compare the hashed passwords for authentication<br>if hashed_password == input_hashed_password:<br>    print(&quot;Password is correct.&quot;)<br>else:<br>    print(&quot;Password is incorrect.&quot;)</pre><p>In this updated example, we introduce the concept of a salt. A salt is a random value that is combined with the password before hashing. The salt value is stored along with the hashed password. When verifying the password, the stored salt is retrieved and combined with the input password before hashing. This ensures that even if two users have the same password, their hashed passwords will be different due to the unique salt.</p><p>Remember to generate a random salt for each user and store it securely. The os.urandom(16) function is used in this example to generate a 16-byte random salt. Additionally, ensure that the salt is properly associated with each user in the storage mechanism.</p><p>By implementing password storage with hashlib and using a salt, we can significantly improve the security of user passwords and protect sensitive information.</p><h3>Conclusion</h3><p>Hashing is a powerful concept with diverse applications in Python and other programming languages. By understanding the underlying principles and leveraging appropriate hashing algorithms, we can enhance data integrity, ensure secure password storage, and optimize data retrieval processes. Remember to choose the appropriate hashing algorithm based on your specific use case and security requirements.</p><p>Thank you for reading! I hope this article provides you with valuable insights into password storage using hashlib in Python. By adopting secure hashing practices, we can enhance the security of user passwords and protect sensitive information. If you have any questions or feedback, please feel free to reach out. Happy coding!</p><p>Inan Delibas — inanpy</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be3a6d85a5a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Socket ?]]></title>
            <link>https://medium.com/@inandelibas/web-socket-c36c4662e118?source=rss-4b3036116dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c36c4662e118</guid>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[İnan DELİBAŞ]]></dc:creator>
            <pubDate>Mon, 26 Dec 2022 17:37:58 GMT</pubDate>
            <atom:updated>2022-12-26T17:43:22.416Z</atom:updated>
            <content:encoded><![CDATA[<h3>Nedir Bu WebSocket ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*DUtXsEgY2O_6-dR4Pmp7Mg.png" /></figure><h3>WebSocket?</h3><p>HTTP üzerinden başlar ve daha sonra HTTP yerine bir bağlantı kurar. Bu, WebSocket’lerin HTTP isteklerine göre daha verimli olmasını sağlar, çünkü bir bağlantının sürekli açık kalması sayesinde istekler ve yanıtlar arasındaki gecikmeler azaltılır.</p><p>Gerçek zamanlı uygulamalar için özellikle yararlıdır. Örneğin, bir sohbet uygulamasında, kullanıcılar arasında mesajların anında iletimini sağlamak için WebSocket kullanılabilir. Ayrıca, bir finansal ticaret uygulamasında, anlık piyasa verilerinin iletilmesi için de WebSocket kullanılabilir.</p><p>JavaScript ile tarayıcıda kullanılabilir ve sunucuda Node.js gibi bir JavaScript çalışma zamanı ortamında kullanılabilir. WebSocket’ler, ayrıca birçok farklı programlama dilinde de desteklenir.</p><p>Ayrıca birçok web tarayıcısı tarafından da desteklenir. Bu, WebSocket’lerin çeşitli cihazlarda ve tarayıcılarda çalıştırılabilmesini sağlar.</p><p>Sonuç olarak, WebSocket, bir ağ protokolüdür ve bir tarayıcı ve sunucu arasında iki yönlü, gerçek zamanlı veri akışı sağlar. Gerçek zamanlı uygulamalar için yararlıdır ve JavaScript ile tarayıcıda ve sunucuda kullanılabilir. Ayrıca, birçok farklı programlama dilinde de desteklenir ve birçok web tarayıcısı tarafından da desteklenir.</p><h3>WS ve WSS arasındaki fark?</h3><p>WebSocket (WS) ve WebSocket Secure (WSS) haberleşmesi arasındaki temel fark, güvenliktir. WSS, bir web uygulaması için iki yönlü veri akışı sağlayan bir internet protokolüdür ve WS ile benzer şekilde çalışır. Ancak, WSS, WS’e göre daha güvenlidir, çünkü veri akışının şifrelenmesini sağlar.</p><p>WSS, tarayıcının bir web sunucusuna bir SSL/TLS (Secure Sockets Layer/Transport Layer Security) bağlantısı üzerinden bir WebSocket bağlantısı açmasını ve bu bağlantıyı koruyarak iki taraf arasında veri gönderimini sağlar. SSL/TLS, veri akışının şifrelenmesini ve güvenliğini sağlamak için kullanılan bir internet güvenlik protokolüdür.</p><p>Bu nedenle, WSS, WS’e göre daha güvenli bir seçenektir ve özellikle güvenliği önemli olan uygulamalar için tavsiye edilir. Ancak, WSS’nin kullanımı biraz daha zor olabilir ve daha fazla kaynak tüketebilir. Bu nedenle, WS ve WSS arasındaki seçim, uygulamanın gereksinimlerine ve ihtiyaçlarına göre yapılmalıdır.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c36c4662e118" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django App Güvenliğini Sağlamak.]]></title>
            <link>https://medium.com/@inandelibas/django-app-g%C3%BCvenli%C4%9Fini-sa%C4%9Flamak-2624fefc1d31?source=rss-4b3036116dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2624fefc1d31</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[İnan DELİBAŞ]]></dc:creator>
            <pubDate>Fri, 17 Sep 2021 11:19:47 GMT</pubDate>
            <atom:updated>2021-09-17T11:38:41.787Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHcV8hSm2pPXuc66s_8_JA.png" /></figure><p>Merhaba, bu yazımda sizlere Django framework için araştırdığım bazı güvenlik önerilerini yazacağım. Öncelikle eğer herkesin erişmesine ihtiyacınız yoksa mutlaka bir network rule ile whitelist yapmamız daha mantıklı olacaktır. Eğer bir atak gelirse bu daha app katmanına gelmeden network katmanında önlemiş olacaksınız. 10 adımda bu güvenlikten bahsedeceğim.</p><h4>1. SSL sertifikası kullanmalıyız.</h4><p>Dağıtımınızı HTTPS arkasından yapmanız her zaman daha güvenli olacaktır. Eğer HTTPS kullanmıyorsanız public network üzerinde bir çok bilgiye sızmak çok zor olamayacaktır(username, pass vs.). SSL etkinleştirme ve daha fazla detay için <a href="https://docs.djangoproject.com/en/3.2/topics/security/#ssl-https">Django dökümanı</a> inceleyebilirsiniz.</p><h4>2. Admin url erişimini değiştirmeliyiz.</h4><p>Bir çok sitenin yönetim paneli “<strong>/admin”</strong> path altında. Bu yüzden mutlaka admin erişimi için url path değiştirilmelidir. Detay için <a href="https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#hooking-adminsite-instances-into-your-urlconf">Django dökümanı</a> inceleyebilirsiniz.</p><pre>urlpatterns = <strong>[<br></strong>    path<strong>(&#39;special-admin-login/&#39;</strong> , admin.site.urls <strong>)</strong> ,<strong><br>]</strong></pre><p>Eğer yönetim paneliniz için daha fazla güvenliğe ihtiyacınız varsa tamamen farklı bir domainde barındırmayı tercih edebilirsiniz. Gerçekten bir tık daha fazla güvenlik için farklı domain + VPN arkasına saklayabilirsiniz.</p><h4>3. Fake admin panel kullanın!</h4><p>Evet evet gayet doğru anladınız! Yönetim panelinizi yukarıda bahsettiğimiz şekilde güvenlik önlemlerini aldıysanız şimdi “/admin” url yoluna admin panel ile aynı olan ama login bilgilerini mail atan bir panel (Fake Panel) kurabilirsiniz. Böylece herkese açık bir yönetim paneline saldıran kişilerin IPlerini alarak black liste ekleyebilirsiniz. <a href="https://github.com/dmpayton/django-admin-honeypot">Django Admin Honeypot</a> kütüphanesini kullanabilirsiniz. Django Conf 2011 de McMillian’ın güvenlik ile ilgili konuşmasından esinlenerek yapılmış bir kütüphane!</p><h4>4. Parola kullanımına dikkat edin.</h4><p>Her zamanki olduğu gibi içerideki (staff ve super olabilir.) kullanıcıların zayıf şifre kullanmayı bir ilke haline getirdiğini biliyoruz. Bu yüzden içeride güçlü parola tutmamız gerekiyor. Bunun için eğer register ekranımız varsa kullanıcıları güçlü parola setlemeye zorlayabiliriz. Validator ile ilgili <a href="https://docs.djangoproject.com/en/3.2/topics/auth/passwords/#module-django.contrib.auth.password_validation">Django dökümanı</a> inceleyebilirsiniz. Kullanıcıların parolalarını daha güvenli hala getirmesini istiyorsanız <a href="https://github.com/Pawamoy/django-zxcvbn-password">Django ZXCVBN Password </a>kütüphanesini kullanabilirsiniz.</p><h4>5. Django’nun en son sürümünü kullanın (LTS).</h4><p>Böylece en son güvenlik güncellemelerini almış olursunuz. <a href="https://www.djangoproject.com/download/">Bu sayfadan</a> takip edebilirsiniz.</p><h4>6. 2 Faktörlü doğrulama kullanın.</h4><p>Şifre güçlendirme dışında bir de 2FA kullanmak güvenliği arttıracaktır. Bunu SMS ile veya Authenticator ile kullanabiliriz. SMS ile olanı önermiyorum çünkü bir numarayı ele geçirmek oldukça kolaydır. QR kod ile tanımlanarak kullanılan <a href="https://www.google.com/landing/2step/#tab=how-it-works">Google Auth </a>kullanmanızı öneriyorum. Bu uygulamanın bir kaç benzer örnekleri var ama Google’a güvenmemiz gerektiğini düşünüyorum. <a href="https://github.com/Bouke/django-two-factor-auth">Django Two Factor Auth</a> adlı kütüphaneyi kullanabilirsiniz. Bu kütüphane bir çok farklı 2FA app’i destekliyor.</p><h4>7. Production için DEBUG modun False olduğundan emin olun.</h4><p>Debug modunu sadece geliştirme süreçlerinde kulladığımızdan production ortamında mutlaka kapalı tutmalıyız. Eğer debug mode açık kalırsa vermek istemediğimiz bir çok bilgi kullanıcıya görünmüş olacaktır (tracebacks vs.). Bunu önlemek için DEBUG modu ENV ortamından alarak staging ve prod environmentlerini ayrı tutabilirsiniz. Tam tersi olarak settings dosyalarınızı ayrıştırabilirsiniz ( Bunu öneriyorum.). Bunun ile ilgili bir yazı <a href="https://simpleisbetterthancomplex.com/tips/2017/07/03/django-tip-20-working-with-multiple-settings-modules.html">buraya</a> tıklayarak inceleyebilirsiniz.</p><h4>8. Hangi ortamda olduğunuza dikkat edin.</h4><p>Aslında bunu kontrol etmek tarayıcının URL çubuğuna bakmak kolayca anlaşılır. Ama bunu insan bazen atlayabiliyor. Bu yüzden paneldeyken KOCAMAN hangi ortamda olduğunuzu yazan bir header iyi olabilir. <a href="https://github.com/dizballanze/django-admin-env-notice">Bu kütüphaneyi</a> kullanarak bunu kolayca yapabilirsiniz.</p><figure><img alt="Django Admin Production Env" src="https://cdn-images-1.medium.com/max/1024/1*lo3z0AOJR1yBvBiri6kdBA.png" /><figcaption>Göründüğü gibi KOCAMAN ve KIRMIZI bir yazı!</figcaption></figure><h4>9. Hatalarınızı kontrol edin!</h4><p>Bu sadece Django veya Python için geçerli değil tüm dillerde mutlaka deployment sürecinden önce mutlaka shell üzerinde görünen hataları kontrol edin. Django için ise şu komut ile kontrol edebilirsiniz.</p><pre>python manage.py check --deploy</pre><p>Bu komut bir check yapacak ve size hataları gösterecektir. <a href="https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/">Django dökümanda</a> inceleyebilirsiniz.</p><h4>10. Zafiyetler ve açıklar kontrol edilmeli (CVE).</h4><p>CVE: “Common Vulnerabilities and exposures”. Yani zafiyetler ve açıklar olarak Türkçe’ye çevirebiliriz. Süreçleri takip edebilir eğer kullandığınız versiyonda bir açık varsa sürüm değişikliği yapabilirsiniz. <a href="https://www.cvedetails.com/product/18211/Djangoproject-Django.html?vendor_id=10199">Buradan</a> takip edilebilir.</p><p>Sevgiler, saygılar ile umarım yardımcı olmuşumdur.</p><p>İnan Delibaş</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2624fefc1d31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python json dumps ile PHP json encode arasındaki fark.]]></title>
            <link>https://medium.com/@inandelibas/python-json-dumps-ile-php-json-encode-aras%C4%B1ndaki-fark-ce9ede6cd887?source=rss-4b3036116dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce9ede6cd887</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[encode]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[İnan DELİBAŞ]]></dc:creator>
            <pubDate>Fri, 19 Mar 2021 16:27:51 GMT</pubDate>
            <atom:updated>2021-03-19T21:13:54.630Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python json dumps ile PHP json encode arasındaki fark</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*aDTCUti6J1EHikxOW4sh1g@2x.jpeg" /></figure><p>Python ve PHP dilleri ile bir çok proje geliştirdim. Fakat bazı projeler için entegrasyon yaparken php ile yazılmış örnek kodları inceledim ve PHP json_encode ile Python json.dumps() arasında fark olduğunu keşfettim.</p><p>Öncelikle bir örnek json hazırlayalım.</p><pre>{&quot;key&quot;: &quot;value&quot;, &quot;key1&quot;: &quot;value1&quot;}</pre><p>Her iki dil için de bu json datayı kullancağız.</p><h3>1. Python:</h3><pre>import json<br>json_data = {&quot;key&quot;: &quot;value&quot;, &quot;key1&quot;: &quot;value1&quot;}<br>encoded_data = json.dumps(json_data)</pre><pre>print(encoded_data) <br># &#39;{&quot;key&quot;: &quot;value&quot;, &quot;key1&quot;: &quot;value1&quot;}&#39;</pre><h3>2. PHP :</h3><pre>$json_data = [&quot;key&quot; =&gt; &quot;value&quot;, &quot;key1&quot; =&gt; &quot;value1&quot;];<br>$encoded_data = json_encode($json_data);<br>var_dump($encoded_data);</pre><pre># string(31) &quot;{&quot;key&quot;:&quot;value&quot;,&quot;key1&quot;:&quot;value1&quot;}&quot;</pre><h3>3. Hash Karşılaştırmaları :</h3><p>Simdi bu iki export aldığımız datayı karşılaştırmak için basic bir hash sistemi kullanalım. Stringleri karşılaştırmak yerine hash kullanarak karşılaştırmak daha doğru ve basit olacaktır.</p><pre># Python Export : &#39;{&quot;key&quot;: &quot;value&quot;, &quot;key1&quot;: &quot;value1&quot;}&#39;<br># PHP Export: &quot;{&quot;key&quot;:&quot;value&quot;,&quot;key1&quot;:&quot;value1&quot;}&quot;</pre><pre># Base 64 encode kullanmak icin Python dilinde stringlerimizi encode # etmemiz gerekiyor. Hatta base64 hash bize byte tipinde return  <br># edecektir. Onu da decode edip string tipine cevireceğim.</pre><pre># Python :</pre><pre>b64_encoded = base64.b64encode(encoded_data.encode(&#39;utf-8&#39;))<br>print(b64_encoded.decode(&#39;utf-8&#39;))<br># &#39;eyJrZXkiOiAidmFsdWUiLCAia2V5MSI6ICJ2YWx1ZTEifQ==&#39;<br></pre><pre># PHP :<br> <br>var_dump(base64_encode($encoded_data))<br># string(44) &quot;eyJrZXkiOiJ2YWx1ZSIsImtleTEiOiJ2YWx1ZTEifQ==&quot;</pre><p>İlk bakışta ben de aa aynı gibi demiştim ama değil işte :)</p><p>Gördüğümüz gibi iki hash birbirinden farklı, şimdi hangi dil doğru yapıyor hangi dil yanlış yapıyor diye tartışmamıza gerek yok sonuca odaklanalım.</p><h3>4. Çözüm :</h3><p>Nasıl iki dilde de aynı json encode alacağız buna bakalım. Aslında json encode dediğimiz şey çok önemsiz gibi görünse de bir çok entegrasyonda güvenlik olarak farklı hash tipleri kullanılır. Hash sistemlerini kullanmak için response-request bodylerindeki datayı json encode etmemiz gerekebiliyor.</p><p>Hadi çözüme odaklanalım…</p><blockquote>Python icin json dumps kullanırken separators parametresi vermemiz gerekiyor. Peki nedir bu seperators?</blockquote><blockquote>Seperators : Verilen değeri öğeler arasında ayraç olarak kullanır, tuple tipinde deger alır.</blockquote><p>Hadi kod yazalım biraz, bu yazdıklarımı unutabilirsin. Kodu yazınca kalıcı olacaktır.</p><pre>Python : </pre><pre>import json<br>json_data = {&quot;key&quot;: &quot;value&quot;, &quot;key1&quot;: &quot;value1&quot;}<br>encoded_data = json.dumps(json_data, separators=(&#39;,&#39;, &#39;:&#39;))<br>print(encoded_data)<br># &#39;{&quot;key&quot;:&quot;value&quot;,&quot;key1&quot;:&quot;value1&quot;}&#39;</pre><pre>PHP: </pre><pre>$json_data = [&quot;key&quot; =&gt; &quot;value&quot;, &quot;key1&quot; =&gt; &quot;value1&quot;];<br>var_dump(json_encode($json_data));<br># string(31) &quot;{&quot;key&quot;:&quot;value&quot;,&quot;key1&quot;:&quot;value1&quot;}&quot;</pre><p>Simdi aynı gibi görünüyor değil mi ? Hadi hash ile kontrol edelim :)</p><pre># Python Export : &#39;{&quot;key&quot;:&quot;value&quot;,&quot;key1&quot;:&quot;value1&quot;}&#39;<br># PHP Export: &quot;{&quot;key&quot;:&quot;value&quot;,&quot;key1&quot;:&quot;value1&quot;}&quot;</pre><pre>Python :</pre><pre>import base64<br>import json<br>json_data = {&quot;key&quot;: &quot;value&quot;, &quot;key1&quot;: &quot;value1&quot;}<br>encoded_data = json.dumps(json_data, separators=(&#39;,&#39;, &#39;:&#39;))<br>b64_encoded = base64.b64encode(encoded_data.encode(&#39;utf-8&#39;))<br>print(b64_encoded.decode(&#39;utf-8&#39;))<br># &quot;eyJrZXkiOiJ2YWx1ZSIsImtleTEiOiJ2YWx1ZTEifQ==&quot;</pre><pre>PHP: </pre><pre>$json_data = [&quot;key&quot; =&gt; &quot;value&quot;, &quot;key1&quot; =&gt; &quot;value1&quot;];<br>$encoded_data = json_encode($json_data);<br>echo base64_encode($encoded_data);<br># &quot;eyJrZXkiOiJ2YWx1ZSIsImtleTEiOiJ2YWx1ZTEifQ==&quot;</pre><p>Son olarak hash leri kontrol edelim artık :)</p><pre>Python base64 hash: &quot;eyJrZXkiOiJ2YWx1ZSIsImtleTEiOiJ2YWx1ZTEifQ==&quot; PHP base64 hash:&#39;eyJrZXkiOiJ2YWx1ZSIsImtleTEiOiJ2YWx1ZTEifQ==&#39;</pre><p>Baya baya aynı :) <br>Sevgiler</p><p>İnan Delibaş</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce9ede6cd887" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>