<?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"><channel><title><![CDATA[JohnSpeaks ]]></title><description><![CDATA[JohnSpeaks ]]></description><link>https://sirneij.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sun, 15 Nov 2026 08:50:56 GMT</lastBuildDate><atom:link href="https://sirneij.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[FullStack JWT Auth: Migrating SvelteKit to its latest version]]></title><description><![CDATA[From where we left off, SvelteKit has undergone some breaking changes as discussed in Fixing load, and tightening up SvelteKit's design before 1.0 #5748…]]></description><link>https://sirneij.hashnode.dev/fullstack-jwt-auth-migrating-sveltekit-to-its-latest-version</link><guid isPermaLink="true">https://sirneij.hashnode.dev/fullstack-jwt-auth-migrating-sveltekit-to-its-latest-version</guid><category><![CDATA[BlogsWithCC]]></category><category><![CDATA[Sveltekit]]></category><category><![CDATA[Svelte]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[John Idogun]]></dc:creator><pubDate>Sat, 08 Oct 2022 21:45:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1665265198142/xHH_lZ-b9.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>From where we left off, SvelteKit has undergone some breaking changes as discussed in <a target="_blank" href="https://github.com/sveltejs/kit/discussions/5748">Fixing load, and tightening up SvelteKit's design before 1.0 #5748</a>. The subject of this article is not to discuss whether or not these breaking changes are worth it. We basically want to see how to successfully update the application built in the course of this series of articles to incorporate the latest design decisions of SvelteKit. We will extensively refer to this <a target="_blank" href="https://github.com/sveltejs/kit/discussions/5774">Migration guide #5774</a>.</p>
<h2 id="heading-assumption">Assumption</h2>
<p>In case you want to catch up, kindly go through <a target="_blank" href="https://dev.to/sirneij/fullstack-jwt-authentication-and-authorization-system-with-django-and-sveltekit-2ih3">the series where we built a Fullstack application with Django and SvelteKit</a> from scratch.</p>
<h2 id="heading-source-code">Source code</h2>
<p>These changes can be seen in this <a target="_blank" href="https://github.com/Sirneij/django_svelte_jwt_auth/commit/3c02bfabe55c7b5504b20b54026e935aaf84a4fe">git commit</a>.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/Sirneij/django_svelte_jwt_auth">https://github.com/Sirneij/django_svelte_jwt_auth</a></div>
<h2 id="heading-live-version">Live version</h2>
<p>This project was deployed on Heroku (backend) and vercel (frontend) and its live version can be accessed <a target="_blank" href="https://django-sveltekit-jwt-auth.vercel.app/">here</a>.</p>
<h2 id="heading-applications-migration-guide">Application's Migration Guide</h2>
<p>To fully migrate our current application to incorporate the latest changes, the following steps should be taken:</p>
<h3 id="heading-step-1-check-possible-update-in-packagejson">Step 1: Check possible update in <code>package.json</code></h3>
<p>Open up your terminal in the <code>frontend</code> directory and issue the following command:</p>
<pre><code class="lang-bash">╭─[Johns-MacBook-Pro] as sirneij <span class="hljs-keyword">in</span> ~/Documents/Devs/django_svelte_jwt_auth/frontend using node v18.10.0 on (main)✔                                            09:16:47
╰─(๑˃̵ᴗ˂̵)و npx npm-check-updates -u
</code></pre>
<p>Then:</p>
<pre><code class="lang-bash">╭─[Johns-MacBook-Pro] as sirneij <span class="hljs-keyword">in</span> ~/Documents/Devs/django_svelte_jwt_auth/frontend using node v18.10.0 on (main)✔                                            09:16:47
╰─(๑˃̵ᴗ˂̵)و npm install
</code></pre>
<p>After that, change the <code>"dev"</code>, <code>"build"</code>, <code>"package"</code>, and <code>"preview"</code> part of <code>scripts</code> in <code>package.json</code> file to:</p>
<pre><code class="lang-json">{
    ...
    <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"vite dev"</span>,
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"vite build"</span>,
    <span class="hljs-attr">"package"</span>: <span class="hljs-string">"vite package"</span>,
    <span class="hljs-attr">"preview"</span>: <span class="hljs-string">"vite preview"</span>,
    ...
  },
  ...
}
</code></pre>
<p>These ensure that SvelteKit uses <code>vite</code> for serving your files in development, build, packaging, or preview mode.</p>
<hr />
<p>These commands should update all the dependencies in the project's <code>package.json</code> file. Peradventure it didn't, remove the project's <code>node_modules</code> and <code>package-lock.json</code> file:</p>
<pre><code class="lang-bash">╭─[Johns-MacBook-Pro] as sirneij <span class="hljs-keyword">in</span> ~/Documents/Devs/django_svelte_jwt_auth/frontend using node v18.10.0 on (main)✔                                            09:16:47
╰─(๑˃̵ᴗ˂̵)و rm -rf node_modules package-lock.json
</code></pre>
<p>Then, manually update your <code>package.json</code> file's <code>"devDependencies"</code> and <code>"dependencies"</code> sections to the following:</p>
<pre><code class="lang-json">{
    ...
    <span class="hljs-attr">"devDependencies"</span>: {
        <span class="hljs-attr">"@sveltejs/adapter-auto"</span>: <span class="hljs-string">"next"</span>,
        <span class="hljs-attr">"@sveltejs/kit"</span>: <span class="hljs-string">"^1.0.0-next.511"</span>,
        <span class="hljs-attr">"@typescript-eslint/eslint-plugin"</span>: <span class="hljs-string">"^5.39.0"</span>,
        <span class="hljs-attr">"@typescript-eslint/parser"</span>: <span class="hljs-string">"^5.39.0"</span>,
        <span class="hljs-attr">"eslint"</span>: <span class="hljs-string">"^8.24.0"</span>,
        <span class="hljs-attr">"eslint-config-prettier"</span>: <span class="hljs-string">"^8.5.0"</span>,
        <span class="hljs-attr">"eslint-plugin-svelte3"</span>: <span class="hljs-string">"^4.0.0"</span>,
        <span class="hljs-attr">"prettier"</span>: <span class="hljs-string">"^2.7.1"</span>,
        <span class="hljs-attr">"prettier-plugin-svelte"</span>: <span class="hljs-string">"^2.7.1"</span>,
        <span class="hljs-attr">"svelte"</span>: <span class="hljs-string">"^3.50.1"</span>,
        <span class="hljs-attr">"svelte-check"</span>: <span class="hljs-string">"^2.9.1"</span>,
        <span class="hljs-attr">"svelte-preprocess"</span>: <span class="hljs-string">"^4.10.7"</span>,
        <span class="hljs-attr">"tslib"</span>: <span class="hljs-string">"^2.4.0"</span>,
        <span class="hljs-attr">"typescript"</span>: <span class="hljs-string">"^4.8.4"</span>
    },
    ...
    <span class="hljs-attr">"dependencies"</span>: {
        <span class="hljs-attr">"@sveltejs/adapter-vercel"</span>: <span class="hljs-string">"^1.0.0-next.77"</span>
    }
    ...
}
</code></pre>
<p>Then install them:</p>
<pre><code class="lang-bash">╭─[Johns-MacBook-Pro] as sirneij <span class="hljs-keyword">in</span> ~/Documents/Devs/django_svelte_jwt_auth/frontend using node v18.10.0 on (main)✔                                            09:16:47
╰─(๑˃̵ᴗ˂̵)و npm install
</code></pre>
<h3 id="heading-step-2-run-sveltekits-migration-script">Step 2: Run SvelteKit's migration script</h3>
<p>To ease migrating previous codebases to the new design, SvelteKit's maintainers wrote a migration script. Run the migration script using the command below:</p>
<pre><code class="lang-bash">╭─[Johns-MacBook-Pro] as sirneij <span class="hljs-keyword">in</span> ~/Documents/Devs/django_svelte_jwt_auth/frontend using node v18.10.0 on (main)✔                                            09:16:47
╰─(๑˃̵ᴗ˂̵)و npx svelte-migrate routes
</code></pre>
<p>At first, it needs to be installed which you should consent to. The script helps rename your files and create directories when appropriate. Our <code>routes/__layout.svelte</code> turns to <code>+layout.svelte</code>, <code>routes/index.svelte</code> to <code>routes/+page.svelte</code>, and so on. All codes in each file's <code>&lt;script context="module" lang="ts"&gt; ... &lt;/script&gt;</code> have been moved to the file's or directory's <code>+page.ts</code>. If a file's <code>&lt;script context="module" lang="ts"&gt; ... &lt;/script&gt;</code> returns a prop such as the one previously in <code>routes/accounts/user/[username]-[id].svelte</code>, you will have to return only the data, in this case <code>userResponse</code> without putting it in <code>props</code>. Also, in the <code>+page.svelte</code> of the directory, replace <code>export let userResponse: UserResponse;</code> with <code>export let data: any;</code> and all its occurrences.</p>
<p>Aside from these, I also made some TypeScript-based adjustments as seen in the <a target="_blank" href="https://github.com/Sirneij/django_svelte_jwt_auth/commit/3c02bfabe55c7b5504b20b54026e935aaf84a4fe">git commit</a>. <code>browser</code> which previously lived in <code>$app/env</code> has been moved to <code>$app/environment</code>.</p>
<h2 id="heading-outro">Outro</h2>
<p>Enjoyed this article? Consider <a target="_blank" href="mailto:sirneij@gmail.com">contacting me for a job, something worthwhile or buying a coffee ☕</a>. You can also connect with/follow me on <a target="_blank" href="https://www.linkedin.com/in/idogun-john-nelson/">LinkedIn</a> and <a target="_blank" href="https://twitter.com/Sirneij">@Sirneij</a> on Twitter. Also, it isn't bad if you help share it for wider coverage. I will appreciate it...</p>
]]></content:encoded></item><item><title><![CDATA[Building a barebone Web API service in Python without a web framework]]></title><description><![CDATA[Have you ever wondered how Python web frameworks work under the hood? Are you interested in just playing with python and not the complexities of its web…]]></description><link>https://sirneij.hashnode.dev/building-a-barebone-web-api-service-in-python-without-a-web-framework</link><guid isPermaLink="true">https://sirneij.hashnode.dev/building-a-barebone-web-api-service-in-python-without-a-web-framework</guid><category><![CDATA[BlogsWithCC]]></category><category><![CDATA[#BlogsWithCC on Hashnode]]></category><dc:creator><![CDATA[John Idogun]]></dc:creator><pubDate>Sat, 10 Sep 2022 05:32:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1662787488320/KR3p85Y-d.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Have you ever wondered how Python web frameworks work under the hood? Are you interested in just playing with python and not the complexities of its web frameworks such as <a target="_blank" href="https://www.djangoproject.com/">Django</a>, <a target="_blank" href="https://flask.palletsprojects.com/en/2.2.x/">Flask</a>, <a target="_blank" href="https://fastapi.tiangolo.com/">FastAPI</a>, and so on? Do you know that with just Python, you can have some functionalities built? Do you want to explore the popular Python WSGI HTTP Server for UNIX, <a target="_blank" href="https://gunicorn.org/">Gunicorn 'Green Unicorn'</a>? If these sound interesting to you, welcome onboard! We will be exploiting the capabilities of <a target="_blank" href="https://gunicorn.org/">gunicorn</a> to serve our "sketchy", barebone, and "not-recommended-for-production" web API service with the following features:</p>
<ul>
<li>Getting users added to the app</li>
<li>Allowing users to check balances, deposit and withdraw money to other app users and out of the app.</li>
</ul>
<p><strong>NOTE: This application does not incorporate any real database. It stores data in memory.</strong></p>
<h2 id="heading-assumptions">Assumptions</h2>
<p>It is assumed you have a basic understanding of Python, and how the web works.</p>
<h2 id="heading-source-code">Source code</h2>
<p>The entire source code for this article can be accessed via <a target="_blank" href="https://github.com/Sirneij/peer_to_peer">github.com/sirneij/peer_to_peer</a></p>
<h2 id="heading-implementation">Implementation</h2>
<h3 id="heading-step-1-create-a-new-project">Step 1: Create a new project</h3>
<p>As with every project, we need to create it. Open up your terminal/cmd/PowerShell and navigate to the directory where the project will be housed. Then create the project. For me, I used <a target="_blank" href="https://python-poetry.org/">poetry</a> to bootstrap a typical python project like so:</p>
<pre><code class="lang-bash">sirneij@pop-os ~/D/Projects&gt; poetry new peer_to_peer
</code></pre>
<p>I named the project <code>peer_to_peer</code>. Change the directory into it. If <a target="_blank" href="https://python-poetry.org/">poetry</a> was used, you should have a file structure like:</p>
<pre><code class="lang-bash">.
├── peer_to_peer
│   ├── __init__.py
├── pyproject.toml
├── README.md
├── tests
│   ├── __init__.py
</code></pre>
<p>To build this app, we need one dependency, <a target="_blank" href="https://gunicorn.org/">gunicorn</a>. It'll help serve that entire application. Let's install it in our app's virtual environment.</p>
<pre><code class="lang-bash">(virtualenv) sirneij@pop-os ~/D/P/peer_to_peer (main)&gt; pip install gunicorn
</code></pre>
<h3 id="heading-step-2-create-important-files-for-the-project">Step 2: Create important files for the project</h3>
<p>Create some files, <code>server.py</code>, <code>models.py</code>, <code>urls.py</code>, and <code>handlers.py</code>, inside the <code>peer_to_peer</code> folder.</p>
<pre><code class="lang-bash">sirneij@pop-os ~/D/P/peer_to_peer (main)&gt; touch peer_to_peer/server.py peer_to_peer/urls.py peer_to_peer/models.py peer_to_peer/handlers.py
</code></pre>
<p><code>server.py</code> does exactly what its name implies. It is the entry point of the app. <code>models.py</code> will hold the app's "model" or more appropriately, in-memory database. <code>urls.py</code> routes all requests to the appropriate logic. <code>handlers.py</code> houses the logic of each route.</p>
<h3 id="heading-step-3-design-the-apps-database">Step 3: Design the app's database</h3>
<p>Let's employ the database-first approach by defining the kind of data our app needs. It will be a Python class with a single field which is a list of dictionaries, <code>_user_data</code>.</p>
<pre><code class="lang-python"><span class="hljs-comment"># peer_to_peer/models.py</span>

