<?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 Radwan Hijazi on Medium]]></title>
        <description><![CDATA[Stories by Radwan Hijazi on Medium]]></description>
        <link>https://medium.com/@radwanhijazi?source=rss-d019e5a7a336------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zB4g1sY02UUMWKIftII6aA.jpeg</url>
            <title>Stories by Radwan Hijazi on Medium</title>
            <link>https://medium.com/@radwanhijazi?source=rss-d019e5a7a336------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:48:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@radwanhijazi/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[Building a Back-End Framework Using Python For Fun !]]></title>
            <link>https://medium.com/@radwanhijazi/building-a-back-end-framework-using-python-for-fun-8280022f8713?source=rss-d019e5a7a336------2</link>
            <guid isPermaLink="false">https://medium.com/p/8280022f8713</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Radwan Hijazi]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 00:21:30 GMT</pubDate>
            <atom:updated>2025-07-14T00:25:39.556Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Back-End Framework Using Python For Fun !</h3><p>Any software today can’t lunch without a backend server , Nowadays there is a lot of backend technologies u can use to built your own server, But what if I told you that on this article we are not gonna to built a back-end server , We are gonna to build a very simple back-end framework from scratch ..!</p><h3>Timeline</h3><ul><li>Introduction to backend</li><li>Why I build a backend framework although there is already a lot of them exists ?</li><li>Cook the framework !</li><li>Try the framework</li><li>My Framework vs DRF</li><li>Conclusion</li></ul><h3>Introduction To Back-End</h3><p>If you open Facebook to login what you will see ? , you will see a nice user interface design and a two inputs for enter your personal data and if you enter a wrong data you can’t be able to login to your account and if you enter correct data you be able to login to your account, This logic is implemented by the “backend server” , On a brief description of backend : This is a place that communicate with the client side (web, mobile, etc..) and take the request of the client and process logic on it and depends on the logic response the server respond.</p><p>Important thing that you must know that the backend has a 2 ways to communicate with the client side :</p><ul><li>Server Side Rendering (SSR)</li><li>APIs</li></ul><p>Server Side Rendering : We but the client side on the backend server, And make the response content type ‘text/html’ and the response is like :</p><pre>HTTP/1.1 200 OK  <br>Content-Type: text/html;<br>Content-Length: 245<br><br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Home Page - SSR Example&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Welcome to My Python Framework!&lt;/h1&gt;<br>    &lt;p&gt;Current server time: 2025-07-14 15:30:00&lt;/p&gt;<br>    &lt;ul&gt;<br>        &lt;li&gt;User: John Doe&lt;/li&gt;<br>        &lt;li&gt;Status: Logged In&lt;/li&gt;<br>    &lt;/ul&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>APIs : The client-side is far a way of the server-side and the communication is done with APIs, The APIs request and response content type is ‘application/json’ and looks like :</p><pre> HTTP/1.1 200 OK  <br>Content-Type: application/json  <br>Content-Length: 89<br><br>{<br>    &quot;status&quot;: &quot;success&quot;,<br>    &quot;data&quot;: {<br>        &quot;id&quot;: 1,<br>        &quot;name&quot;: &quot;Radwan&quot;,<br>        &quot;email&quot;: &quot;radwan@example.com&quot;,<br>        &quot;is_active&quot;: true<br>    },<br>    &quot;datetime&quot;: &quot;2025-07-14&quot;<br>}</pre><h3>Why I build a backend framework although there is already a lot of them exists ?</h3><p>If you search of the backend frameworks you will see a lot of frameworks shown for you like : Django, Laravel, Dot Net , Ruby on rails and a very long list, And the good news that you can pick any one of them and create a backend server, But there is a specific fields we choose the framework depends on it, And on this article it’s not matter the framework or the field which the framework created for I will talk about the main idea of creating a backend framework to learn “How the backend frameworks running behind the scene”.</p><h3>Let’s Cook the framework !</h3><p>Before building the framework I need to cover 4 important things:</p><ul><li><strong>Networking and how computers communicate with each other : </strong>The current internet that we use today is about some computers that communicate with each other globally via networks which made the World Wide Web “WWW” that we know today, Each network send messages and the message to be sent need the sender and the receiver, Before sending the message between them we must specify which protocol we will use, The protocol is some rules that the sender and receiver agree with for successful sending messages without any failures , And the type of protocol is important here because if you send email or browsing or sending files , etc.. on all of them you gonna use custom protocol, And depends on your usage you must specify the protocol.</li><li><strong>HTTP Request-Response Life Cycle : </strong>When we browsing the internet we use protocol called HTTP and this protocol running on port 80, And the computer which run this protocol we called it “Server” and the computer which want to communicate with the server we called it “Client”, When the client do a request for the server we called it HTTP Request , and it’s look like :</li></ul><pre>GET /api/users/ HTTP/1.1<br>Host: example.com<br>Accept: application/json</pre><p>And when the server take this request make a respond with message called HTTP Response, and it’s look like :</p><pre>HTTP/1.1 200 OK<br>Content-Type: application/json<br><br>[<br>  {<br>    &quot;id&quot; : 1,<br>    &quot;name&quot; : &quot;Radwan&quot;,<br>    &quot;age&quot; : 20,<br>    &quot;role&quot; : &quot;Backend&quot;<br>  },<br>  {<br>    &quot;id&quot; : 2,<br>    &quot;name&quot; : &quot;Youssef&quot;,<br>    &quot;age&quot; : 20,<br>    &quot;role&quot; : &quot;Frontend&quot;<br>  },<br>]</pre><ul><li><strong>Threading : </strong>On a past years ago when the computers started it’s CPUs can&#39;t perform tasks in parallel, example of that if you want to open calculator and open file browser you cannot do that in parallel , After updates on the CPUs the computers could perform tasks in parallel, and each process can do multi-threading like todays browsers you can open browser (Process) and open tabs (threads) and each tab has own data, The main idea of threading is that enable the processes to perform it’s tasks in parallel and that boost the performance of the application.</li><li><strong>ORM : </strong>For dealing with databases we write a SQL query to do CRUD operations on the database, But for avoid writing SQL query we can write with the native programming language that we use and the code translated to SQL query and this is the main job of the ORM it’s mapping the programming language code to SQL query code, like :</li></ul><pre># simple orm using python<br><br>def all_users() : <br>  &quot;&quot;&quot;Return all users from the database by implement SQL command&quot;&quot;&quot;<br>  return &quot;SELECT * FROM Users;&quot;<br><br>all_users() # getting all users from the db by calling the function</pre><h3>Building The Framework</h3><p>Our framework name is “rAPI” and it’s a backend framework that helps the developers to build back-end server that enable creating REST APIs.</p><p>File Structure :</p><pre>rAPI/<br>|   __init__.py<br>|   rHTTP.py<br>|   server.py<br>|   views.py</pre><h4>rHTTP.py</h4><p>The file which we will receive the HTTP request and handle it and return the HTTP response, and the code is :</p><pre>import json<br><br>class HttpRequest:<br>    __CODES = {<br>        200 : &quot;200 OK&quot;,<br>        404 : &quot;404 Not Found&quot;,<br>        400 : &quot;400 Bad Request&quot;,<br>        500 : &quot;500 Internal Server Error&quot;<br>    }<br><br>    def __init__(self, request_bytes, views_list, host, port) -&gt; None:<br>        self.request_bytes = request_bytes<br>        self.views_list = views_list<br>        self.host = host<br>        self.port = port<br><br>        <br><br>    @property<br>    def data (self) -&gt; dict : <br>        bytes_data = self.request_bytes.split(&#39;\n\r\n&#39;)[-1]<br>        try : <br>            json_data = json.loads(bytes_data)<br>        except json.decoder.JSONDecodeError : <br>            json_data = {}<br>        return json_data<br>    <br>    @property<br>    def query (self) -&gt; dict:<br>        data = {}<br>        if hasattr(self, &#39;path_query&#39;) : <br>            for k in self.path_query.split(&quot;&amp;&quot;) : <br>                query = k.split(&#39;=&#39;)<br>                data[query[0]] = query[1]    <br>        return data<br><br>    def handle (self) : <br>        request_line = self.request_bytes.splitlines()[0]<br>        self.method, self.path, _ = request_line.split()<br><br>        if &quot;?&quot; in self.path:<br>            self.path, self.path_query  = self.path.split(&#39;?&#39;)<br><br>        get_view = None<br>        for view in self.views_list :<br>            view = view()<br>            if view.url == self.path and self.method == view.method:<br>                get_view = view<br>                break<br><br>        # Handle the request based on the path<br>        if get_view:<br>            get_view.request = self<br>            response_data, response_code = get_view.get_response()<br>            response_body = json.dumps(response_data)<br>            status_code = self.__CODES[response_code or 200]<br>        <br>        else:<br>            response_body = &quot;&quot;<br>            status_code = self.__CODES[404]<br><br>        return self.__make_response(status_code, response_body)<br>    <br>    def __make_response(self , status_code, response_body) :<br>        self.status_code = status_code <br>        # Prepare HTTP response<br>        response = f&quot;HTTP/1.1 {status_code}\r\n&quot; \<br>                f&quot;Content-Type: application/json\r\n&quot; \<br>                f&quot;Content-Length: {len(response_body)}\r\n&quot; \<br>                f&quot;\r\n&quot; \<br>                f&quot;{response_body}&quot;<br>        <br>        return response.encode(&#39;utf-8&#39;)</pre><h3>server.py</h3><p>In this file you will see the running server which is waiting for http requests and pass this request to a thread , and the code is :</p><pre>&quot;&quot;&quot;<br>    Server Side main Logic<br>&quot;&quot;&quot;<br>import socket, threading, keyboard<br>from .rHTTP import HttpRequest<br><br>class ThreadMapper:<br>    def thread_mapper(self, client_socket, addr) :<br>        with client_socket:<br>            request = client_socket.recv(1024).decode(&#39;utf-8&#39;)<br>            load_request = HttpRequest(request, self.views_list, self.host, self.port)<br>            response = load_request.handle()<br>            print(f&quot;[-] {addr[0]}:{addr[1]} {load_request.path} {load_request.method} --&gt; {load_request.status_code}&quot;)<br>            client_socket.sendall(response)<br><br><br>    def keyboard_thread(self) : <br>        keyboard.wait(&#39;ctrl+c&#39;)  # Wait for Ctrl+C to be pressed<br>        self.stop_server.set()<br>        print(&quot;Closing Server...&quot;)<br><br>class Server(ThreadMapper):<br><br>    def __init__(<br>            self, <br>            views_list,<br>            host : str = &#39;localhost&#39;, <br>            port : int = 8080, <br>        ):<br>        self.host = host<br>        self.port = port<br>        self.views_list = views_list<br>        self.__url = f&quot;http://{self.host}:{self.port}/&quot;<br>        self.stop_server = threading.Event()<br>        threading.Thread(<br>            target=self.keyboard_thread,<br>        ).start()<br><br>    def run(self) : <br>        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:<br>            server_socket.bind((self.host, self.port))<br>            server_socket.listen(5)<br>            print(f&quot;[+] Server is listening on {self.__url}&quot;)<br>            <br>            while not self.stop_server.is_set():<br>                try : <br>                    client_socket, addr = server_socket.accept()<br>                    th = threading.Thread(target=self.thread_mapper, args=(client_socket, addr,))<br>                    th.start()<br>                except KeyboardInterrupt:<br>                    print(&#39;[&gt;] Server Quit.&#39;)<br>                    break</pre><h3>views.py</h3><p>On this file you will use the abstract view that the developer will use it as a parent class to build their REST APIs and write their logic and able to auto creating the documentation for their APIs, The code is :</p><pre>&quot;&quot;&quot; <br>    Server views and rendering api.<br>&quot;&quot;&quot;<br><br>from abc import ABC, abstractmethod<br>from typing import Any<br>from .rHTTP import HttpRequest<br><br>class View (ABC) : <br>    request:HttpRequest = None<br>    request = None<br>    method:str = &quot;&quot;<br>    fields:dict[str, Any] = {}<br>    url:str = &quot;&quot;<br>    __errors:dict = {}<br><br>    @abstractmethod<br>    def get_response(self) -&gt; tuple[str, int] : ...<br><br>    def is_valid_fields (self) : <br>        self.__errors.clear()<br>        fields_keys = self.fields.keys()<br>        request_data_keys = self.request.data.keys()<br>        <br>        for field in fields_keys : <br>            if field not in request_data_keys : <br>                self.__errors[field] = &#39;field not found&#39;<br>        <br>        return not any(self.__errors)<br><br>    def errors(self) : <br>        return self.__errors<br><br>class APIDocs (View) :<br>    &quot;&quot;&quot;For auto creating docs for the current APIs&quot;&quot;&quot;<br>    method = &quot;GET&quot;<br>    url = &quot;/__docs__/&quot;<br>    views_list = []<br><br>    def get_response(self) : <br>        apis = []<br>        for view in self.views_list[:-1]: <br>            view_obj = view()<br>            apis.append({<br>                &#39;url&#39; : view_obj.url,<br>                &#39;method&#39; : view_obj.method,<br>                &#39;fields&#39; : list(view_obj.fields.keys()) if view_obj.fields else []<br>            })<br><br>        return apis, 200</pre><h3>Let’s Try The Framework</h3><p>we will gonna to creating a small project with 2 endpoints:</p><ul><li>endpoint for get data as response for JSON</li><li>endpoint for post some data</li></ul><p>the code :</p><pre># my_rapi_file.py<br><br># Import Libs<br>from rAPI.server import Server<br>from rAPI.views import View, APIDocs<br><br># Create your endpoint<br>class IndexView (View) :<br>    url = &quot;/&quot; # url of the endpoint<br>    method = &quot;GET&quot; # endpoint method<br><br>    # NOTE: important to call get_response func and must return tuple as you see.<br>    def get_response(self) -&gt; tuple[str, int]:<br>        data = {<br>            &#39;name&#39; : &#39;radwan&#39;,<br>            &#39;age&#39; : 19<br>        }<br>        return data, 200<br><br><br># Another endpoint to implement POST method with custom fields<br>class PostView(View) : <br>    url = &quot;/auth/login/&quot;<br>    method = &#39;POST&#39;<br>    fields = {<br>        &#39;username&#39; : str,<br>        &#39;password&#39; : str,<br>    }<br>  <br>    def get_response(self) -&gt; tuple[str, int]:<br>        if self.is_valid_fields() : <br>            return self.request.data, 200<br>        return self.errors() ,400<br>    <br># add your endpoints in views_list <br>views_list=[<br>    IndexView,<br>    PostView<br>]<br><br># define an api docs for automatically descripe your APIs<br>class UserDefineApiDocs(APIDocs) :<br>    url = &quot;/docs/&quot;<br>    views_list = views_list<br><br># must do that to can see the result in /docs/ endpoints<br>views_list.extend([UserDefineApiDocs])<br><br># load the view_list to the server to see it<br># you can also set host and port.<br># default host is localhost and default port is 8080<br>server = Server(<br>    views_list=views_list<br>)<br><br># run the server<br>server.run()</pre><p>Running the server :</p><pre>python my_rapi_file.py</pre><p>Now you must see the server is running at : <a href="http://localhost:8080/">http://localhost:8080/</a></p><h3>My Framework vs DRF</h3><p>When I finished from this framework I want to test the power of this server vs Django Rest Framework, I created an overload requests by a 1000 requests for each server , and the “DRF ”server handle the 1000 request by 2.01s and “rAPI ”take 1.88s , Not big difference but still there is a difference, could you answer me on the comments why my framework is faster than DRF ? (I know the answer but I want to hear yours)</p><p><a href="https://github.com/RadwanHegazy/rAPI">rAPI Code in github</a></p><h3>Conclusion</h3><p>rAPI is created for learning purposes only and I really enjoy the journey of creating it , I learnt a lot and search a lot and go deep so much which was very good to me , I do that because a wise man once told me “if u want to deep dive into a something try to built it”.</p><p>Thanks for reading , I really appreciate that and I hope that the article helps you ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8280022f8713" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My journey of creating programming language using python from scratch on 6 days.]]></title>
            <link>https://medium.com/@radwanhijazi/my-journey-of-creating-programming-language-using-python-from-scratch-on-6-days-a0398d8f6a53?source=rss-d019e5a7a336------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0398d8f6a53</guid>
            <category><![CDATA[compiler-design]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Radwan Hijazi]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 02:08:01 GMT</pubDate>
            <atom:updated>2025-07-08T02:08:01.844Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*5qP6N1fdWptwBQpnJ_W_6A.jpeg" /></figure><h3>Introduction</h3><p>Hi programmers, how are you , I hope u do well.</p><p>From the lunching of the computer world and the computer languages has been upgraded from the 0s and 1s to todays known programming languages like C, C++, C#, Python and more than 600 PLs and all of these PLs has been used on specific fields and on for a specific jobs.</p><h3>Why I want to create a programming language ?</h3><p>As a backend developer using Django I‘m writing python code for more than 5 years and I really like python because it’s easy syntax to understand and more other staff and when I grow on this field I ask myself a question “How python works ?” from this question I starts to search on google and asking AI-models and I found myself surrounded with a lot of information and I was distracted , So I decided to create a programming language from scratch to kill the distraction and really understand what is happen under the hood.</p><h3>What I gain from searching and asking AI-models ?</h3><p>All what I gain from this is the massive amount of information that made my brain burn 😂, The search operation was not easy and I found a new things and theses things has new things inside it so I must to dive into it which made me more distracted more and more …. So the solution here that I should depends on myself and building the programming language.</p><h3>What is a PL (Programming Language) ?</h3><p>In general the programming language is a middleman between you and the computer which it translate the commands that you type it into instructions that the computer understand it and perform it to u, So right now we understand a two main things of PLs which is :</p><ul><li>Commands you type</li><li>Translate these commands</li></ul><h3>Commands You Type</h3><p>On any PL on the world you found that each PL has it’s own syntax and semantics , but what is the different between them ?</p><p><strong>Syntax </strong>: Checking the correctness of the coding style</p><p><strong>Semantics</strong> : Checking the correctness of the logic.</p><p>Ex:</p><pre><br># right syntax and right semantics<br>print(1 + 1)<br><br># invalid syntax and right semantics<br>print{1 + 1}<br><br># right syntax and invalid semantics<br>print( 1 + &quot;Radwan&quot; )</pre><h3>Translate Theses Commands</h3><p>Alright, Now we have known about the syntax and semantics and already write the code, Then how could we will run this code on the machine ? the answer is on the compiler or interpreter.</p><p><strong>Compiler </strong>: Translate the whole code to a machine language.</p><p><strong>Interpreter </strong>: Translate code line-by-line to a machine language.</p><p>There is a lot of differences between the compilers and interpreters but I won’t to dive on it right now, But the main idea here that you should know that the interpreter or compiler translate the commands that the programmer type into a machine language code that the computer can understand and performing it.</p><h3>Build Requirements</h3><p>By depending on the two major things we talk about which is :</p><ul><li>Commands you type</li><li>Translate these commands</li></ul><p>You should understand that our requirements is :</p><ol><li>Create the syntax and semantics of our programming language</li><li>Create the interpreter to run the code</li></ol><h3>Lets cooking our programming language 🔥</h3><p>First of all we need to name our programming language which will be “RadwanLang” , the second things is to define the syntax and the semantic of the code :</p><pre># This is for commenting the code<br><br>Define the variables &lt;var_type&gt;: &lt;var_key&gt; = &lt;var_value&gt;<br>Avaliable Data Types :<br><br>s: -&gt; for string<br>i: -&gt; for integers<br>f: -&gt; for floats<br>b: -&gt; for booleans<br><br>Example on define a variable<br>s: name = &quot;&quot;<br>i: age = 0<br>f: salary = 0<br>b: is_student = 0<br><br>Built-in Methods @&lt;method_name&gt;<br>These is all built-in methods in the language :<br><br>@userInput: &lt;variable_name&gt;, &lt;output_text&gt;  -&gt; take input from user and save it on a variable you choose<br>@cleanScreen -&gt; clean the screen<br>@calc: &lt;variable_name&gt;, &lt;operation&gt; -&gt; for calculation<br>@write: &lt;*args&gt; -&gt; for write data on screen</pre><p>After finishing of the second level , let’s go to the last level which is the interpreting and running our code .</p><h3>RadwanLang Interpreter</h3><p>This is the most hard and complex level I faces it when I created “RadwanLang” but let’s go through it and crack it.</p><p>First of all I create 3 main Objects :</p><ol><li>Interpreter</li><li>Code Parser</li><li>Dispatcher</li></ol><p><strong>Interpreter </strong>: Read and implement the code and checking from the correctness of the file name and that should end with “.radwan”, and this is the code :</p><pre>import sys, os<br>from parser import CodeParser<br><br><br>class Interpreter :<br>    &quot;&quot;&quot;<br>    Read and implement the code<br>    &quot;&quot;&quot;<br>    def __init__(self, file_path) -&gt; None:<br>        self.file_path = file_path<br><br>        current_directory = os.path.dirname(os.path.abspath(__file__))<br>        filename = file_path<br>        file_path = os.path.join(current_directory,filename)<br><br>        if file_path.endswith(&#39;.radwan&#39;) : <br>            code = open(file_path, &#39;r&#39;)<br>            self.code_lines = code.read().split(&#39;\n&#39;)<br>        else:<br>            raise Exception(&quot;Invalid file extension name&quot;)<br>   <br>    def run (self) : <br>        &quot;&quot;&quot;<br>        Run the list of code lines<br>        &quot;&quot;&quot;<br>        CodeParser(self.code_lines)<br><br>if __name__ == &quot;__main__&quot; : <br>    file_path = sys.argv[1:]<br>    if file_path:<br>        file_path = file_path[0]<br>        interpreter = Interpreter(file_path)<br>        interpreter.run()<br>    else:    <br>        print(&#39;[!] Please Insert file path.&#39;)</pre><p><strong>Code Parser</strong>: read code line-by-line and check if the line starts with comment “#” will jump on the next line direct, Executing the current line and saving the results on memory.</p><pre>from manager import MemoryManager<br>from dispatcher import Dispatcher<br><br>class CodeParser:<br><br>    __memory_manager = MemoryManager()<br>    __line = 0<br>    <br>    def __init__(self, code_lines:list[str]) -&gt; None:<br>        <br>        for line in code_lines : <br>            self.__line += 1<br><br>            # ignore the comments lines <br>            if line.startswith(&#39;#&#39;) or len(line) == 0:<br>                continue<br>            <br>            # save the instractions to memory and implement it,<br>            # The write new output to the memory<br>            dis = Dispatcher(line, self.__memory_manager, self.__line)<br>            self.__memory_manager = dis.response()<br><br></pre><p><strong>Dispatcher </strong>: Receives the current line and check of the correctness of syntax and semantics then run the code</p><pre>from main import MainDispatcher<br>from method_manager import MethodManager<br>from variables import (<br>    BoolVar,<br>    FloatVar,<br>    IntegerVar,<br>    StringVar,<br>)<br><br>class Dispatcher (MainDispatcher):<br><br>    __REGISTERD = {<br>        &#39;s&#39; : StringVar,<br>        &#39;i&#39; : IntegerVar,<br>        &#39;f&#39; : FloatVar,<br>        &#39;b&#39; : BoolVar,<br>        &quot;@&quot; : MethodManager<br>    }<br><br>    def __init__(self, code_line : str, manager, line_number : int) -&gt; None:<br>        &quot;&quot;&quot;Check the line is variable or method, and implement the line<br><br>        Args:<br>            code_line (str): one line of code, One line only<br>            manager (_type_): the memory manager which has all variables on it<br>            line_number (int): the number of current code_line on the file<br>        &quot;&quot;&quot;<br>        key = code_line[0]<br>        is_method = key == &quot;@&quot;<br>        self.manager = manager<br>        if not is_method : <br>            assert key in self.__REGISTERD.keys(), f&quot;error on line {line_number} -&gt; {code_line}&quot;<br>            output = self.__REGISTERD[key](code_line)<br>        else:<br>            output = self.__REGISTERD[key](code_line, self.manager)<br><br>        self.__output = output<br>    <br>    def response (self) : <br>        &quot;&quot;&quot;<br>        Dispatcher response data<br>        &quot;&quot;&quot;<br>        response = self.__output.response()<br>        if response :<br>            key, val = response<br>            self.manager.set_it(key, val)<br>        return self.manager</pre><p>Okay Let’s Try RadwanLang:</p><ol><li>Code:</li></ol><pre># File name : main.radwan<br><br># Define Variables<br>s: name = &quot;&quot;<br>i: age = 0<br>f: salary = 0<br>b: is_student = 0<br><br># Ask user for data<br>@userInput: name, &quot;Enter your name &quot;<br>@userInput: age, &quot;Enter your Age &gt; &quot;<br>@userInput: salary, &quot;Enter Your salary &gt; &quot;<br>@userInput: is_student, &quot;Student ? [1/0] &gt; &quot;<br><br><br># clean the screen<br>@cleanScreen<br><br># write the output on screen<br>@write: &quot;Your name is &quot; , name<br>@write: &quot;Your Age is  &quot;, age<br>@write: &quot;Your salary is &quot;, salary<br>@write: &quot;is Student &quot;, is_student<br><br># do an calculation operation with built-in method calc<br>f: result = 0<br><br>@calc : result , 123 + 103 + (123 - 11) / 12<br><br>@write: &quot;The result of operation is : &quot; , result</pre><p>2. Running the code</p><pre>python core/interpreter.py main.radwan</pre><h3>Conclusion</h3><p>On the end all I want to say that “RadwanLang ” was created for learning purpose only and it was the answer of the question “How Python Works?”, And on real-world PLs not has the same structure of my PL because it’s more complex and complicated than you think, I just try to implement PL with my ideas and my structure and this is the result.</p><p>RadwnLang Full Code : <a href="https://github.com/RadwanHegazy/RadwanLang">Here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0398d8f6a53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How could i build my own NO-SQL db used for caching from scratch (Using Python)?]]></title>
            <link>https://medium.com/@radwanhijazi/how-could-i-build-my-own-no-sql-db-used-for-caching-from-scratch-using-python-04f05ea81b4d?source=rss-d019e5a7a336------2</link>
            <guid isPermaLink="false">https://medium.com/p/04f05ea81b4d</guid>
            <dc:creator><![CDATA[Radwan Hijazi]]></dc:creator>
            <pubDate>Thu, 08 Aug 2024 19:21:07 GMT</pubDate>
            <atom:updated>2024-08-08T19:21:07.027Z</atom:updated>
            <content:encoded><![CDATA[<p>we live in the 20th century where there is a very big and large data, and theses data need to be saved on databases, we have types of databases like: SQL databases, No-SQL databases, Graph databases, time series databases and more types of db, and each type of theses databases have a specific use.</p><h3>Why i build my db from scratch and there is a lot of dbs already exists ?</h3><p>i build this database for educational purposes and for fun, and work on make theses things makes you dive into it and know how it actually works inside.</p><h3>Our database structure</h3><pre>&quot;&quot;&quot;<br>Data Structure:<br>    {<br>        &quot;a&quot; : ValObj,<br>        &quot;b&quot; : ValObj,<br>        &quot;c&quot; : ValObj,<br>        ...<br>        &quot;A&quot; : ValObj,<br>        &quot;B&quot; : ValObj,<br>        &quot;C&quot; : ValObj,<br>        ...<br>    }<br><br>    ValObj [linked list] : <br>        - next [ValObject]<br>        - key [str]<br>        - value [Any]<br>        - exp [timestamps]<br><br>&quot;&quot;&quot;</pre><p>You can see here that we have a Hash Table (dict) and inside this hash table we have an ValObj which will be the linked list data structure.</p><p>Inside the Hash Table we have the keys and all keys is Alphatical and each key got a ValObj and this key we will name it “router”, I do that to classify the data in each key, because if you save a cache data with key “name1” and another data with key “name2” we will save it on the objects with key “n”, we will know why i do that.</p><p>of curse u see the object which called ValObj and you want to know what this object is for ? this object is our linked list model we will use it to save four things :</p><ul><li>key : which is the cache key we will use it for read, write and delete the data inside our db</li><li>value : the saved value which will be any datatype</li><li>exp : it the time that data will expired</li><li>next : the pointer of the next ValObj if there is next or it will be none</li></ul><p>This is the basic and easy structure of our database and now let’s talk about the main point in our database which is where is this data will be saved ?</p><p>this is a database used for caching and it must be fast so the best place to save this data is in the RAM by default we will save this data on RAM but we will have some problems that will face us like the data of our cache will save until you run the app and if u close the app will deleted with the cached data from the RAM, and for saving the data from lose we will read/delete every new cache data added or deleted in a disk, we will save the data in a binary file to read them fast when we restart or close our app.</p><p>So we now know what is the structure of our database and where is the place which we will save the cached data on it.</p><h3>Why i use linked list data structure not an array ?</h3><p>that is because how is the mechanism of the array works, if we have a 10 items in the array the array will search on the whole memory to find a 10 places for the 10 items on the array and if we need to add more one item on the array the array will take the 10 items and the inserted item and going to search on the whole memory for an existing places for the 11 items, this is so bad in memory and performance , and as i say that i save data on memory so i want to take the best performance to make the db work as well as it can, so the solution of this problem is the linked list, the linked lists is an objects linked to gather and each object has its place in memory without moving, just the object keep saved on the memory doesn’t go any where until we deleted it, and on inserting new element on the linked lists the get the last element and make the next is to the inserted object.</p><h3>Let’s Start Coding the database🔥</h3><p>every line or method of the code i write the documentation for it in a comment.</p><pre><br>from datetime import timedelta, datetime<br>from string import ascii_lowercase, ascii_uppercase<br>import pickle<br><br>&quot;&quot;&quot;<br>pickle :<br>  - to write/read data from the binary file<br><br>timedelta, datetime:<br>  - to set the expiration as timestamps and compare it to current time.<br><br>ascii_lowercase, ascii_uppercase:<br>  - to set all the keys to alphatical order and setting the value to None<br><br>&quot;&quot;&quot;<br><br>class ValObj:<br>    &quot;&quot;&quot;<br>        ValObject Where the data is stored with its key and val.<br>        Attrs : <br>            - key [ data key name]<br>            - val [data value , any type of data]<br>            - exp [the time of expiration from the db]<br>            <br>    &quot;&quot;&quot;<br><br>    next = None # our pointer<br><br>    def __init__(self, key, val, exp) -&gt; None:<br>        self.key = key<br>        self.val = val<br>        self.exp = (datetime.now() + timedelta(seconds=exp or  60 * 60)).timestamp()<br><br>    def __repr__(self) -&gt; str:<br>        return f&quot;ValObj(key={self.key}, val={self.val}, epx_mins={self.exp})&quot;<br><br># Main Cache Model<br>class cache :<br><br>    def __init__(self) : <br>        &quot;&quot;&quot;<br>            We need to read a binary file which is called temp.bin <br>            which we will save the data on it to save the data from lose.<br>            if we not found this binary file that mean that we didn&#39;t use <br>            write any data on the file yet, so we will create our Hash Table<br>            and inside each key on it we will set None<br>        &quot;&quot;&quot;<br>        try :<br>            with open(&#39;temp.bin&#39;,&#39;rb&#39;) as binary_file :<br>                self.__db_core = pickle.load(binary_file)<br>                binary_file.close()<br>        except FileNotFoundError:<br>            self.__db_core = {<br>                i : None<br>                for i in [j for j in ascii_lowercase+ascii_uppercase]<br>            }<br><br>    def __update_binary (self):<br>        &quot;&quot;&quot;<br>            For any inserting new data we need our binary file to<br>            be updated<br>        &quot;&quot;&quot;<br>        with open (&#39;temp.bin&#39;, &#39;wb&#39;) as binary_file :<br>            pickle.dump(self.__db_core, binary_file)<br>            binary_file.close()  <br>    <br>    def set (self, key, val,exp=None):<br>        &quot;&quot;&quot;<br>            set is a method to save element on cache.<br>            <br>            we detect the router which the key in the hash table <br>            to know where we will save the data<br>            and the router is the first char in the key,<br>            first of all we detect the value of this router if none <br>            that this value with this key is the first one so we will create our object<br>            and pass the data on it.<br><br>            if not none, that mean there is an object already exists on it and we need <br>            to create that object and add it on the tail of the linked list which we <br>            build.<br><br>                Attrs :<br>                    - key [String Value]<br>                    - val [any type of data ]<br>                    - exp [the total seconds to expire from db] <br>        &quot;&quot;&quot;<br>        router = str(key)[0]<br>        if self.__db_core[router] is None :<br>            self.__db_core[router] = ValObj(<br>                key=key,<br>                val=val,<br>                exp=exp<br>            )<br>        else:<br>            val_obj:ValObj = self.__db_core[router]<br>            while val_obj : <br>                if val_obj.next == None:<br>                    val_obj.next = ValObj(<br>                        key=key,<br>                        val=val,<br>                        exp=exp<br>                    )<br>                    break<br>                val_obj = val_obj.next<br>        self.__update_binary()<br><br>    def __view(self, obj:ValObj) : <br>        &quot;&quot;&quot;<br>            for check in the current ValObject, if its time expired<br>            we will delete it<br>        &quot;&quot;&quot;<br>        current_time = datetime.now().timestamp()<br>        if current_time &gt; obj.exp:<br>            self.delete(obj.key)<br>            return None<br>        return obj.val<br>    <br>    def get(self, key) : <br>        &quot;&quot;&quot;<br>            Get Element from cache<br>        &quot;&quot;&quot;<br>        router = str(key)[0]<br>        obj_val = self.__db_core[router]<br>        while obj_val:<br>            if obj_val.key == key: <br>                return self.__view(obj_val)<br>            obj_val = obj_val.next<br><br>    def delete (self, key) :<br>        &quot;&quot;&quot;<br>            Delete element from cache and update the binary file<br>        &quot;&quot;&quot;<br>        router = str(key)[0]<br>        obj_val:ValObj = self.__db_core[router]<br>        prevoius = None<br>        while obj_val:<br><br>            if obj_val.key == key: <br>                if prevoius:<br>                    prevoius.next = obj_val.next<br>                else:<br>                    self.__db_core[router] = obj_val.next<br>                self.__update_binary()<br>                break<br><br>            prevoius = obj_val<br>            obj_val = obj_val.next<br><br>cache = cache() # init the cache model to build and make our hash table ready to use</pre><h3>I hope you learn a new thing today and find it fun to write your first NO-SQL db, you can improve the db and made it better and more efficient .</h3><p>You can find the whole code <a href="https://github.com/RadwanHegazy/rdb/">here</a> you can write the changes and make it better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04f05ea81b4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Threading Vs Celery in Django]]></title>
            <link>https://medium.com/@radwanhijazi/threading-vs-celery-in-django-56ae4f86438e?source=rss-d019e5a7a336------2</link>
            <guid isPermaLink="false">https://medium.com/p/56ae4f86438e</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[celery-django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[threading]]></category>
            <dc:creator><![CDATA[Radwan Hijazi]]></dc:creator>
            <pubDate>Mon, 25 Mar 2024 22:56:28 GMT</pubDate>
            <atom:updated>2024-03-25T22:56:28.051Z</atom:updated>
            <content:encoded><![CDATA[<p>In our Django projects we have a very large and big tasks to implement, this tasks takes a lot of time, And this is very bad for the project performance .</p><p>So the key to solve this performance issues is on <strong>background tasks.</strong></p><p>in this article we will talk about threading and celery as a background tasks in Django, the pros and cons of each library and when we use celery or threading.</p><h3>The main task</h3><p>if you have an endpoint like “<strong>api/user/send-mail/&lt;int:user_id&gt;/</strong>” this endpoint takes the user id and get the email of this user and takes one parameter in the body which is the <strong>message_content , </strong>Then Send the email with this message_content to this user, these process takes a lot of time and we want to implement the task in background</p><p>Example of the code :</p><pre>#myapp/mailer.py<br><br>#import libs<br>from django.conf import settings<br>from django.core.mail import send_mail<br><br>def send_email_by_threading(to_user_email,msg_content) :<br>  # subject of the email msg<br>  subject = &quot;New message from admin&quot;<br>  # the admin email [sender]<br>  from_email = settings.EMAIL_HOST_USER<br>  # this email must goes to [receiver]<br>  recipient_list = [to_user_email]<br>  # send_mail method to implement the logic<br>  send_mail(subject, msg_content, from_email, recipient_list)</pre><h3>Let’s implement this task with threading and celery .</h3><h3>Threading in Django</h3><p>threading is a built-in library in python and you don’t need to install it , and work in threading in Django is so easily as you imagine .</p><p>Example of send the email with threading :</p><pre># myapp/views.py<br>from rest_framework import decorators, permissions<br># import threading<br>import threading<br>from django.contrib.auth.models import User<br>from rest_framework.response import Response<br>from .mailer import send_email_by_threading<br><br>@decorators.api_view([&quot;POST&quot;])<br>@decorators.permissions_classes([permissions.IsAdminUser])<br>def SendMailView (request,user_id) : <br>  try : <br>    # catch the email message from client<br>    msg_content = request.data.get(&quot;message_content&quot;,None)<br>    <br>    # check the message is inserted by the client<br>    if msg_content is None :<br>      return Response({&quot;message&quot;:&quot;please insert the message&quot;},status=400)<br>    <br>    # check if there user in the db has this id or not<br>    try : <br>      to_user = User.objects.get(id=user_id)<br>    except User.DoesNotExist:<br>      return Respose({&quot;message&quot;:&quot;user with this id not found&quot;},stauts=404)<br>      <br>    # send the email by threading <br>    to_user_email = to_user.email<br>    thread = threading.Thread(target=send_email_by_threading,args=(to_user_email,msg_content,))<br>    thread.start()<br>    <br>    return Respose({&quot;message&quot;:&quot;email sent successfully&quot;},status=200)<br><br>  except Exception as error : <br>    return Response({<br>  &quot;message&quot; : f&quot;an error accoured : {error}&quot;<br>},status=500)</pre><blockquote>NOTE : You can implement this logic in custom serializer but for save time i implement the logic in the views</blockquote><p>Now u implement the task successfully using threading✅️</p><p>but here we have a problem , if we call the endpoint two or three times there is threads not working and has been killed by the operating system.</p><p>but why and how to solve it !</p><p>i will tell you why after implement the task with celery</p><h3>Celery in Django</h3><p>Celery do exactly what threading do but in a different pattern ,celery run tasks faraway from the server and takes the tasks you want to implement and add it in a <strong>Queue</strong></p><blockquote>Queue Fast Explanation:</blockquote><blockquote>i want you to imagine there is a list, and in this list the tasks that user do in the server , and this tasks is ordered by it’s time the latest first and oldest after latest.</blockquote><p>Then the tasks in this queue implemented depends on your workers in your machine.</p><p>After created our task we need to add the celery in Django to be able to run the tasks in the background using celery.</p><h4>configure celery in Django</h4><p>install celery</p><pre>pip install celery</pre><blockquote>Celery 5.3.x supports Django 2.2 LTS or newer versions. Please use Celery 5.2.x for versions older than Django 2.2 or Celery 4.4.x if your Django version is older than 1.11</blockquote><p>follow these steps for right configuration</p><pre># myproject/celery.py<br>import os<br>from celery import Celery<br><br># Set the default Django settings module for the &#39;celery&#39; program.<br>os.environ.setdefault(&#39;DJANGO_SETTINGS_MODULE&#39;, &#39;myproject.settings&#39;)<br><br>app = Celery(&#39;myproject&#39;)<br><br># Using a string here means the worker doesn&#39;t have to serialize<br># the configuration object to child processes.<br># - namespace=&#39;CELERY&#39; means all celery-related configuration keys<br>#   should have a `CELERY_` prefix.<br>app.config_from_object(&#39;django.conf:settings&#39;, namespace=&#39;CELERY&#39;)<br><br># Load task modules from all registered Django apps.<br>app.autodiscover_tasks()<br><br><br>@app.task(bind=True, ignore_result=True)<br>def debug_task(self):<br>    print(f&#39;Request: {self.request!r}&#39;)</pre><p>then we need to import the celery app in <strong>myproject/__init__.py </strong>file</p><pre># This will make sure the app is always imported when<br># Django starts so that shared_task will use this app.<br>from .celery import app as celery_app<br><br>__all__ = (&#39;celery_app&#39;,)</pre><p>final step is to add some options in settings.py file</p><pre>CELERY_BROKER_URL = &quot;redis://localhost:6379/&quot; # you must have redis in your device<br>CELERY_ACCEPT_CONTENT = [&quot;application/json&quot;]<br>CELERY_TASK_SERIALIZER = &quot;json&quot;<br>CELERY_TIMEZONE = &quot;Africa/Cairo&quot;</pre><p>Finally celery configured successfully but still not working 😆.</p><p>we configure the celery successfully but we didn’t create the functions that must perform the background task , and for doing that we go throw the app Dir and create a file called it myapp/tasks.py and write on it :</p><pre># myapp/tasks.py<br>from celery import shared_task<br>from django.conf import settings<br>from django.core.mail import send_mail<br><br>@shared_task<br>def send_email_by_celery(to_user_email,msg_content) :<br>  # subject of the email msg<br>  subject = &quot;New message from admin&quot;<br>  # the admin email [sender]<br>  from_email = settings.EMAIL_HOST_USER<br>  # this email must goes to [reciver]<br>  recipient_list = [to_user_email]<br>  # send_mail method to implement the logic<br>  send_mail(subject, msg_content, from_email, recipient_list)</pre><p>the task is created successfully but we must run the celery server to implement the tasks , just you need to type this command in the same project directory :</p><pre>celery -A your_project_name worker --loglevel=info --pool=solo</pre><p>Then let’s write the logic in the views.py file</p><pre># myapp/views.py<br>from rest_framework import decorators, permissions<br><br>from django.contrib.auth.models import User<br>from rest_framework.response import Response<br># import our celery method which we created in tasks.py file<br>from .tasks import send_email_by_celery<br><br>@decorators.api_view([&quot;POST&quot;])<br>@decorators.permissions_classes([permissions.IsAdminUser])<br>def SendMailView (request,user_id) : <br>  try : <br>    # catch the email message from client<br>    msg_content = request.data.get(&quot;message_content&quot;,None)<br>    <br>    # check the message is inserted by the client<br>    if msg_content is None :<br>      return Response({&quot;message&quot;:&quot;please insert the message&quot;},status=400)<br>    <br>    # check if there user in the db has this id or not<br>    try : <br>      to_user = User.objects.get(id=user_id)<br>    except User.DoesNotExist:<br>      return Respose({&quot;message&quot;:&quot;user with this id not found&quot;},stauts=404)<br>      <br>    # send the email by celery<br>    to_user_email = to_user.email<br>    send_email_by_celery.delay(to_user_email,msg_content)<br>    <br>    return Respose({&quot;message&quot;:&quot;email sent successfully&quot;},status=200)<br><br>  except Exception as error : <br>    return Response({<br>  &quot;message&quot; : f&quot;an error accoured : {error}&quot;<br>},status=500)</pre><h4>we successfully done the task ✅</h4><p>You Can now decide the pros and cons of each background task performer , you see that how we use threading and how its configuration is more easy than celery and we also see the threading maybe kill the process because threading didn’t manage the tasks like celery .</p><h4>when i use threading ?</h4><p>you can use it for create a simple background tasks not heavy tasks, but you can not deploy the project with threading because it maybe cause some issues in the future .</p><h4>when i use celery ?</h4><p>if you work in a big systems like CMS , E-commerce , etc.., the perfect choice for background tasks is celery , maybe the configuration is so complex than threading but your project will become more and more powerful in the future and didn’t cause any problem in the background tasks side.</p><h3>Conclusion</h3><p>the main thing that make your projects good, fast and efficient not the programming language or the framework , it depends on you and how you will create the project and what tools you will use and how you will use theses tools.</p><p>Follow me in <a href="https://github.com/RadwanHegazy">Github</a> or <a href="https://www.linkedin.com/in/radwan-gaber-2366b6219/">Linkedin </a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56ae4f86438e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>