Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] BrainWaves P2P Social Network – How I Created a Basic Server

#1
BrainWaves P2P Social Network – How I Created a Basic Server

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;1163183&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;starsonly&quot;:&quot;&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</p></div>
<p>Welcome back to the <a href="https://blog.finxter.com/how-i-started-my-journey-to-help-build-a-p2p-social-network-part-1-deciding-on-a-framework/" data-type="post" data-id="1132824" target="_blank" rel="noreferrer noopener">Brainwaves P2P project</a>, or at least my take on it :-). </p>
<p>The <a href="https://blog.finxter.com/how-i-started-my-journey-to-help-build-a-p2p-social-network-part-1-deciding-on-a-framework/" data-type="URL" data-id="https://blog.finxter.com/how-i-started-my-journey-to-help-build-a-p2p-social-network-part-1-deciding-on-a-framework/" target="_blank" rel="noreferrer noopener">previous article</a> was a theoretical explanation of how I envision this project. It is now time to start laying the groundwork! </p>
<h2>I learn as I go…</h2>
<p>As some of you might have guessed already, I’m a completely self-taught coder. Because of that, I’m sure many professionals might not agree with how I code. </p>
<p>I accept that and will welcome any constructive criticism. I have been learning non-stop since I started this project. I assume this will not slow down anytime soon. YouTube is my main source of knowledge as I learn best when seeing something done. I am, in other words, a visual learner. I found an article that explains it well here. </p>
<p>Articles on various sites are the other half of how I learn new concepts in coding. That is how I found Finxter :-).</p>
<p>So to sum it up, my code is far from perfect, and I will never claim it is. This is my take on trying to solve this puzzle. I actually look forward to alternative approaches! </p>
<p>You can <a href="https://github.com/shandralor/PeerBrain" data-type="URL" data-id="https://github.com/shandralor/PeerBrain" target="_blank" rel="noreferrer noopener">open issues on my GitHub</a> if you want to address something.</p>
<p>Now that we all know where we stand let us dive right in! <strong>How to build a server for our peer-to-peer social network app?</strong></p>
<h2>Flask vs FastAPI</h2>
<p>In the <a href="https://blog.finxter.com/how-i-started-my-journey-to-help-build-a-p2p-social-network-part-1-deciding-on-a-framework/" data-type="URL" data-id="https://blog.finxter.com/how-i-started-my-journey-to-help-build-a-p2p-social-network-part-1-deciding-on-a-framework/" target="_blank" rel="noreferrer noopener">previous article</a>, I mentioned that I want to use FastAPI to build the relay server, as opposed to Flask. As I have done before and will do again, I asked ChatGPT about the differences between Flask and FastAPI.</p>
<pre class="wp-block-preformatted"><strong><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f916.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Flask vs FastAPI</strong> <em>Flask is based on the Werkzeug WSGI (Web Server Gateway Interface) toolkit, which is synchronous by default. However, Flask can still be used to build asynchronous applications. You will need to use a third-party library like gevent or asyncio. With these libraries, Flask can use coroutines and event loops to handle I/O operations asynchronously.</em> <em>FastAPI, on the other hand, is designed to be fully asynchronous from the ground up. It uses the async/await syntax of Python to write asynchronous code. It is based on the ASGI (Asynchronous Server Gateway Interface) specification. FastAPI uses the Starlette framework as its foundation. the framework provides a high-performance event loop and asynchronous request handlers.</em></pre>
<p>Both the speed and the asynchrony determined my choice for FastAPI. </p>
<p>Those of you familiar with Flask will know about its built-in development server. As FastAPI doesn’t have this, we’ll need to install a separate server.</p>
<h2>Uvicorn Server </h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://www.uvicorn.org/" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="747" height="468" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-350.png" alt="" class="wp-image-1163291" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-350.png 747w, https://blog.finxter.com/wp-content/uplo...00x188.png 300w" sizes="(max-width: 747px) 100vw, 747px" /></a></figure>
</div>
<p>This is where I encountered my first small hiccup. I code on Windows (I know, sue me <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f61d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />), and I wanted to use Uvicorn. As this only runs on Linux, I needed to get it to function in WSL. </p>
<p>I’ll not go into all the details here, but I could write something about it if anyone has an interest in it. Let me know!</p>
<p>After getting Uvicorn to function as it should, we can continue. It is important to remember that the Python interpreter on WSL does not share anything with its Windows counterpart. This means that you either need two separate virtual environments or that you install pip packages for each OS.</p>
<h2>Creating Basic FastAPI App</h2>
<p>Once all this annoying prep work is done, creating a basic FastAPI app is very easy. We first import FastAPI as below:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from fastapi import FastAPI</pre>
<p>All you need to do afterward is define the basic app and create an endpoint.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#---APP INIT---#
app = FastAPI() @app.get("/")
async def root(): return {"message": "Hello World"}</pre>
<p>To get this to run, you need to navigate to the working directory of your FastAPI project via WSL. Afterward, you call the Uvicorn server. The command below assumes you called your Python file <code>main.py</code>!</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">uvicorn main:app --reload</pre>
<p>I usually run the Uvicorn server in a separate terminal instance of WSL. </p>
<p>That way, I can leave it on and test any changes I make immediately. Later, when I’ll be working on the client also, I can split the terminal. You can then make API calls through the client terminal window. FastAPI’s response in the server WSL window is then visible immediately.</p>
<h2>Receiving “Hello World” from Server</h2>
<p>If you now navigate to <code>127.0.0.1:8000</code> you should get a JSON response with the <code>"Hello World"</code> we returned in the endpoint above. We will change this endpoints function later, but for now, it works to prove our API is working.</p>
<p>For the API server, I have the following layout in mind. It might change throughout the development process. I currently foresee two endpoints that do not require the user to be logged in with a JWT token. The first will be to get that token, and the second to register a new user. Everything else will require the user to be authenticated.</p>
<p>I stated earlier that I would change the root’s endpoint function. Its new role is now to allow a user to request a JWT token. The token is only granted after providing a correct combination of username and password. This requires a dedicated set of both helper functions and Pydantic models to work. </p>
<p>I will go into this in another article, as it requires much explaining :-). It was something I am still learning myself.</p>
<h2>Endpoint Layout</h2>
<p>The current layout of my endpoints at a high level is the following:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#---OPEN ENDPOINTS---# #Root route to get token
@app.post("/", response_model=Token) #Route to create a new user
@app.post("/api/v1/users") #---AUTH ENDPOINTS---# #Route to get all current users and their attributes(development only)
@app.get("/api/v1/users") #Route to test if the token is valid, used while authenticating
@app.get("/api/v1/token-test") #Route to get all thoughts/messages created by a certain user
@app.get("/api/v1/thoughts/{username}") #Route to return all thoughts/messages containing the query string
@app.get("/api/v1/thoughts/{query_str}") #Route to create a new message/thought
@app.post("/api/v1/thoughts") #Route to return all info about the current user(like a user profile)
@app.get("/api/v1/me", response_model=User)
</pre>
<p>The current setup should allow for the barebones functionality of the application. At least from a server point of view. The routes above and/or their function are liable to change during development.  I do find it helps to have a visual reminder of what I am working toward. That is why I created the high-level outlay. As you might recall, I am a visual learner <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f600.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>
<h2>Database Considerations</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="709" height="704" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-351.png" alt="" class="wp-image-1163293" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-351.png 709w, https://blog.finxter.com/wp-content/uplo...00x298.png 300w, https://blog.finxter.com/wp-content/uplo...50x150.png 150w" sizes="(max-width: 709px) 100vw, 709px" /></figure>
</div>
<p>I will dedicate the last part of this article to the database part. As we need to store both users, user credentials, and messages/tweets somewhere, a database is a must.</p>
<p>If you have read any of my previous articles, you will know I like Deta a lot.</p>
<p>Their NoSQL databases work great for development. They recently evolved into <a href="https://deta.space/manual/apps">Deta Space</a>. This change makes their ecosystem even more interesting for developers. The fact that they are free is also important for a single developer coding this app on his own time <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f61d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />. Make sure to check them out!</p>
<p>The next article will focus on both the database code and the Pydantic models we will need to get our API to function.</p>
<p>As always, feel free to ask me questions or pass suggestions! And check out the GitHub repository for participation!</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>GitHub</strong>: <a href="https://github.com/shandralor/PeerBrain" target="_blank" rel="noreferrer noopener">https://github.com/shandralor/PeerBrain</a></p>
</div>


https://www.sickgaming.net/blog/2023/02/...ic-server/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016