<span class="hljs-keyword">from</span> typing <span class="hljs-keyword">import</span> Any


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>:</span>
    _user_data: list[dict[str, Any]] = []

<span class="hljs-meta">    @property</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">user_data</span>(<span class="hljs-params">self</span>) -&gt; list[dict[str, Any]]:</span>
        <span class="hljs-keyword">return</span> self._user_data

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">set_user_data</span>(<span class="hljs-params">self, data</span>):</span>
        self._user_data = self._user_data.append(data)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">return_user</span>(<span class="hljs-params">self, username</span>) -&gt; dict[str, Any] | <span class="hljs-keyword">None</span>:</span>
        <span class="hljs-keyword">for</span> d <span class="hljs-keyword">in</span> self._user_data:
            <span class="hljs-keyword">if</span> username <span class="hljs-keyword">in</span> d.values():
                <span class="hljs-keyword">return</span> d
        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>
</code></pre>
<p>This field was made "private" but a "getter" property, <code>user_data</code>, gets its value for the "outside world" to use. We also defined a "setter", <code>set_user_data</code> method that appends data to it. There was a <code>return_user</code> method which searches the "database" for a user via the "unique" <code>username</code> (or name) and returns such user in case it's found. Pretty basic!</p>
<p>Let's proceed to the content of the <code>server.py</code>.</p>
<h3 id="heading-step-4-write-the-apps-entry-script">Step 4: Write the app's entry script</h3>
<pre><code class="lang-python"><span class="hljs-comment"># peer_to_peer/server.py</span>

<span class="hljs-keyword">from</span> typing <span class="hljs-keyword">import</span> Iterator

<span class="hljs-keyword">from</span> peer_to_peer.models <span class="hljs-keyword">import</span> User
<span class="hljs-keyword">from</span> peer_to_peer.urls <span class="hljs-keyword">import</span> url_handlers


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">app</span>(<span class="hljs-params">environ, start_reponse</span>) -&gt; Iterator[bytes]:</span>
    user = User()
    <span class="hljs-keyword">return</span> iter([url_handlers(environ, start_reponse, user)])
</code></pre>
<p>The simple script above is the app's entry point. It's a two-liner housed by the <code>app</code> function. This function takes the <code>environ</code> and <code>start_reponse</code> arguments, the requirements for <a target="_blank" href="https://gunicorn.org/">gunicorn</a> apps as defined <a target="_blank" href="https://docs.gunicorn.org/en/latest/run.html#gunicorn">here</a>. The <code>environ</code> serves as the "request" object which contains all the details of all incoming requests to the app. As for the <code>start_reponse</code>, it defines the response's status code and headers. This function returns an <code>Iterator</code> of <code>bytes</code>. For data consistency, we passed only one instance of the User model defined previously to the <code>url_hadndlers</code>, housed in the <code>urls.py</code> file. The content of which is shown below:</p>
<pre><code class="lang-python"><span class="hljs-comment"># peer_to_peer/urls.py</span>
<span class="hljs-keyword">import</span> json

<span class="hljs-keyword">from</span> peer_to_peer.handlers <span class="hljs-keyword">import</span> (
    add_money,
    add_user,
    check_balance,
    index,
    transfer_money_out,
    transfer_money_to_user,
)
<span class="hljs-keyword">from</span> peer_to_peer.models <span class="hljs-keyword">import</span> User


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">url_handlers</span>(<span class="hljs-params">environ, start_reponse, user: User</span>):</span>
    path = environ.get(<span class="hljs-string">'PATH_INFO'</span>)
    <span class="hljs-keyword">if</span> path.endswith(<span class="hljs-string">'/'</span>):
        path = path[:<span class="hljs-number">-1</span>]

    <span class="hljs-keyword">if</span> path == <span class="hljs-string">''</span>:
        context = index(environ, user)
        data = json.dumps(context.get(<span class="hljs-string">'data'</span>)) <span class="hljs-keyword">if</span> context.get(<span class="hljs-string">'data'</span>) <span class="hljs-keyword">else</span> json.dumps(context.get(<span class="hljs-string">'error'</span>))
        status = context[<span class="hljs-string">'status'</span>]

    <span class="hljs-keyword">elif</span> path == <span class="hljs-string">'/add-user'</span>:
        context = add_user(environ, user)
        data = json.dumps(context.get(<span class="hljs-string">'data'</span>)) <span class="hljs-keyword">if</span> context.get(<span class="hljs-string">'data'</span>) <span class="hljs-keyword">else</span> json.dumps(context.get(<span class="hljs-string">'error'</span>))
        status = context[<span class="hljs-string">'status'</span>]

    <span class="hljs-keyword">elif</span> path == <span class="hljs-string">'/add-money'</span>:
        context = add_money(environ, user)
        data = json.dumps(context.get(<span class="hljs-string">'data'</span>)) <span class="hljs-keyword">if</span> context.get(<span class="hljs-string">'data'</span>) <span class="hljs-keyword">else</span> json.dumps(context.get(<span class="hljs-string">'error'</span>))
        status = context[<span class="hljs-string">'status'</span>]
    <span class="hljs-keyword">elif</span> path == <span class="hljs-string">'/check-balance'</span>:
        context = check_balance(environ, user)
        data = json.dumps(context.get(<span class="hljs-string">'data'</span>)) <span class="hljs-keyword">if</span> context.get(<span class="hljs-string">'data'</span>) <span class="hljs-keyword">else</span> json.dumps(context.get(<span class="hljs-string">'error'</span>))
        status = context[<span class="hljs-string">'status'</span>]
    <span class="hljs-keyword">elif</span> path == <span class="hljs-string">'/transfer-money-to-user'</span>:
        context = transfer_money_to_user(environ, user)
        data = json.dumps(context.get(<span class="hljs-string">'data'</span>)) <span class="hljs-keyword">if</span> context.get(<span class="hljs-string">'data'</span>) <span class="hljs-keyword">else</span> json.dumps(context.get(<span class="hljs-string">'error'</span>))
        status = context[<span class="hljs-string">'status'</span>]
    <span class="hljs-keyword">elif</span> path == <span class="hljs-string">'/transfer-money-out'</span>:
        context = transfer_money_out(environ, user)
        data = json.dumps(context.get(<span class="hljs-string">'data'</span>)) <span class="hljs-keyword">if</span> context.get(<span class="hljs-string">'data'</span>) <span class="hljs-keyword">else</span> json.dumps(context.get(<span class="hljs-string">'error'</span>))
        status = context[<span class="hljs-string">'status'</span>]
    <span class="hljs-keyword">else</span>:
        data, status = json.dumps({<span class="hljs-string">'error'</span>: <span class="hljs-string">'404 Not Found'</span>}), <span class="hljs-string">'400 Not FOund'</span>

    data = data.encode(<span class="hljs-string">'utf-8'</span>)
    content_type = <span class="hljs-string">'application/json'</span> <span class="hljs-keyword">if</span> int(status.split(<span class="hljs-string">' '</span>)[<span class="hljs-number">0</span>]) &lt; <span class="hljs-number">400</span> <span class="hljs-keyword">else</span> <span class="hljs-string">'text/plain'</span>
    response_headers = [(<span class="hljs-string">'Content-Type'</span>, content_type), (<span class="hljs-string">'Content-Length'</span>, str(len(data)))]

    start_reponse(status, response_headers)
    <span class="hljs-keyword">return</span> data
</code></pre>
<p>If you are familiar with any of the Python web frameworks mentioned earlier, this is equivalent to how requests are being routed. The <code>environ</code> contains, among many other things, the <code>PATH_INFO</code> which represents the URL entered into your browser. From the path info, we tried calling different logic as contained in the <code>handlers.py</code>, to be discussed soon. For each path, we turn the data or error returned into <a target="_blank" href="https://www.json.org/json-en.html">JSON</a> using python's JSON module and then extract the status of the request. Later on, the data were encoded to be <code>utf-8</code>-compliant and the headers were set accordingly. Now to the <code>handlers.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-comment"># peer_to_peer/handlers.py</span>
<span class="hljs-keyword">from</span> typing <span class="hljs-keyword">import</span> Any
<span class="hljs-keyword">from</span> urllib <span class="hljs-keyword">import</span> parse

<span class="hljs-keyword">from</span> peer_to_peer.models <span class="hljs-keyword">import</span> User


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span>(<span class="hljs-params">environ, user: User</span>) -&gt; dict[str, Any]:</span>
    <span class="hljs-string">"""Display the in-memory data to users."""</span>
    request_params = dict(parse.parse_qsl(parse.urlsplit(environ.get(<span class="hljs-string">'RAW_URI'</span>)).query))

    context = {<span class="hljs-string">'status'</span>: <span class="hljs-string">'200 Ok'</span>}
    <span class="hljs-keyword">if</span> request_params <span class="hljs-keyword">and</span> request_params.get(<span class="hljs-string">'name'</span>).replace(<span class="hljs-string">'\''</span>, <span class="hljs-string">''</span>).lower() == <span class="hljs-string">'admin'</span>:
        user_data = user.user_data
        <span class="hljs-keyword">for</span> data <span class="hljs-keyword">in</span> user_data:
            <span class="hljs-keyword">if</span> data:
                <span class="hljs-keyword">if</span> data.get(<span class="hljs-string">'password'</span>):
                    data.pop(<span class="hljs-string">'password'</span>)
        context[<span class="hljs-string">'data'</span>] = user_data

    <span class="hljs-keyword">elif</span> request_params <span class="hljs-keyword">and</span> request_params.get(<span class="hljs-string">'name'</span>).replace(<span class="hljs-string">'\''</span>, <span class="hljs-string">''</span>).lower():
        current_user = user.return_user(request_params.get(<span class="hljs-string">'name'</span>).replace(<span class="hljs-string">'\''</span>, <span class="hljs-string">''</span>).lower())
        context[<span class="hljs-string">'data'</span>] = current_user

    <span class="hljs-keyword">else</span>:
        context[<span class="hljs-string">'data'</span>] = <span class="hljs-string">'You cannot just view this page without a `name` query parameter.'</span>
    <span class="hljs-keyword">return</span> context


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add_user</span>(<span class="hljs-params">environ, user: User</span>) -&gt; dict[str, Any]:</span>
    <span class="hljs-string">"""Use query parameters to add users to the in-memory data."""</span>

    <span class="hljs-keyword">if</span> parse.parse_qsl(parse.urlsplit(environ.get(<span class="hljs-string">'RAW_URI'</span>)).query) == <span class="hljs-string">''</span>:
        <span class="hljs-keyword">return</span> {<span class="hljs-string">'error'</span>: <span class="hljs-string">'405 Method Not Allowed'</span>, <span class="hljs-string">'status'</span>: <span class="hljs-string">'405 Method Not Allowed'</span>}
    request_meta_query = dict(parse.parse_qsl(parse.urlsplit(environ.get(<span class="hljs-string">'RAW_URI'</span>)).query))
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> request_meta_query:
        <span class="hljs-keyword">return</span> {<span class="hljs-string">'error'</span>: <span class="hljs-string">'Query must be provided.'</span>, <span class="hljs-string">'status'</span>: <span class="hljs-string">'405 Method Not Allowed'</span>}

    user_data = user.user_data
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> any(d.get(<span class="hljs-string">'username'</span>) == request_meta_query.get(<span class="hljs-string">'name'</span>).replace(<span class="hljs-string">'\''</span>, <span class="hljs-string">''</span>).lower() <span class="hljs-keyword">for</span> d <span class="hljs-keyword">in</span> user_data):
        <span class="hljs-keyword">if</span> all(<span class="hljs-keyword">not</span> data <span class="hljs-keyword">for</span> data <span class="hljs-keyword">in</span> user_data):
            user.set_user_data(
                {
                    <span class="hljs-string">'id'</span>: <span class="hljs-number">1</span>,
                    <span class="hljs-string">'username'</span>: request_meta_query.get(<span class="hljs-string">'name'</span>).replace(<span class="hljs-string">'\''</span>, <span class="hljs-string">''</span>).lower(),
                    <span class="hljs-string">'password'</span>: request_meta_query.get(<span class="hljs-string">'password'</span>),
                }
            )
        <span class="hljs-keyword">else</span>:
            user.set_user_data(
                {
                    <span class="hljs-string">'id'</span>: user_data[<span class="hljs-number">-1</span>][<span class="hljs-string">'id'</span>] + <span class="hljs-number">1</span>,
                    <span class="hljs-string">'username'</span>: request_meta_query.get(<span class="hljs-string">'name'</span>).replace(<span class="hljs-string">'\''</span>, <span class="hljs-string">''</span>).lower(),
                    <span class="hljs-string">'password'</span>: request_meta_query.get(<span class="hljs-string">'password'</span>),
                }
            )

    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> {
            <span class="hljs-string">'error'</span>: <span class="hljs-string">f'A user with username, <span class="hljs-subst">{request_meta_query.get(<span class="hljs-string">"name"</span>)}</span>, already exists.'</span>,
            <span class="hljs-string">'status'</span>: <span class="hljs-string">'409 Conflict'</span>,
        }
    context = {<span class="hljs-string">'data'</span>: user_data[<span class="hljs-number">-1</span>], <span class="hljs-string">'status'</span>: <span class="hljs-string">'200 Ok'</span>}
    <span class="hljs-keyword">return</span> context


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add_money</span>(<span class="hljs-params">environ, user: User</span>) -&gt; dict[str, Any]:</span>
    <span class="hljs-string">"""Use query parameters to add money to a user's account to the in-memory data."""</span>
    <span class="hljs-keyword">if</span> parse.parse_qsl(parse.urlsplit(environ.get(<span class="hljs-string">'RAW_URI'</span>)).query) == <span class="hljs-string">''</span>:
        <span class="hljs-keyword">return</span> {<span class="hljs-string">'error'</span>: <span class="hljs-string">'405 Method Not Allowed'</span>, <span class="hljs-string">'status'</span>: <span class="hljs-string">'405 Method Not Allowed'</span>}
    request_meta_query = dict(parse.parse_qsl(parse.urlsplit(environ.get(<span class="hljs-string">'RAW_URI'</span>)).query))
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> request_meta_query:
        <span class="hljs-keyword">return</span> {<span class="hljs-string">'error'</span>: <span class="hljs-string">'Query must be provided.'</span>, <span class="hljs-string">'status'</span>: <span class="hljs-string">'405 Method Not Allowed'</span>}

    context = {<span class="hljs-string">'status'</span>: <span class="hljs-string">'200 Ok'</span>}

    user_data = user.return_user(request_meta_query.get(<span class="hljs-string">'name'</span>).replace(<span class="hljs-string">'\''</span>, <span class="hljs-string">''</span>).lower())
    <span class="hljs-keyword">if</span> user_data:
        <span class="hljs-keyword">if</span> user_data[<span class="hljs-string">'password'</span>] == request_meta_query.get(<span class="hljs-string">'password'</span>):
            user_data[<span class="hljs-string">'balance'</span>] = user_data.get(<span class="hljs-string">'balance'</span>, <span class="hljs-number">0.0</span>) + float(request_meta_query.get(<span class="hljs-string">'amount'</span>))
            context[<span class="hljs-string">'data'</span>] = user_data
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> {
                <span class="hljs-string">'error'</span>: <span class="hljs-string">'You are not authorized to add money to this user\'s balance.'</span>,
                <span class="hljs-string">'status'</span>: <span class="hljs-string">'401 Unauthorized'</span>,
            }
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> {<span class="hljs-string">'error'</span>: <span class="hljs-string">'A user with that name does not exist.'</span>, <span class="hljs-string">'status'</span>: <span class="hljs-string">'404 Not Found'</span>}

    <span class="hljs-keyword">return</span> context


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_balance</span>(<span class="hljs-params">environ, user: User</span>) -&gt; dict[str, Any]:</span>
    <span class="hljs-string">"""Use query parameters to check a user's account balance to the in-memory data."""</span>
    <span class="hljs-keyword">if</span> parse.parse_qsl(parse.urlsplit(environ.get(<span class="hljs-string">'RAW_URI'</span>)).query) == <span class="hljs-string">''</span>:
        <span class="hljs-keyword">return</span> {<span class="hljs-string">'error'</span>: <span class="hljs-string">'405 Method Not Allowed'</span>, <span class="hljs-string">'status'</span>: <span class="hljs-string">'405 Method Not Allowed'</span>}
    request_meta_query = dict(parse.parse_qsl(parse.urlsplit(environ.get(<span class="hljs-string">'RAW_URI'</span>)).query))
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> request_meta_query:
        <span class="hljs-keyword">return</span> {<span class="hljs-string">'error'</span>: <span class="hljs-string">'Query must be provided.'</span>, <span class="hljs-string">'status'</span>: <span class="hljs-string">'405 Method Not Allowed'</span>}

    context = {<span class="hljs-string">'status'</span>: <span class="hljs-string">'200 Ok'</span>}

    user_data = user.return_user(request_meta_query.get(<span class="hljs-string">'name'</span>).replace(<span class="hljs-string">'\''</span>, <span class="hljs-string">''</span>).lower())
    <span class="hljs-keyword">if</span> user_data:
        password = request_meta_query.get(<span class="hljs-string">'password'</span>)
        <span class="hljs-keyword">if</span> password:
            <span class="hljs-keyword">if</span> user_data[<span class="hljs-string">'password'</span>] == password:
                context[<span class="hljs-string">'data'</span>] = {<span class="hljs-string">'balance'</span>: user_data.get(<span class="hljs-string">'balance'</span>, <span class="hljs-number">0.0</span>)}
            <span class="hljs-keyword">else</span>:
                <span class="hljs-keyword">return</span> {
                    <span class="hljs-string">'error'</span>: <span class="hljs-string">'You are not authorized to check this user\'s balance.'</span>,
                    <span class="hljs-string">'status'</span>: <span class="hljs-string">'401 Unauthorized'</span>,
                }
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> {
                <span class="hljs-string">'error'</span>: <span class="hljs-string">'You must provide the user\'s password to check balance.'</span>,
                <span class="hljs-string">'status'</span>: <span class="hljs-string">'401 Unauthorized'</span>,
            }
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> {<span class="hljs-string">'error'</span>: <span class="hljs-string">'A user with that name does not exist.'</span>, <span class="hljs-string">'status'</span>: <span class="hljs-string">'404 Not Found'</span>}
    <span class="hljs-keyword">return</span> context


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">transfer_money_to_user</span>(<span class="hljs-params">environ, user: User</span>) -&gt; dict[str, Any]:</span>
    <span class="hljs-string">"""Use query parameters to transfer money from a user to another."""</span>
    <span class="hljs-keyword">if</span> parse.parse_qsl(parse.urlsplit(environ.get(<span class="hljs-string">'RAW_URI'</span>)).query) == <span class="hljs-string">''</span>:
        <span class="hljs-keyword">return</span> {<span class="hljs-string">'error'</span>: <span class="hljs-string">'405 Method Not Allowed'</span>, <span class="hljs-string">'status'</span>: <span class="hljs-string">'405 Method Not Allowed'</span>}
    request_meta_query = dict(parse.parse_qsl(parse.urlsplit(environ.get(<span class="hljs-string">'RAW_URI'</span>)).query))
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> request_meta_query:
        <span class="hljs-keyword">return</span> {<span class="hljs-string">'error'</span>: <span class="hljs-string">'Query must be provided.'</span>, <span class="hljs-string">'status'</span>: <span class="hljs-string">'405 Method Not Allowed'</span>}

    context = {<span class="hljs-string">'status'</span>: <span class="hljs-string">'200 Ok'</span>}

    user_data = user.return_user(request_meta_query.get(<span class="hljs-string">'from_name'</span>).replace(<span class="hljs-string">'\''</span>, <span class="hljs-string">''</span>).lower())

    <span class="hljs-keyword">if</span> user_data:
        <span class="hljs-keyword">if</span> user_data[<span class="hljs-string">'password'</span>] == request_meta_query.get(<span class="hljs-string">'from_password'</span>):
            <span class="hljs-keyword">if</span> request_meta_query.get(<span class="hljs-string">'amount'</span>) <span class="hljs-keyword">and</span> user_data.get(<span class="hljs-string">'balance'</span>, <span class="hljs-number">0.0</span>) &gt;= float(
                request_meta_query.get(<span class="hljs-string">'amount'</span>)
            ):
                beneficiary = user.return_user(request_meta_query.get(<span class="hljs-string">'to_name'</span>).replace(<span class="hljs-string">'\''</span>, <span class="hljs-string">''</span>).lower())
                <span class="hljs-keyword">if</span> beneficiary:
                    beneficiary[<span class="hljs-string">'balance'</span>] = beneficiary.get(<span class="hljs-string">'balance'</span>, <span class="hljs-number">0.0</span>) + float(request_meta_query[<span class="hljs-string">'amount'</span>])
                    user_data[<span class="hljs-string">'balance'</span>] = user_data[<span class="hljs-string">'balance'</span>] - float(request_meta_query[<span class="hljs-string">'amount'</span>])
                    context[
                        <span class="hljs-string">'data'</span>
                    ] = <span class="hljs-string">f'A sum of $<span class="hljs-subst">{float(request_meta_query[<span class="hljs-string">"amount"</span>])}</span> was successfully transferred to <span class="hljs-subst">{request_meta_query.get(<span class="hljs-string">"to_name"</span>)}</span>.'</span>
                <span class="hljs-keyword">else</span>:
                    <span class="hljs-keyword">return</span> {
                        <span class="hljs-string">'error'</span>: <span class="hljs-string">'The user you want to credit does not exist.'</span>,
                        <span class="hljs-string">'status'</span>: <span class="hljs-string">'404 Not Found'</span>,
                    }
            <span class="hljs-keyword">else</span>:
                <span class="hljs-keyword">return</span> {
                    <span class="hljs-string">'error'</span>: <span class="hljs-string">'You either have insufficient funds or did not include `amount` as query parameter.'</span>,
                    <span class="hljs-string">'status'</span>: <span class="hljs-string">'404 Not Found'</span>,
                }
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> {
                <span class="hljs-string">'error'</span>: <span class="hljs-string">'You are not authorized to access this user\'s account.'</span>,
                <span class="hljs-string">'status'</span>: <span class="hljs-string">'401 Unauthorized'</span>,
            }
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> {<span class="hljs-string">'error'</span>: <span class="hljs-string">'A user with that name does not exist.'</span>, <span class="hljs-string">'status'</span>: <span class="hljs-string">'404 Not Found'</span>}
    <span class="hljs-keyword">return</span> context


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">transfer_money_out</span>(<span class="hljs-params">environ, user: User</span>) -&gt; dict[str, Any]:</span>
    <span class="hljs-string">"""Use query parameters to transfer money out of this app."""</span>
    <span class="hljs-keyword">if</span> parse.parse_qsl(parse.urlsplit(environ.get(<span class="hljs-string">'RAW_URI'</span>)).query) == <span class="hljs-string">''</span>:
        <span class="hljs-keyword">return</span> {<span class="hljs-string">'error'</span>: <span class="hljs-string">'405 Method Not Allowed'</span>, <span class="hljs-string">'status'</span>: <span class="hljs-string">'405 Method Not Allowed'</span>}
    request_meta_query = dict(parse.parse_qsl(parse.urlsplit(environ.get(<span class="hljs-string">'RAW_URI'</span>)).query))
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> request_meta_query:
        <span class="hljs-keyword">return</span> {<span class="hljs-string">'error'</span>: <span class="hljs-string">'Query must be provided.'</span>, <span class="hljs-string">'status'</span>: <span class="hljs-string">'405 Method Not Allowed'</span>}

    context = {<span class="hljs-string">'status'</span>: <span class="hljs-string">'200 Ok'</span>}

    user_data = user.return_user(request_meta_query.get(<span class="hljs-string">'name'</span>).replace(<span class="hljs-string">'\''</span>, <span class="hljs-string">''</span>).lower())
    <span class="hljs-keyword">if</span> user_data:
        <span class="hljs-keyword">if</span> user_data.get(<span class="hljs-string">'password'</span>) == request_meta_query.get(<span class="hljs-string">'password'</span>):
            <span class="hljs-keyword">if</span> request_meta_query.get(<span class="hljs-string">'amount'</span>) <span class="hljs-keyword">and</span> user_data.get(<span class="hljs-string">'balance'</span>) &gt;= float(request_meta_query.get(<span class="hljs-string">'amount'</span>)):
                user_data[<span class="hljs-string">'balance'</span>] = user_data[<span class="hljs-string">'balance'</span>] - float(request_meta_query[<span class="hljs-string">'amount'</span>])
                context[
                    <span class="hljs-string">'data'</span>
                ] = <span class="hljs-string">f'A sum of $<span class="hljs-subst">{float(request_meta_query[<span class="hljs-string">"amount"</span>])}</span> was successfully transferred to <span class="hljs-subst">{request_meta_query.get(<span class="hljs-string">"to_bank"</span>)}</span>.'</span>
            <span class="hljs-keyword">else</span>:
                <span class="hljs-keyword">return</span> {
                    <span class="hljs-string">'error'</span>: <span class="hljs-string">'You either have insufficient funds or did not include `amount` as query parameter.'</span>,
                    <span class="hljs-string">'status'</span>: <span class="hljs-string">'404 Not Found'</span>,
                }
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> {
                <span class="hljs-string">'error'</span>: <span class="hljs-string">'You are not authorized to access this user\'s account.'</span>,
                <span class="hljs-string">'status'</span>: <span class="hljs-string">'401 Unauthorized'</span>,
            }
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> {<span class="hljs-string">'error'</span>: <span class="hljs-string">'A user with that name does not exist.'</span>, <span class="hljs-string">'status'</span>: <span class="hljs-string">'404 Not Found'</span>}
    <span class="hljs-keyword">return</span> context
</code></pre>
<p>That's lengthy! However, taking a closer look will reveal that these lines are basic python codes. Each route gets and parses the query parameter(s) included by the user(s). If no parameter was included, an appropriate error will be returned. In case there is/are query parameter(s), different simple logic that manipulates the in-memory data we have was implemented. All pretty simple if looked at.</p>
<h3 id="heading-step-5-running-the-app">Step 5: Running the app</h3>
<p>Having gone through the app's build-up, we can now run it using:</p>
<pre><code class="lang-bash">(virtualenv) sirneij@pop-os ~/D/P/peer_to_peer (main)&gt; gunicorn peer_to_peer.server:app --reload -w 5
</code></pre>
<p>We are giving the app 5 workers using the <code>-w 5</code> flag. You can also turn on DEBUG mode by:</p>
<pre><code class="lang-bash">(virtualenv) sirneij@pop-os ~/D/P/peer_to_peer (main)&gt; gunicorn peer_to_peer.server:app --reload --log-level DEBUG -w 5
</code></pre>
<p>You then can play with the <code>"APIs"</code>. A comprehensive work-through of how to send requests and all are available in the project's <a target="_blank" href="https://github.com/Sirneij/peer_to_peer">README on github</a>.</p>
<h2 id="heading-outro">Outro</h2>
<p>Enjoyed this article? Consider <a target="_blank" href="mailto:sirneij@gmail.com">contacting me for a job, something worthwhile or buying a coffee ☕</a>. You can also connect with/follow me on <a target="_blank" href="https://www.linkedin.com/in/idogun-john-nelson/">LinkedIn</a>. Also, it isn't bad if you help share it for wider coverage. I will appreciate it...</p>
<p>#BlogsWithCC</p>
]]></content:encoded></item></channel></rss>