<?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 Charles Effiong on Medium]]></title>
        <description><![CDATA[Stories by Charles Effiong on Medium]]></description>
        <link>https://medium.com/@ceffiong?source=rss-aaf7407e4abd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*C5Y00xUrlUBJcWR9PqlX3w.jpeg</url>
            <title>Stories by Charles Effiong on Medium</title>
            <link>https://medium.com/@ceffiong?source=rss-aaf7407e4abd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:16:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ceffiong/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[Expo React-native Email with Attachment]]></title>
            <link>https://levelup.gitconnected.com/expo-react-native-email-with-attachment-d6a677b6d864?source=rss-aaf7407e4abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6a677b6d864</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[expo]]></category>
            <dc:creator><![CDATA[Charles Effiong]]></dc:creator>
            <pubDate>Mon, 14 Feb 2022 17:37:24 GMT</pubDate>
            <atom:updated>2022-02-18T12:45:48.962Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to send emails using device OS UI in Expo React-Native</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HdHFsUEQFB6FdlasJxJaSA.png" /></figure><p>Hi guys, welcome to another React tutorial where I’m going to show you how to send emails using the OS (Android or IOS) UI in Expo React-native. In addition, this tutorial covers how to include attachments in the email. This tutorial assumes some basic React/React-native know-how. However, it&#39;s simple enough for a complete beginner, so hang in there.</p><h3>What we&#39;ll be building</h3><p>The app will allow users to send emails with/without an attachments. This does a lot of heavy lifting, as you do not require a backend or some paid email APIs in order to implement sending emails with pre-filled fIelds. You can use this approach to enable users report in-app bug in your mobile app. The animation below shows the running application. Let’s look at the source codes in the next section. You can find the <a href="https://github.com/effiongcharles/expo_react_native_email">complete source code on my Github</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*oa4fExzjy4vAfes0dolvVA.gif" /></figure><h3>Setup expo react native</h3><p>This project uses <a href="https://docs.expo.dev/">Expo</a> for development. What is Expo you might ask? The following quote is taking from the official <a href="https://docs.expo.dev/">expo documentation</a>:</p><blockquote>Expo is a framework and a platform for universal React applications. It is a set of tools and services built around React Native and native platforms that help you develop, build, deploy, and quickly iterate on iOS, Android, and web apps from the same JavaScript/TypeScript codebase.</blockquote><p>Expo makes developing, testing, and deploying React-native application a breeze. You’ll have a higher appreciation for Expo if you have tried developing mobile app using <em>bare React-native</em> —you won’t like it! It’s simply a great tool for developing Android/IOS apps using React-native.</p><pre># Install the expo command line tools<br>npm install --global expo-cli</pre><pre># Create a new project<br>expo init email-app</pre><p>The above code snippet is all you need to setup and get started with developing React-native app using Expo. The second command creates a new app called <em>email-app</em>. You need to first have <a href="https://nodejs.org/en/download/">node</a> if you haven’t.</p><p>We&#39;ll need two expo-packages: one for <a href="https://docs.expo.dev/versions/latest/sdk/mail-composer/">sending email</a> using the OS UI and the second for <a href="https://docs.expo.dev/versions/latest/sdk/imagepicker/">selecting images</a> for attachment.</p><pre># Install mail package<br>expo install expo-mail-composer</pre><pre># Install image picker package<br>expo install expo-image-picker</pre><p>The code snippets above installs the neccessary packages. Let&#39;s start using the packages.</p><h3>Send email user interface</h3><p>We only need a button to trigger the event that launches the OS UI (as seen in the animation). The following code in the <em>App component</em> (App.js source) takes care of that.</p><pre>import * as ImagePicker from &#39;expo-image-picker&#39;;<br>import * as MailComposer from &#39;expo-mail-composer&#39;;</pre><pre>export default function App() {<br>  const [status, setStatus] = useState(null)</pre><pre>  return (<br>    &lt;View style={styles.container}&gt;<br>      &lt;TouchableOpacity onPress={showAlert}&gt;<br>        &lt;Text&gt;Send email&lt;/Text&gt;<br>      &lt;/TouchableOpacity&gt;<br>      {status !== null &amp;&amp;<br>        &lt;View&gt;<br>          &lt;Text&gt;{status}&lt;/Text&gt;<br>        &lt;/View&gt;<br>       }<br>    &lt;/View&gt;<br>  );<br>}</pre><p>I have abstracted away some import statements and UI styling in order to keep things simple. You can find the complete <a href="https://github.com/effiongcharles/expo_react_native_email">source codes on Github</a> as stated earlier. The output of the code (assuming all other imports and styling are included) is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*Wd70tXRU3UL5TxnUl8nNLQ.png" /><figcaption><strong>Left</strong>: Base UI. <strong>Right</strong>: Alert prompt when the send email button is clicked.</figcaption></figure><p>The UI code snippet is pretty self explanatory. We are calling the <strong><em>showAlert</em></strong> function when the button is pressed. The code snippet for the function is given below:</p><pre>const showAlert = () =&gt;<br>  Alert.alert(<br>    &quot;Add a file&quot;,<br>    &quot;Do you want to attach a file?&quot;, [<br>      {<br>        text: &quot;No&quot;,<br>        onPress: () =&gt; {sendEmail([])},<br>        style: &quot;cancel&quot;<br>      },<br>      { text: &quot;Yes&quot;, onPress: sendEmailWithAttachment }<br>    ]<br>  );</pre><h3>Send email without an attachment</h3><p>If the user chooses not to attach a file i.e. the <strong><em>No</em></strong> button on the Alert is pressed, the <strong><em>sendEmail</em></strong> function is called. Let’s see the function implementation.</p><pre>const sendEmail = async(file) =&gt; {<br>  var options = {}<br>  if(file.length &lt; 1){<br>    options = {<br>      subject: &quot;Sending email with attachment&quot;,<br>      recipients: [&quot;talkwithcharles@gmail.com&quot;],<br>      body: &quot;Enter email body here...&quot;<br>    }<br>  }else{<br>    options = {<br>    subject: &quot;Sending email with attachment&quot;,<br>    recipients: [&quot;talkwithcharles@gmail.com&quot;],<br>    body: &quot;Enter email body here...&quot;,<br>    attachments: file<br>  }</pre><pre>  let promise = new Promise((resolve, reject) =&gt; {<br>    MailComposer.composeAsync(options)<br>      .then((result) =&gt; {<br>        resolve(result)<br>      })<br>      .catch((error) =&gt; {<br>        reject(error)<br>      })<br>    })<br>  promise.then(<br>    result =&gt; setStatus(&quot;Status: email &quot; + result.status),<br>    error =&gt; setStatus(&quot;Status: email &quot; + error.status)<br>   )<br>}</pre><p>The code snippet above shows the function implementation. First we check if a file is included the function call. Remember the <em>MailComposer object</em> that was imported earlier? This object has a function i.e. <strong><em>composeAsync</em></strong> that allows us to compose a message with options such as message subject, body, recipient and attachments. The function returns a result or error with a status when it is done executing. For example, if the message was successfully sent, it returns a <em>status sent object. </em>The UI is updated with the mail status in order to keep the user informed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*RA3AI4P5VT2AupYqojzEMQ.png" /><figcaption><strong>Left</strong>: Sending message without attachment with IOS UI. <strong>Middle</strong>: App UI updated with status. <strong>Right</strong>: Phone email client showing that the email is indeed received.</figcaption></figure><p>Now for the fun path. What happens when a user selects the <strong><em>Yes</em></strong> button on the <em>Alert</em> prompt? In this case, we want the user to be able to select a file to be attached to the email. Let&#39;s discuss this next.</p><h3>Send email with an attachment</h3><p>When the Yes button on the Alert prompt is pressed, the <strong><em>sendEmailWithAttachment</em></strong> function is called. Let&#39;s take a look at the function implementation.</p><pre>const sendEmailWithAttachment = async() =&gt; {<br>  //get the image to attach.<br>  let result = await ImagePicker.launchImageLibraryAsync({<br>    mediaTypes: ImagePicker.MediaTypeOptions.All,<br>    allowsEditing: false,<br>    aspect: [4, 3],<br>    quality: 1,<br>  });</pre><pre>  if (!result.cancelled) {<br>    sendEmail([result.uri]); // file path<br>  }else{<br>    sendEmail([])<br>  }<br>}</pre><p>The function uses the <em>ImagePicker</em> object to select an image to attach to the email. The object calls the <em>launchImageLibraryAsync</em> function. This function launches the phone’s image gallery. Next we check the returned object. If the process was cancelled i.e. no file was selected. We can still send an email by calling the <strong><em>sendEmail</em></strong> function with an empty array (meaning no attachment.) On the other hand, if a user indeed select a file, we get the <em>file path</em> from the result i.e. <strong><em>result.uri</em></strong> and pass that to the <strong><em>sendEmail </em></strong>function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*2RzgZhrJ9JVHKPBZxJpgSg.png" /><figcaption><strong>Left</strong>: Phone image gallery is opened. <strong>Middle</strong>: Selected image is included in the email UI. <strong>Right</strong>: Email is received.</figcaption></figure><p>The selected image is included in the email body as shown in the image above.</p><h3><strong>Summary</strong></h3><p>You have learned how to send emails using the device OS UI in Expo React-native. We have also covered file attachments with the help of the <em>Image picker library</em>. One limitation of the <em>image picker library</em> is that it only allows for selecting a single image. This project can be extended to include multiple files selection if your use case requires it or for the fun of learning by doing. You can use the <a href="https://github.com/MonstroDev/expo-image-picker-multiple#readme">expo-image-picker-multiple</a> for this purpose — yes, give it a shot.</p><p>I hope you’ve learned something in this tutorial.</p><p>Feel free to <a href="https://github.com/effiongcharles/expo_react_native_email">download/clone the project source code on Github</a>.</p><p>Check out my other <a href="https://ceffiong.medium.com/">React/React-Native tutorials.</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6a677b6d864" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/expo-react-native-email-with-attachment-d6a677b6d864">Expo React-native Email with Attachment</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-stack Web App with Python, React and Bootstrap — Backend]]></title>
            <link>https://levelup.gitconnected.com/full-stack-web-app-with-python-react-and-bootstrap-backend-8592baa6e4eb?source=rss-aaf7407e4abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8592baa6e4eb</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Charles Effiong]]></dc:creator>
            <pubDate>Fri, 25 Jun 2021 14:00:21 GMT</pubDate>
            <atom:updated>2021-07-23T18:16:37.607Z</atom:updated>
            <content:encoded><![CDATA[<h3>Full-stack Web App with Python, React and Bootstrap — Backend</h3><h4>Create a RESTful API backend with Python Flask and SQLite</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jsi4bR2aWTGlIEm4AeP3Tw.png" /></figure><p>Hi guys, welcome to another awesome web tutorial. I&#39;m going to show you how to build a full-stack web app using Python flask/SQLite for backend and Reactjs/bootstrap for the frontend. We are going to cover the backend implementation in this tutorial and the frontend in the next. This is going to be so much fun as this will equip you with the general principles and practices for building cool full-stack web apps.</p><h3>What we will be building</h3><p>We will learn the architecture of a backend full-stack web app by implementing a simple user management API. The video below shows the finished backend app. The app provides functionalities to manage user data — Create, Read, Update and Delete data. The concepts and principles that will be covered can be applied to create other more complex web-apps and also to other web-technologies. So, let&#39;s get started with the Backend RESTful API with Python flask/SQLite.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2LiQJG02Fhs&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2LiQJG02Fhs&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/167dac412f5bba7e0475392515701919/href">https://medium.com/media/167dac412f5bba7e0475392515701919/href</a></iframe><h3>RESTful API</h3><p>REST API (or RESTful API), stands for <strong>R</strong>epresentational <strong>S</strong>tate <strong>T</strong>ransfer — <strong>A</strong>pplication <strong>P</strong>rogramming <strong>I</strong>nterface, allows apps to interact with resources via HTTP protocols. Such interactions are normally CRUD operations which implements specific business logics. So, an app running on either web, desktop or mobile requests a resource via HTTP methods and the response is returned normally in JSON format for interoperability. In our use case, our business logic include adding user to our database — Create operation, getting list of users or a single user — Read operation, Updating users — Update operation and deleting users — Delete operation. All these will be done via HTTP requests.</p><p>Let&#39;s define our REST API endpoints:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*rwdW7bsYv3vB9hYXk_PJAg.png" /><figcaption>User management API endpoints</figcaption></figure><p>The table above shows the API endpoints for the User management app. The endpoints are pretty straightforward to understand and they perform database CRUD operations.</p><h3>Backend implementation</h3><p>As stated earlier, we&#39;ll use Python Flask and SQLite for our backend. This tutorial uses Python 3. 9 and luckily ships in with SQLite so we do not need to worry about a separate database server. This tutorial assumes some familiarity with Python and basic SQL queries. However, don&#39;t worry if you are not yet familiar with SQL queries as you&#39;ll still be able to follow along. To get started, ensure you already have Python installed — preferably Python 3.*. You can also use any IDE of your choice — I&#39;m using the popular PyCharm. The complete <a href="https://github.com/effiongcharles/full_stack_web_python_flask_react_bootstrap">project source codes is available on my github page.</a></p><p>In order to use Python Flask, we need to first install the package. You can do that using the command below in your terminal. SQLite3 is already included when Python was installed i.e. in standard library.</p><pre># install flask package<br>pip install Flask</pre><pre># Only if you don&#39;t have sqlite installed<br>pip install db-sqlite3</pre><h3>Database Implementation</h3><p>Now that we have the basic setups out of the way, let&#39;s take a look at the source codes. First, we&#39;ll focus on database implementation , then we&#39;ll focus on the REST API implementation. Basically, we need to create our database and table. Then, write functions for each of our business logic.</p><pre>#!/usr/bin/python<br>import sqlite3<br><br>def connect_to_db():<br>    conn = sqlite3.connect(&#39;database.db&#39;)<br>    return conn<br><br>def create_db_table():<br>    try:<br>        conn = connect_to_db()<br>        conn.execute(&#39;&#39;&#39;<br>            CREATE TABLE users (<br>                user_id INTEGER PRIMARY KEY NOT NULL,<br>                name TEXT NOT NULL,<br>                email TEXT NOT NULL,<br>                phone TEXT NOT NULL,<br>                address TEXT NOT NULL,<br>                country TEXT NOT NULL<br>            );<br>        &#39;&#39;&#39;)<br><br>        conn.commit()<br>        print(&quot;User table created successfully&quot;)<br>    except:<br>        print(&quot;User table creation failed - Maybe table&quot;)<br>    finally:<br>        conn.close()</pre><p>The code snippet above implements the User database. The implementation is pretty straightforward. First we define a function that connects to db i.e. <em>connect_to_db</em>. This function creates the database if it doesn&#39;t exist and returns a connection object. This object will be required to perform other database operations — CRUD. The <em>create_db_table</em> function connects to the database and creates table. The user table contains several fields including user_id (a unique identifier), name and email. The &quot;changes&quot; to the db is saved when the <em>commit</em> function is executed. Next, let&#39;s see the implementations of our business logics.</p><pre>def insert_user(user):<br>    inserted_user = {}<br>    try:<br>        conn = connect_to_db()<br>        cur = conn.cursor()<br>        cur.execute(&quot;INSERT INTO users (name, email, phone, address,       <br>                    country) VALUES (?, ?, ?, ?, ?)&quot;, (user[&#39;name&#39;],   <br>                    user[&#39;email&#39;], user[&#39;phone&#39;], user[&#39;address&#39;],   <br>                    user[&#39;country&#39;]) )<br>        conn.commit()<br>        inserted_user = get_user_by_id(cur.lastrowid)<br>    except:<br>        conn().rollback()<br><br>    finally:<br>        conn.close()<br><br>    return inserted_user</pre><p>The code snippet above defines a function that adds a new user into the database table. The function takes a user object as an argument. The user object is simply a python dictionary as shown in the code snippet below.</p><pre>user = {<br>    &quot;name&quot;: &quot;John Doe&quot;,<br>    &quot;email&quot;: &quot;jondoe@gamil.com&quot;,<br>    &quot;phone&quot;: &quot;067765434567&quot;,<br>    &quot;address&quot;: &quot;John Doe Street, Innsbruck&quot;,<br>    &quot;country&quot;: &quot;Austria&quot;<br>}</pre><p>Notice that the <em>user_id</em> is not inserted. This is because it&#39;s automatically generated. A <em>cursor</em> object is normally use to execute CRUD operations as it facilities traversal/processing over database records. In addition, we return the just inserted user by calling another function that returns a user given the user_id. We&#39;ll see this function implementation next.</p><pre>def get_users():<br>    users = []<br>    try:<br>        conn = connect_to_db()<br>        conn.row_factory = sqlite3.Row<br>        cur = conn.cursor()<br>        cur.execute(&quot;SELECT * FROM users&quot;)<br>        rows = cur.fetchall()<br><br>        # convert row objects to dictionary<br>        for i in rows:<br>            user = {}<br>            user[&quot;user_id&quot;] = i[&quot;user_id&quot;]<br>            user[&quot;name&quot;] = i[&quot;name&quot;]<br>            user[&quot;email&quot;] = i[&quot;email&quot;]<br>            user[&quot;phone&quot;] = i[&quot;phone&quot;]<br>            user[&quot;address&quot;] = i[&quot;address&quot;]<br>            user[&quot;country&quot;] = i[&quot;country&quot;]<br>            users.append(user)<br><br>    except:<br>        users = []<br><br>    return users<br><br><br>def get_user_by_id(user_id):<br>    user = {}<br>    try:<br>        conn = connect_to_db()<br>        conn.row_factory = sqlite3.Row<br>        cur = conn.cursor()<br>        cur.execute(&quot;SELECT * FROM users WHERE user_id = ?&quot;, <br>                       (user_id,))<br>        row = cur.fetchone()<br><br>        # convert row object to dictionary<br>        user[&quot;user_id&quot;] = row[&quot;user_id&quot;]<br>        user[&quot;name&quot;] = row[&quot;name&quot;]<br>        user[&quot;email&quot;] = row[&quot;email&quot;]<br>        user[&quot;phone&quot;] = row[&quot;phone&quot;]<br>        user[&quot;address&quot;] = row[&quot;address&quot;]<br>        user[&quot;country&quot;] = row[&quot;country&quot;]<br>    except:<br>        user = {}<br><br>    return user</pre><p>The code snippet above implements the feature to retrieve user(s) from the database. The <em>get_user</em> function returns the list of all users from the database, while the <em>get_user_by_id</em> takes in a <em>user_id</em> as an argument and returns the user record matching the <em>user_id</em>. Let&#39;s see how to update a user next.</p><pre>def update_user(user):<br>    updated_user = {}<br>    try:<br>        conn = connect_to_db()<br>        cur = conn.cursor()<br>        cur.execute(&quot;UPDATE users SET name = ?, email = ?, phone = <br>                     ?, address = ?, country = ? WHERE user_id =?&quot;,  <br>                     (user[&quot;name&quot;], user[&quot;email&quot;], user[&quot;phone&quot;], <br>                     user[&quot;address&quot;], user[&quot;country&quot;], <br>                     user[&quot;user_id&quot;],))<br>        conn.commit()<br>        #return the user<br>        updated_user = get_user_by_id(user[&quot;user_id&quot;])<br><br>    except:<br>        conn.rollback()<br>        updated_user = {}<br>    finally:<br>        conn.close()<br><br>    return updated_user</pre><p>The code snippet implements the feature to update user record in the database. It takes in a user object as an argument, execute a SQL query to update the user with the new values and finally returns the updated user by calling the <em>get_user_by_id</em> function as seen previously. What if we want to remove or delete a user from the database? Let&#39;s see how to do that next.</p><pre>def delete_user(user_id):<br>    message = {}<br>    try:<br>        conn = connect_to_db()<br>        conn.execute(&quot;DELETE from users WHERE user_id = ?&quot;,     <br>                      (user_id,))<br>        conn.commit()<br>        message[&quot;status&quot;] = &quot;User deleted successfully&quot;<br>    except:<br>        conn.rollback()<br>        message[&quot;status&quot;] = &quot;Cannot delete user&quot;<br>    finally:<br>        conn.close()<br><br>    return message</pre><p>The code snippet above implements the delete user feature. We define a function that takes in a user id as an argument, remove the user from the database (SQL DELETE query) and return a message back.</p><p>Let&#39;s see how to make these function available via REST API endpoints next.</p><h3>REST API implementation</h3><p>The REST api endpoints expose the database functions created in the previous section. The table below maps the database functions to the API endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yWKUaR263JumW7Cxub04FA.png" /><figcaption>User management API endpoints with database function</figcaption></figure><pre>from flask import Flask, request, jsonify #added to top of file<br>from flask_cors import CORS #added to top of file</pre><pre>app = Flask(__name__)<br>CORS(app, resources={r&quot;/*&quot;: {&quot;origins&quot;: &quot;*&quot;}})<br><br>@app.route(&#39;/api/users&#39;, methods=[&#39;GET&#39;])<br>def api_get_users():<br>    return jsonify(<strong>get_users()</strong>)<br><br>@app.route(&#39;/api/users/&lt;user_id&gt;&#39;, methods=[&#39;GET&#39;])<br>def api_get_user(user_id):<br>    return jsonify(<strong>get_user_by_id(user_id)</strong>)<br><br>@app.route(&#39;/api/users/add&#39;,  methods = [&#39;POST&#39;])<br>def api_add_user():<br>    user = request.get_json()<br>    return jsonify(<strong>insert_user(user)</strong>)<br><br>@app.route(&#39;/api/users/update&#39;,  methods = [&#39;PUT&#39;])<br>def api_update_user():<br>    user = request.get_json()<br>    return jsonify(<strong>update_user(user)</strong>)<br><br>@app.route(&#39;/api/users/delete/&lt;user_id&gt;&#39;,  methods = [&#39;DELETE&#39;])<br>def api_delete_user(user_id):<br>    return jsonify(<strong>delete_user(user_id)</strong>)<br><br>if __name__ == &quot;__main__&quot;:<br>    #app.debug = True<br>    #app.run(debug=True)<br>    app.run() #run app</pre><p>The code snippet above implements our API endpoints. First we import the neccessary packages. The API endpoints receive JSON objects as request and also return JSON objects. For this reason, we convert Python dictionary to JSON using the <em>jsonify</em> package. Next we create the Flask app and configure the app to allows access to our endpoints from any ip-address using <em>CORS</em>.</p><p>In order to create an endpoint, we first define the route. Let&#39;s take the first endpoint an an example. We define the root as <em>‘/api/users’</em> and set the method to <em>GET</em>. The default method is <em>GET</em> so it is also fine to leave out the method parameter. The root (or endpoint) specifies an api function i.e. <em>api_get_users </em>which uses the database function <em>get_user</em> to return the list of users in our database. Notice that, a JSON object is returned. The other endpoints are straightforward.</p><h3><strong>Testing the API</strong></h3><p>The next step after implementing the endpoint is to carry out a functional test of all the endpoints before making it available to the public (frontend app). We can achieve this by using a REST API client. There are many options available but I particularly like <a href="https://www.postman.com/product/rest-client/">Postman</a>. It has a free package, it&#39;s easy to use and has loads of great features such as saving and grouping endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htxrszv-hx_Dj5P8qpTqAA.png" /><figcaption>Initiating REST API request using Postman</figcaption></figure><p>The figure above shows how to initiate a REST API request using Postman. Notice that the request is a <em>GET</em> request to our endpoint to fetch user record with matching <em>user_id</em> (i.e. <em>user_id</em> = 1). The response is also formatted as JSON. The frontend application receives this info (user record) and decides how to present it to the user.</p><h3>Summary</h3><p>In this tutorial, you&#39;ve learned how to create RESTful API using Python Flask and SQLite. We have covered very important concepts and principles for implementing RESTful API by implementing a User management application. So, we have covered the first half of a full-stack application i.e. the backend. We&#39;ll create a frontend web app that &quot;consumes&quot; the API we&#39;ve created in this tutorial — you surely don&#39;t want to miss the next tutorial.</p><p>You can freely get the <a href="https://github.com/effiongcharles/full_stack_web_python_flask_react_bootstrap">complete project source code on my github</a>. I hope you have learn something interesting that you can apply to your projects.</p><p>Interested in more Python programming? Check out my other Python tutorials.</p><ul><li><a href="https://levelup.gitconnected.com/program-a-networked-tic-tac-toe-game-in-python-30f8826e591d?sk=5366727d6280b6256c79a94b74689aa2">Program a Networked Tic-Tac-Toe Game in Python</a></li><li><a href="https://levelup.gitconnected.com/build-a-note-taking-app-with-mysql-backend-in-python-927b4c5fad91?sk=a57e187ba5d8275d8fef32670f9f461d">Build a Note-Taking App with MySQL Backend in Python</a></li><li><a href="https://levelup.gitconnected.com/learn-python-by-building-a-gui-guessing-game-with-tkinter-9f82291db6?sk=4154727ca3623ac1a98f9aa1dbb4a565">Learn Python by Building a GUI Guessing Game with Tkinter</a></li><li><a href="https://levelup.gitconnected.com/program-your-first-multiple-user-network-game-in-python-9f4cc3650de2?sk=312059e7967875fdbf4c7b67520bbdc9">Program Your First Multiple User Network Game in Python</a></li><li><a href="http://Learn Python by Building a Multi-user Group Chat GUI Application">Learn Python by Building a Multi-user Group Chat GUI Application</a></li></ul><p>Happy coding and see you in the next tutorial.</p><p>Regards,</p><p>Charles</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8592baa6e4eb" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/full-stack-web-app-with-python-react-and-bootstrap-backend-8592baa6e4eb">Full-stack Web App with Python, React and Bootstrap — Backend</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ionic-React Login Authentication with RESTful API]]></title>
            <link>https://levelup.gitconnected.com/ionic-react-login-authentication-with-restful-api-79352883b9f3?source=rss-aaf7407e4abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/79352883b9f3</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ionic]]></category>
            <dc:creator><![CDATA[Charles Effiong]]></dc:creator>
            <pubDate>Mon, 14 Sep 2020 11:48:19 GMT</pubDate>
            <atom:updated>2020-09-17T00:48:04.582Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to program a native mobile app using Ionic-React framework.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qhqd8qBNtbrWLq6ZVtzXCA.png" /></figure><p>In this tutorial, I&#39;m going to help you get started with Ionic-React framework by building a simple Login Authentication app. The video below shows the application we&#39;ll be developing together.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCF1XrKWgess%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCF1XrKWgess&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCF1XrKWgess%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e46768b35c860f172010994d63f2699/href">https://medium.com/media/8e46768b35c860f172010994d63f2699/href</a></iframe><p>So, what’s <a href="https://ionicframework.com/docs/react">Ionic-React</a> and why use it? Ionic-React is Ionic version of &quot;React Native&quot; for building &quot;native&quot; mobile apps. The framework provides many out-of-the-box mobile UI components for building cool mobile apps. One major advantage of the framework over “React Native” is that it allows you to leverage your existing CSS skills. This means that you can create the entire mobile UI using “everyday” css elements such as buttons, h1 tags, p tags etc. How cool is that!</p><p>I am going to assume you have basic React know-how and understand concepts such as components and hooks. I have created an awesome tutorial to help you get started with R<a href="https://levelup.gitconnected.com/react-material-table-crud-operations-with-restful-api-data-ca1af738d3c5?source=friends_link&amp;sk=971af34c01f09c724d94a9de67c8e70b">eact and Material UI </a>— yes go have a look! Ionic know-how is not required for this tutorial but nice to have. Also, I have uploaded the <a href="https://github.com/effiongcharles/login_auth">complete project source code on Github</a> for you to download and try out.</p><p>In order to get started with Ionic-React, we need to install it using the command below:</p><pre>npm install -g @ionic/cli</pre><p>Now that we have installed Ionic-React, it&#39;s time to create our App using the command below:</p><pre>ionic start <strong>Auth</strong> blank --type=react</pre><p>The command creates an Ionic-React app named &quot;Auth&quot; with blank template. We can immediately view the app on the web-browser by running the command below:</p><pre>ionic serve</pre><p>When the web-browser opens, the screenshot in the figure below is displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*OkIv8qw7d0OLjtZRFc8UMA.png" /></figure><p>Congratulations! You have created your very first Ionic-React mobile app. Wasn&#39;t that easy?☺️ Notice that the page or screen displayed is the default &quot;Home&quot; page that ships in with the Ionic-React boilerplate. The &quot;<em>&lt;Project&gt;/pages</em>&quot; directory contains the source file for the home page i.e. &quot;<em>Home.tsx.</em>&quot; Before we start with creating our own page with Ionic-React components, let&#39;s first discuss the backend side of our app.</p><h3>Backend</h3><p>Our app uses a free online RESTful API which allows us to abstract away the complexity of developing such an API ourselves. It uses the freely available API provided by <a href="https://reqres.in/"><em>Regress</em></a>. <em>Regres </em>provides many api endpoints which I have found very useful for prototyping. We&#39;ll use the <strong><em>/api/login</em></strong> endpoint in order to authenticate users. This endpoint requires two parameters — email and password as show in the code snippet below:</p><pre>//request<br>{<br>    &quot;email&quot;: &quot;eve.holt@reqres.in&quot;,<br>    &quot;password&quot;: &quot;cityslicka&quot;<br>}</pre><pre>//success  - Response 200</pre><pre>{<br>    &quot;token&quot;: &quot;QpwL5tke4Pnpja7X4&quot;<br>}</pre><pre>//failure - Response 400<br>{<br>    &quot;error&quot;: &quot;Missing password&quot;<br>}</pre><p>So, we get back a response from the server after initiating an api request. In this case, we get back a valid token (which normally stores user details in encrypted form) for a successful server response. Otherwise, we get back an error.</p><p>Let&#39;s now move on to the frontend side of the application, now that you have a good understanding of the backend process.</p><h3>Frontend</h3><p>Ionic-React framework provides many out-of-the-box mobile UI components such as alerts, toolbar, cards, etc. This allows for setting-up mobile page easily without writing a line of css codes much like Material UI and Bootstrap. However, Ionic-React apps takes on the look and feel of the underlaying platform which can be android or IOS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*j0RDnjzvwPi4oL7SLO4MRw.png" /></figure><p>The figure above shows our page login page which is typical of most login page. The page is divided into the header (host the page title i.e. Login) and the page content. Each item on the page is actually an Ionic-React component.</p><p>Ionic-React UI components are easy to use and you should have no problem using the components especially if you have worked with other UI framework such as bootstrap. Let&#39;s take a look at some of the components used to render the page.</p><pre>&lt;IonHeader&gt;<br>  &lt;IonToolbar&gt;<br>    &lt;IonTitle&gt;Login&lt;/IonTitle&gt;<br>  &lt;/IonToolbar&gt;<br>&lt;/IonHeader&gt;</pre><p>The code snippet above is used to render the page title. First, we specify the header section of the page (using <em>IonHeader component) </em>and then use the <em>Iontoolbar </em>component to place the title at the top (header section) of the page. The toolbar component can also be used to place components at the bottom of the page using the <em>IonFooter </em>component as parent.</p><pre>&lt;IonRow&gt;<br>  &lt;IonCol&gt;<br>    &lt;IonIcon<br>      style={{ fontSize: &quot;70px&quot;, color: &quot;#0040ff&quot; }}<br>      icon={personCircle}<br>    /&gt;<br>  &lt;/IonCol&gt;<br>&lt;/IonRow&gt;</pre><p>Similar to the most css frameworks, Ionic-React allows us to layout contents in Grid layout i.e. in rows/columns. The code snippet above renders the page icon i.e. the person icon using the <em>IonIcon </em>component. Notice that we can change the icon style using traditional css which is one of the advantage of Ionic-React over the React-Native framework.</p><pre>&lt;IonRow&gt;<br>  &lt;IonCol&gt;<br>    &lt;IonItem&gt;<br>      &lt;IonLabel position=&quot;floating&quot;&gt; Email&lt;/IonLabel&gt;<br>      &lt;IonInput<br>        type=&quot;email&quot;<br>        value={email}<br>        onIonChange={(e) =&gt; setEmail(e.detail.value!)}<br>        &gt;<br>      &lt;/IonInput&gt;<br>    &lt;/IonItem&gt;<br>  &lt;/IonCol&gt;<br>&lt;/IonRow&gt;</pre><p>The code snippet above displays the email area of the page using <em>IonLabel</em> (for displaying the label) and <em>IonInput </em>for displaying the actual email input field. Notice that we can specify the input type (text, email, password) similar to traditional css. We change the &quot;email state&quot; object when user enters an email address via the <em>onIonChange </em>function. This is similar to traditional css <em>onChange</em> event for input elements.</p><pre>&lt;IonRow&gt;<br>  &lt;IonCol&gt;<br>    &lt;p style={{ fontSize: &quot;small&quot; }}&gt;<br>      By clicking LOGIN you agree to our &lt;a href=&quot;#&quot;&gt;Policy&lt;/a<br>    &lt;/p&gt;</pre><pre>    &lt;IonButton expand=&quot;block&quot; onClick={handleLogin}&gt;<br>      Login<br>    &lt;/IonButton&gt;</pre><pre>    &lt;p style={{ fontSize: &quot;medium&quot; }}&gt;<br>      Don&#39;t have an account? &lt;a href=&quot;#&quot;&gt;Sign up!&lt;/a&gt;<br>    &lt;/p&gt;<br>  &lt;/IonCol&gt;<br>&lt;/IonRow&gt;</pre><p>The code snippet above displays the helper texts and login button. Notice that we can use the good old css elements to display text and style it to our taste. Ionic-React provides us with the <em>IonButton </em>component for rendering buttons. We have used the &quot;block&quot; property to allow the button span the entire screen width. Notice that the <em>handleLogin</em> function is called when the button is clicked. Let&#39;s take a look at this function next.</p><pre>const handleLogin = () =&gt; {<br>  //validate inputs code not shown</pre><pre>  const loginData = {<br>    email: email,<br>    password: password,<br>  };</pre><pre>  const api = axios.create({<br>    baseURL: `https://reqres.in/api`,<br>  });</pre><pre>  api.post(&quot;/login&quot;, loginData)<br>    .then((res) =&gt; {<br>      history.push(&quot;/dashboard/&quot; + email);<br>    })<br>    .catch((error) =&gt; {<br>      setMessage(&quot;Auth failure! Please create an account&quot;);<br>      setIserror(true);<br>    });<br>};</pre><p>The <em>handleLogin </em>function code snippet is shown above. First, we validate user inputs (code not shown here for simplicity but available in the project source code). Next, we initiate an api request using the axios package. This package is nice for initiating api calls and can be installed using &quot;<strong><em>npm install axios</em></strong>.&quot; Notice that we&#39;re doing a post request to our backend api and passing in a <em>JSON</em> object containing the user login credentials i.e. email and password. Next, we process the server (API) response and decide the correct action to perform. If we received an error code (e.g. 400, 401) — it means something went wrong and the server could not authenticate the user. In this case we catch the error and display a nice message to our user. On the other hand, if everything went well, we simply redirect the user to a dashboard screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*uJMS3l152bSoqE6KmwDfZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*hE_xcZYq8_Rw0EEiPsYZEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*JqXq6ODKTdgabfVOR5JI1w.png" /><figcaption><strong>Left</strong>: Invalid email. <strong>Middle</strong>: Auth failure. <strong>Right</strong>: Login successful — Dashboard page</figcaption></figure><p>The screenshots above shows some of the cases discussed above. The <em>Dashbord</em> page displays a list of uses fetched from the RESTful API. The data fetched is displayed using <em>IonList</em> components.</p><p><strong>Summary</strong></p><p>I have shown you how to quickly get started with mobile app development using Ion-React component with data from a RESTful API by developing a simple Authentication app. This tutorial illustrates core concepts that can be applied to building other complex mobile apps.</p><p>Ion-React is truly a great frameworks with tons of components for rapid mobile app development. The learning curve is faster compared to React-Native since we can leverage our existing css know-how instead of learning new ways to style components as in React-Native. I&#39;m sure you&#39;ll enjoy learning and building cool apps with Ionic-React.</p><p>I hope you’ve learned something in this tutorial.</p><p>Feel free to <a href="https://github.com/effiongcharles/login_auth">download/clone the project source code on Github.</a></p><p>Check out my other tutorials on <a href="https://levelup.gitconnected.com/react-material-table-crud-operations-with-restful-api-data-ca1af738d3c5?source=friends_link&amp;sk=971af34c01f09c724d94a9de67c8e70b">React/Material UI</a> and <a href="https://levelup.gitconnected.com/program-your-first-multiple-user-network-game-in-python-9f4cc3650de2?source=friends_link&amp;sk=312059e7967875fdbf4c7b67520bbdc9">Network game programming in Python if you haven’t☺️</a></p><p>Have fun programming!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79352883b9f3" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/ionic-react-login-authentication-with-restful-api-79352883b9f3">Ionic-React Login Authentication with RESTful API</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Material-Table CRUD Operations with RESTful API data]]></title>
            <link>https://levelup.gitconnected.com/react-material-table-crud-operations-with-restful-api-data-ca1af738d3c5?source=rss-aaf7407e4abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca1af738d3c5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[material-ui]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Charles Effiong]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 09:23:55 GMT</pubDate>
            <atom:updated>2020-06-02T18:42:20.720Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn to perform CRUD operations in a few lines of code using Material-Table</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DsnBWFglpSrgz7XAylEeFw.png" /></figure><p>Hi guys, welcome to my first <a href="https://reactjs.org/">react.js</a> tutorial 😊 I&#39;m going to show you how to perform CRUD operations in React by building a simple user management web app. We&#39;re going to use the <a href="https://material-table.com/">Material-table</a> package with remote data (i.e. data from a RESTful API).</p><p>The video below shows the application we&#39;ll be developing.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTeAcO0SGZYM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTeAcO0SGZYM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTeAcO0SGZYM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/427e9de9f3dd9688c609f8879af7b281/href">https://medium.com/media/427e9de9f3dd9688c609f8879af7b281/href</a></iframe><p>The Material-table package extends the default table from Material-ui by providing many cool out-of-the box features such as search bar, add button, pagination, etc. Using the Material table provides a super seamless means of performing CRUD operations in react.js. Trust me, you wouldn’t want to go through the stress of using traditional forms for CRUD operations after getting to know how easy it is to do with this awesome package. OK enough talking. Let’s get started.</p><p>I&#39;m going to assume that you are a bit familiar with basic react concepts (such as states), Javascript, and RESTful API. Also, Material UI know-how would be great but not a must.</p><p>In order to start using Material-table ensure you install it as below:</p><pre>npm install material-table --save<br>npm install <a href="http://twitter.com/material">@material</a>-ui/core --save<br><strong>or (if you using yarn)<br></strong>yarn add material-table<br>yarn add <a href="http://twitter.com/material">@material</a>-ui/core</pre><p>Material table uses material-ui icons, so be sure you install Material-ui icons as below:</p><pre>npm install <a href="http://twitter.com/material">@material</a>-ui/icons --save<br>yarn add <a href="http://twitter.com/material">@material</a>-ui/icons</pre><p>I also used Material-ui Alert component for notification in cases of error. We need to install it using the command below:</p><pre>npm install @material-ui/lab --save<br>yarn add @material-ui/lab</pre><p>Oh, I almost forgot the <a href="https://www.npmjs.com/package/axios">axois</a> package used for initiating API request. Do install the package as below:</p><pre>npm install axios --save<br>yarn add axios</pre><p>Let&#39;s look into the source codes now that we have installed the needed packages. <a href="https://github.com/effiongcharles/material-ui-table-crud-restapi"><strong>The complete project source code is available on github</strong></a> for you to download and try out. I&#39;m going to focus only on relevant code sections here.</p><h3>Backend — Remote data source</h3><p>This app relies on a free online REST API in order to abstract away the complexity of creating such an API ourselves as this is not the focus of the tutorial. We’ll use <a href="https://reqres.in/">https://reqres.in/</a> for this purpose. It provides API endpoints that allow us to make (users related) API requests such as POST (for creating a record, in our case: create a new user), GET (for fetching records), PUT/PATCH (for updating record), DELETE (as the name implies😏) etc. I’d suggest that you visit the site and familiarize yourself with the various possible API calls. Let’s move on to the frontend side of things.</p><h3>Frontend — Reactjs, Material UI/Table</h3><p>React <a href="https://material-ui.com/">Material UI</a> provides us with many components (Alert, Tables, Navbar etc) for creating awesome user interfaces in React — without writing a single line of CSS code. Another popular UI framework is &quot;react-bootstrap&quot; (yes it’s the same old bootstrap framework rebuilt for react). As stated earlier, Material-table extends the default Material-UI table with additional cool features. Let’s get started with our users table.</p><p>Tables generally have rows and columns. We&#39;ll need to define columns and rows (data) for our table as below:</p><pre>var columns = [</pre><pre>{title: &quot;id&quot;, field: &quot;id&quot;, hidden: true},<br>{title: &quot;Avatar&quot;, render: rowData =&gt; &lt;Avatar maxInitials={1} size={40} round={true} name={rowData === undefined ? &quot; &quot; : rowData.first_name} /&gt;  },<br>{title: &quot;First name&quot;, field: &quot;first_name&quot;},<br>{title: &quot;Last name&quot;, field: &quot;last_name&quot;},<br>{title: &quot;email&quot;, field: &quot;email&quot;}</pre><pre>]</pre><pre>const [data, setData] = useState([]); //table data</pre><pre>//for error handling<br>const [iserror, setIserror] = useState(false)<br>const [errorMessages, setErrorMessages] = useState([])</pre><p>From the code snippet above, our table will have id, first name, last name, email, and avatar columns. Let&#39;s see an example JSON data that we&#39;ll receive from the RESTful API. This is shown below:</p><pre>//JSON data from RESTful API<br>&quot;user&quot;: <br> {<br>    &quot;id&quot;: 2,<br>    &quot;email&quot;: &quot;janet.weaver@reqres.in&quot;,<br>    &quot;first_name&quot;: &quot;Janet&quot;,<br>    &quot;last_name&quot;: &quot;Weaver&quot;,<br>    &quot;avatar&quot;: &quot; &quot;<br> }</pre><p>Did you notice that the JSON data keys (id, email, …) exactly match the table columns — field attributes (id, email, …)? This is super important as Material-table relies on this to correctly display data from our API i.e. map API data to table columns. Hope you get the idea?</p><p>The &quot;data&quot; variable will store our table data in a state variable. The app (component in <em>react</em> language) re-renders (reacts) when the state changes (using the set method i.e. setData in our example). The other state variables are used for error handling. We’ll touch on them later.</p><p>The next step is to fetch the data from the API so that the data variable can hold the users record instead of an empty array. Here, we will need to initiate a GET request to our API so we can receive the users list as a response from the API. Let’s see how this is done next</p><pre>useEffect(() =&gt; {<br>  api.get(&quot;/users&quot;)<br>    .then(res =&gt; {<br>      setData(res.data.data)<br>    })<br>    .catch(error=&gt;{<br>      setErrorMessage([&quot;Cannot load user data&quot;])<br>      setIserror(true)<br>    })<br>}, [])</pre><p>We fetch the list of users inside the useEffect react hook — the useEffect function runs every time a functional component is rendered e.g. when the page refreshes or when a state data change (in this case, the state data needs to be included in the useEffect array). The API responds to our initiated GET request with a list of users data. We then use the setData method to change the state of the data object. Now, the data variable contains the list of users instead of an empty array. On the other hand, if an error occurs, we alert the user. That was easy right?😊</p><p>So we have our data and it&#39;s just about time we display them on the table.</p><pre>&lt;MaterialTable<br>  title=&quot;User list from API&quot;<br>  columns={columns}<br>  data={data}<br>  icons={tableIcons}<br>  editable={{<br>    <strong>onRowUpdate</strong>: (newData, oldData) =&gt;<br>      new Promise((resolve) =&gt; {<br>        handleRowUpdate(newData, oldData, resolve);<br>  }),<br>  <strong>onRowAdd</strong>: (newData) =&gt;<br>    new Promise((resolve) =&gt; {<br>      handleRowAdd(newData, resolve)<br>    }),<br>  <strong>onRowDelete</strong>: (oldData) =&gt;<br>    new Promise((resolve) =&gt; {<br>      handleRowDelete(oldData, resolve)<br>    }),<br>  }}<br>/&gt;</pre><p>The code snippet above is responsible for displaying the table. It uses the “MaterialTable” component. We specify the title, columns and data (user list). We also include a list of icons required by the component. These icons include Arrows (for pagination), search, edit, delete icons etc. If we run the app, the screen shot below will be displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WA0bUvUZh8bZjCf9rcRZnQ.png" /></figure><p>So that takes care of the <strong>R</strong>ead in C<strong>R</strong>UD operations. Let’s move on to <strong>C</strong>reate operation i.e. Add a new user. Notice that the code above includes “props” for performing the other CRUD operations (create, update and delete). The “onRowAdd&quot; prop creates a new “Promise” object (a promise returns a value in the future. This allows for handling async events — <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">read more here</a>.) The promise object invokes the &quot;handleRowAdd()” function. The code snippet below provides the function implementation.</p><pre>const handleRowAdd = (newData, resolve) =&gt; {<br>  //validation<br>  let errorList = []<br>  if(newData.first_name === undefined){<br>    errorList.push(&quot;Please enter first name&quot;)<br>  }</pre><pre>  if(newData.last_name === undefined){<br>    errorList.push(&quot;Please enter last name&quot;)<br>  }</pre><pre>  if(newData.email === undefined || validateEmail(newData.email) === false){<br>    errorList.push(&quot;Please enter a valid email&quot;)<br>  }</pre><pre>  if(errorList.length &lt; 1){ //no error<br>    api.post(&quot;/users&quot;, newData)<br>      .then(res =&gt; {<br>        let dataToAdd = [...data];<br>        dataToAdd.push(newData);<br>        setData(dataToAdd);<br>        resolve()<br>        setErrorMessages([])<br>        setIserror(false)<br>     })<br>     .catch(error =&gt; {<br>        setErrorMessages([&quot;Cannot add data. Server error!&quot;])<br>        setIserror(true)<br>        resolve()<br>      })<br>  }else{<br>    setErrorMessages(errorList)<br>    setIserror(true)<br>    resolve()<br>  }<br>}</pre><p>The function is as simple as it looks. First we do some validations to ensure user has completed all the required fields. Next, we send a POST request with the data we want to add (i.e. &quot;newData&quot;). Then, we can continue doing something else (yes, this is where &quot;Promise&quot; comes in — think of multithreading) until we receive a response from the server (the API). If the POST request was successful, then we update the state data using the setData() function and mark the &quot;Promise&quot; as resolved (see the &quot;then&quot; function). Otherwise, we alert the user of an error.</p><p>Let&#39;s now see how to update a given row in our table. For this, we call the &quot;handleRowUpdate(…)&quot; function. Its implementation is given below.</p><pre>const handleRowUpdate = (newData, oldData, resolve) =&gt; {</pre><pre>  //validation<br>  .....<br>  if(errorList.length &lt; 1){<br>    api.patch(&quot;/users/&quot;+newData.id, newData)<br>      .then(res =&gt; {<br>        const dataUpdate = [...data];<br>        const index = oldData.tableData.id;<br>        dataUpdate[index] = newData;<br>        setData([...dataUpdate]);<br>        resolve()<br>        setIserror(false)<br>        setErrorMessages([])<br>      })<br>      .catch(error =&gt; {<br>        setErrorMessages([&quot;Update failed! Server error&quot;])<br>        setIserror(true)<br>        resolve()<br>    })<br>  }else{<br>    setErrorMessages(errorList)<br>    setIserror(true)<br>    resolve()<br>  }<br>}</pre><p>I&#39;m pretty sure you can figure out what this function does. We initiate a PATCH request which is the API call for updating data. Note that we pass in the <strong>id</strong> (user id in our case) in the request URL so the API knows which record to update. If the server is able to grant our request successfully, we receive a response. Then, we update our state. Otherwise, we alert the user of error(s). The form validation is skipped since it&#39;s similar to the previous case.</p><p>So, that takes care of our <strong>C</strong>reate <strong>R</strong>ead <strong>U</strong>pdate operations. We are now left with the <strong>D</strong>elete operation. Let&#39;s look at that next.</p><pre>const handleRowDelete = (oldData, resolve) =&gt; {<br>  api.delete(&quot;/users/&quot;+oldData.id)<br>    .then(res =&gt; {<br>      const dataDelete = [...data];<br>      const index = oldData.tableData.id;<br>      dataDelete.splice(index, 1);<br>      setData([...dataDelete]);<br>      resolve()<br>    })<br>    .catch(error =&gt; {<br>      setErrorMessages([&quot;Delete failed! Server error&quot;])<br>      setIserror(true)<br>      resolve()<br>    })<br>}</pre><p>The code snippet above provides the function for handling the delete operation. This method is very similar to the previous (PATCH). The difference here is that we initiate a DELETE request.</p><h3>Summary</h3><p>In this tutorial, you have learned how to perform CRUD operations in React using the popular Material-table for React and with data from a RESTful API.</p><p>Material-table is great and I love the out-of-the-box features such as (ease of creating, updating, deleting records or rows) that it provides. I have personally used this package for a production-level code. Another interesting feature of the package is that it is very easy to customize. You can replace the columns with a Material-UI DateTime picker or change the icons (delete, edit, search). That being said, Material-table is especially great for displaying tabular data.</p><p>I hope you&#39;ve learned something in this tutorial.</p><p>Feel free to <a href="https://github.com/effiongcharles/material-ui-table-crud-restapi">download/clone the project source code on Github</a>.</p><p>Check out my other tutorials on <a href="https://levelup.gitconnected.com/program-your-first-multiple-user-network-game-in-python-9f4cc3650de2?source=friends_link&amp;sk=312059e7967875fdbf4c7b67520bbdc9">Network programming in Python if you haven&#39;t☺️</a></p><p>Good luck from me to you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca1af738d3c5" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/react-material-table-crud-operations-with-restful-api-data-ca1af738d3c5">React Material-Table CRUD Operations with RESTful API data</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Program a Networked Tic-Tac-Toe Game in Python]]></title>
            <link>https://levelup.gitconnected.com/program-a-networked-tic-tac-toe-game-in-python-30f8826e591d?source=rss-aaf7407e4abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/30f8826e591d</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tkinter]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tic-tac-toe]]></category>
            <dc:creator><![CDATA[Charles Effiong]]></dc:creator>
            <pubDate>Tue, 05 May 2020 12:23:37 GMT</pubDate>
            <atom:updated>2020-05-05T12:43:31.131Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to program a networked turn-based game in Python by implementing an online Tic-Tac-Toe</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u584ifVFdWTbTLv3zA95ug.png" /></figure><p>Hi guys, welcome to another tutorial where I&#39;m going to show you how to build a networked/online version of the classic Tic-tac-toe (or Noughts and Crosses) game in Python.</p><p>As with my other tutorials, my goal here is not just to teach you how to create this particular game but to deliver principles, techniques, and best practices for creating network apps and games. Before we get started, I have covered very important client-server concepts in my <a href="https://levelup.gitconnected.com/program-your-first-multiple-user-network-game-in-python-9f4cc3650de2?source=friends_link&amp;sk=312059e7967875fdbf4c7b67520bbdc9">previous tutorial</a>. Please do have a look especially if you are not yet familiar with network (socket) programming.</p><p>We are going to build upon some of the concepts presented in that tutorial here. In the <a href="https://levelup.gitconnected.com/program-your-first-multiple-user-network-game-in-python-9f4cc3650de2?source=friends_link&amp;sk=312059e7967875fdbf4c7b67520bbdc9">previous tutorial</a>, we have answered very important questions such as: where to put the game logic (client or server side) and why? where to keep game score? how to efficiently coordinate user play? Please see the previous tutorial if you have no idea how to answer these questions or why these questions matter in the first place.</p><p>Let&#39;s do some &quot;housekeeping&quot; before we dive into our tutorial. Be sure you have <a href="https://www.python.org/downloads/">installed and setup Python</a> and the <a href="https://tkdocs.com/tutorial/install.html">Tkinter library</a> (for creating UI).</p><p>Now that we got that out of the way, let&#39;s get started!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FpLzsgolaeN4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpLzsgolaeN4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FpLzsgolaeN4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/48cfcbae397809d10e033a7a94a3adc8/href">https://medium.com/media/48cfcbae397809d10e033a7a94a3adc8/href</a></iframe><p>The movie above shows game play sessions of our tic-tac-toe game. The game begins when two users are connected. The game score is computed at the end of each game session (result is either a win, loss or a draw) and the next game session begins after a few seconds. The most outstanding difference between this game and the <a href="https://levelup.gitconnected.com/program-your-first-multiple-user-network-game-in-python-9f4cc3650de2">rock-paper-scissors game in my previous tutorial</a> is that this is a TURN GAME i.e. user takes turns and cannot play simultaneously. Turn games require a cost effective (from network standpoint) and efficient (in terms of player coordination) mechanism to keep track of player turns and inform players when it&#39;s their turn to play.</p><p>I have uploaded the <a href="https://github.com/effiongcharles/tic_tac_toe_network_game"><strong>complete project source code on my github</strong></a><strong> </strong>for you to download and try out. Fasten your seatbelt and let&#39;s take off!</p><h3>The Tic-Tac-Toe Game Rules</h3><p>We&#39;ll start with the general game rule. Please, feel free to skip to the next section if you are already familiar with it😊 The Tic-Tac-Toe is normally played by two players on various board sizes (we&#39;ll be using a 3x3 board in this tutorial for simplicity).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfbRAO3R9cjden3WxZ9BsQ.png" /><figcaption>Fig. 1: Tic-Tac-Toe Game Rule</figcaption></figure><p>Fig. 1 shows the rules that apply to this game. Assuming Player 1 has the &quot;star&quot; symbol (X) and Player 2 has the &quot;circle&quot; symbol (O), then in the first picture, Player 2 wins (since 3 of its symbols are on the board&#39;s column). Note that Player 2 also wins if 3 of its symbols are in the middle or right column. Similar arguments can be made for the second (Player 1 wins — row or horizontal win) and third (Player 1 wins — diagonal) pictures. We have a draw in the fourth picture.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e85ef00fbc0e773911b3c993de996df/href">https://medium.com/media/0e85ef00fbc0e773911b3c993de996df/href</a></iframe><p>The code snippet in Fig. 2 implements the game logic. We check for rows, columns, diagonals wins and a draw each time a Player marks a position on the board. The <a href="https://github.com/effiongcharles/tic_tac_toe_network_game">complete source codes is available on my github</a>.</p><p>Let&#39;s move on to the client application in the next section.</p><h3>The Tic-Tac-Toe Game Client</h3><p>The Tic-Tac-Toe game client application provides an intuitive user interface for connecting to the server and playing the game. Initially a connect &quot;frame&quot; is opened where a player enters the name and connects to the server (please see the movie in the intro-section). After connecting, the connect frame is hidden and the main game window is displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*3xUw1SMuXPMWxdJ490ss0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*X1MLNdEO1jvr1MmQT0Qxwg.png" /><figcaption>Fig. 3: Tic-Tac-Toe Game Client Window</figcaption></figure><p>Fig. 3 shows the main client window for two connected clients. Let&#39;s start with how to create our awesome client game board.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53dff7d2f2c8730d4066fdc7137155c6/href">https://medium.com/media/53dff7d2f2c8730d4066fdc7137155c6/href</a></iframe><p>Fig. 4 shows the function that takes care of creating our awesome UI. It uses two <em>for-loops </em>to create a 3x3 board i.e. a 9 cell grid. Each cell is represented by an XY coordinate and contains a label (Line 6). Notice that we bind the labels to an event that fires when the label is clicked (Line 8) and stored the label in the grid (Line 9). Also we create a dictionary that stores various label properties such as its location (XY coordinates), symbol (X or O), the label object and the ticked info (we set the tick property to <em>true</em> when the label is selected so our players do not select or mark a label twice) — Line 11. Next we add the dictionary to a 1D array and also create the status label that gives our players intuitive connection and game session info (Line 15). When a cell is clicked, the &quot;<em>get_coordinate(..)</em>&quot; function is called. Let&#39;s look at this important function next.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ada2c2dfa8d1bf8449df822fe76320da/href">https://medium.com/media/ada2c2dfa8d1bf8449df822fe76320da/href</a></iframe><p>The code snippet in Fig. 5 shows the &quot;<em>get_coordinate(..)</em>&quot; function that&#39;s trigged each time a Player marks the board (or clicks on a cell). Let&#39;s discuss this function in detail.</p><p>First, we retrieve the label (that was selected) from the list of labels using the XY coordinate returned by the method (Line 4 - 5). Next, we checked if it&#39;s the Player&#39;s turn (Line 7). But, how do we coordinate the Players turn? The simple answer is to have the server send some sort of &quot;signal&quot; to the clients each time it&#39;s their turn to play. This would be just fine but not effective in terms of network communication cost. For this reason, we coordinate the game play (turns) solely in the game client app. We will discuss how that works in more details later. Assuming it&#39;s the Player&#39;s turn, we ensure the cell hasn&#39;t been selected (Line 8). Then, we set the label colour and text with the Player&#39;s symbol (e.g. O or X) — Line 8–12. Next, we send the XY coordinate to server (the server forward&#39;s this info to the opponent — Line 14). Then, we check if current selection leads to a win or a draw. If either case is true, we update the score, display the latest scores, and start a thread that reinitialised the board (Lines 19 — 30). We also ensure that we alternate the player who takes the first turn in each game session in the <em>init()</em> function — fair play huh..?</p><p>Notice that we handled the game logic and score keeping on the client side in order to reduce client/server communication steps. This is an important principle in network-programming. This practice ensures that our server is kept simple and focused on forwarding data (between clients) as opposed to handling all sorts of logic that overloads the server and slows down the network. Let&#39;s see how we receive and process messages from our server next.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5677bb1964f18a0fbaaa0fabdd3cf7a/href">https://medium.com/media/b5677bb1964f18a0fbaaa0fabdd3cf7a/href</a></iframe><p>The code snippet in Fig 6 handles the receiving and processing of incoming messages from the server. I&#39;m sure you can figure out what each line does if you have seen my previous tutorial :) In any case, let&#39;s walk through it together. First, we run an infinite <em>while loop </em>to keep receiving server messages. If we have a new message, we decode it to figure out what the server is asking us to do.</p><p>If the server message is a welcome message. Then, we set the players mark colour and &quot;greet&quot; the just connected player (Line 8–16). Conversely, if the server message begins with &quot;<em>opponent_name$&quot;, </em>the client knows that the message contains the its symbol (O or X) and the opponent&#39;s name (Lines 19–24). The client app determines and saves the opponent&#39;s symbol (Lines 27–30), update the game status (Line 32) and sleeps for 3 seconds. Next, we decide who plays first base on the symbol and store that information so that we can switch who takes the first turn in the next game round (or session) — Lines 35–42.</p><p>Finally, if the server message begins with <em>&quot;</em>$xy$<em>&quot;, </em>the client knows that the opponent has selected that coordinate. It updates the selected location on the board and marks that coordinate as <em>ticked</em> (Lines 48–54). Next, the client app determines if the marked location results in a win (for the opponent) or a draw. In either case, the current game session ends, the score is computed and displayed, the board is re-initialised and a new game session begins after a few seconds.</p><p>Notice that the client app keeps the opponent details (such as colour, symbol, name, scores). In this way, we avoid asking the server periodically for those details which would have led to extra communication cost. I have skipped the <em>&quot;connect()&quot; </em>and &quot;<em>init()</em>&quot; functions because they are pretty straightforward. More so, I have discussed how the clients connect to the server in my <a href="https://levelup.gitconnected.com/program-your-first-multiple-user-network-game-in-python-9f4cc3650de2?source=friends_link&amp;sk=312059e7967875fdbf4c7b67520bbdc9">previous tutorial</a>. This brings us to the client side of things. Let&#39;s look at the server app in the next section.</p><h3>The Tic-Tac-Toe Game Server</h3><p>The game server listens for and accepts clients connections. The server mainly acts as a forwarder i.e. forwards Player 1 name and its marked XY coordinates to Player 2 and vice versa. The server doesn&#39;t do any logic — such as executing game rule, coordinating player’s turn and computing scores because we have handled those at the client application for improved communication efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*WtlqMOtLTP0ExC2GWFpUQw.png" /><figcaption>Fig. 7: Tic-Tac-Toe Game Server</figcaption></figure><p>Fig. 7 shows the game server user interface. I bet you are already familiar with this interface if you are have seen my previous tutorials. The server starts listening for clients connection when the &quot;start&quot; button clicked. Please see my <a href="https://levelup.gitconnected.com/program-your-first-multiple-user-network-game-in-python-9f4cc3650de2">previous tutorial</a> where I explained the function that handles accepting clients connection request or just look at the project source codes. Let&#39;s discuss how the server sends and receives clients messages. The code snippet in Fig. 8 handles sending/receiving clients messages. The function is as simple as it looks. However, let’s take a closer look together :)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19eb4289ffa770ca68f53937472d3eaf/href">https://medium.com/media/19eb4289ffa770ca68f53937472d3eaf/href</a></iframe><p>When a client connects, the server sends a welcome message (Lines 7–10). Next, the server sends the opponent&#39;s name and symbol (O or X) if both clients (Players) are connected (Lines 12–17). The server then enters into an <em>infinite while loop </em>to keep receiving and responding to clients messages. Inside the while loop, we use an if-statement to check if the message from the clients is an XY coordinate. If this is the case, we forward the data to the opponent and yes we are done!</p><p>The server side code is simple because we have intelligently allow the client app handle all of the game logic. The server is only tasked with forwarding messages to the opponent.</p><h3>Conclusion and further improvements</h3><p>This tutorial shows you how to create a turn-based network game in Python by implementing a network version of the Tic-tac-toe classic game. It covers important principles, concepts, and best practices for creating an effective network games. I hope that you&#39;ll be able to apply these principles to building other cool apps and games.</p><p>I have uploaded the <a href="https://github.com/effiongcharles/tic_tac_toe_network_game"><strong>complete project source codes for you to clone/download</strong></a><strong> </strong>and try out. Feel free to contact me should you have any question on this tutorial or general comments. I would be glad to hear from you!</p><p>We have limited the board size to 3x3 in order to keep things simple. However, the tic-tac-toe game can also be played on larger board sizes. For further improvements and your own programming practice, I would suggest that you increase the board size and decide how cell markings leads to a win.</p><p>Good luck</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30f8826e591d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/program-a-networked-tic-tac-toe-game-in-python-30f8826e591d">Program a Networked Tic-Tac-Toe Game in Python</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Note-Taking App with MySQL Backend in Python]]></title>
            <link>https://levelup.gitconnected.com/build-a-note-taking-app-with-mysql-backend-in-python-927b4c5fad91?source=rss-aaf7407e4abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/927b4c5fad91</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[tkinter]]></category>
            <dc:creator><![CDATA[Charles Effiong]]></dc:creator>
            <pubDate>Thu, 09 Apr 2020 13:28:08 GMT</pubDate>
            <atom:updated>2020-04-11T10:34:10.183Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn How to Perform Database Create Read Update Delete (CRUD) Operations in Python.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vuIvcG4PCNwBRCRDRMEWw.png" /></figure><p>I&#39;m going to show you how to perform various database operations e.g. CRUD in Python by building a note-taking desktop app. My goal is not just to teach you how to create a note-taking app in Python but to deliver to you tools, principles, and concepts that can be applied to building other cool web, desktop, mobile apps (requiring backend database).</p><p>I&#39;m going to assume that you have <a href="https://www.python.org/downloads/">installed and setup Python</a> and the <a href="https://tkdocs.com/tutorial/install.html">Tkinter library</a> (for building our GUI). This tutorial will not focus on Tkinter as I&#39;ll focus more on database related operations. Thus, please see my <a href="https://medium.com/@ceffiong/learn-python-by-building-a-gui-guessing-game-with-tkinter-9f82291db6?sk=4154727ca3623ac1a98f9aa1dbb4a565">previous tutorial</a> if you are not yet familiar with Tkinter. I have uploaded the complete <a href="https://github.com/effiongcharles/note-taking-app-python">source code on github for you to download</a> and try out.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqWHAvUGb8d4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqWHAvUGb8d4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqWHAvUGb8d4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/43dce6f97a197d4d5abe8415021ec9c1/href">https://medium.com/media/43dce6f97a197d4d5abe8415021ec9c1/href</a></iframe><p>The movie above shows the working app. The app will allow users to add a new note, view note details, update and delete existing notes. The app relies on mysql database to persist (store) our note data. We will begin with the app backend i.e. setting up and performing basic database CRUD operations and then implement the front end — UI. Fasten your seat belt for take off!</p><h3>Backup — Database setup and operations</h3><p>Our cool app will use a mysql database backend for persisting data. But how do we setup such a database? In order to host the database server on your system you can download and install mysql. There are several options out there (such as <a href="http://www.wampserver.com/en/">WAMP server</a>) but we’ll use the XAMPP, which is a popular open source Apache distribution and ships in with Mysql database. It’s simple to install and use. To download XAMPP go to <a href="https://www.apachefriends.org/index.html">https://www.apachefriends.org/index.html</a> and click on the download button. Follow the instructions to install and start XAMPP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yu8kF5ztgYcOQ3Gu8zUsFA.png" /><figcaption>Fig. 1: XAMPP Dashboard</figcaption></figure><p>Fig. 1 shows the XAMPP dashboard running on localhost and on port 8081. The port number will depend on your settings :) XAMPP ships in with phpMyAdmin — a web interface that allows you to perform various db related functions. Click on &quot;phpMyAdmin&quot; menu to access the phpMyAdmin web interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jiRTJsI7lZDGFvgVe1MrdA.png" /><figcaption>Fig. 2: phpMyAdmin web interface</figcaption></figure><p>Fig. 2 shows the phpMyAdmin web interface. We can create database, tables and carry out database operations (insert data, select, delete etc) from this interface but hey, let&#39;s do it via Python script. Wouldn&#39;t that be fun? I bet it would!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64c5d3860fc1c5515a7351efa990cda4/href">https://medium.com/media/64c5d3860fc1c5515a7351efa990cda4/href</a></iframe><p>The code snippet in Fig. 3 shows the function that creates our database. We need a &quot;driver&quot; for connecting with the MySQL database server. This driver is imported in <em>Line 1</em>. Next, we create a MySQL connection object, where we specified the MySQL server details i.e. host address, port, user and password <em>(Line 3)</em>. You&#39;ll need to change those to match your server credentials.</p><p>The <strong><em>db_create_db(..)</em> </strong>function creates a database (i.e. db_notes) if it does not exist. This is important as we do not want to keep over-writing our database each time the function executes. The <em>cursor i</em>s use to handling various database operations. After executing the function <em>(Line 10)</em>, we can check phpMyAdmin to see that the database is created as shown Fig. 4 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vak4e-XEIQL69hXtXg_-Uw.png" /><figcaption>Fig. 4: Database &quot;db_notes&quot;created</figcaption></figure><p>Currently, our database is created but empty (no tables). The next step is to create tables. A database is like a collection that host other database objects e.g. tables, views etc. Let&#39;s see how to create a table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0237d82cc2f3e8caa1774261c85a507/href">https://medium.com/media/f0237d82cc2f3e8caa1774261c85a507/href</a></iframe><p>The code snippet in Fig. 5 creates table (<em>tb_notes</em>). First, we select the database <em>(Line 3) </em>that will host the table. Next, we create a string that hosts our <em>sql</em> query <em>(Line 5–8). </em>Notice that (as with the database) we create the table if it doesn&#39;t exist to prevent overwrite. Our table will have 3 fields: <em>note_id, title, and note</em>. We need a way to uniquely identify each record in our table (a table-row is known as a record), thus we use a &quot;<em>primary key</em>&quot; on the <em>note_id. </em>This means that we cannot have two records in our table with same <em>note_id </em>and the field cannot be <em>NULL. </em>Also, we set the <em>note_id </em>to &quot;auto increment&quot; which means that the database server takes care of creating unique <em>id</em> for each inserted data. We execute the <em>sql </em>query using the cursor <em>(Line 9). </em>After executing the function <em>(Line 12)</em>, we can check phpMyAdmin to see that the table is created as shown Fig. 6 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPBZdczGd_A4jVvgTlvjAg.png" /><figcaption>Fig. 6: Table &quot;tb_notes&quot; created</figcaption></figure><p>Notice that the newly created table is in the <em>db_notes</em> database because we selected it. Our table is created but currently empty. Let&#39;s see how to insert data into the table via Python.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24e38f700a0f2580ee68e32772f10910/href">https://medium.com/media/24e38f700a0f2580ee68e32772f10910/href</a></iframe><p>The code snippet in Fig. 7 shows how to insert data into our table. Notice that, we specify the table we are going to insert data into in the query <em>(Line 4). </em>Also, the query specifies only the <em>title</em> and the <em>note</em> fields and not the <em>note_id</em> field because the db server takes care of creating unique id for the <em>note_id</em> field as explained earlier. The commit function is called<em> </em>to finalise the insertion operation <em>(Line 7)</em>. This is required for every transaction/queries that modifies table data. The function is invoked to insert dummy records into our table <em>(Line 18–19).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xosQCPNYxdvAykfAQpP0BQ.png" /><figcaption>Fig. 8: Inserted note data</figcaption></figure><p>We can easily verify that the record is successfully saved in the table (<em>tb_notes</em>)<em> </em>via phpMyAdmin as displayed in Fig. 8. As stated earlier, we can also clearly see that <em>note_id </em>fields are automatically inserted for us by the server. You may be wondering how data can be read from the database table. Let&#39;s look at this next.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36c616c9092aabc0df9666ca64693566/href">https://medium.com/media/36c616c9092aabc0df9666ca64693566/href</a></iframe><p>The code snippet in Fig. 9 — <strong><em>db_select_all(..) </em></strong>shows how to retrieve all the data from the database table. We use the MySQL &quot;SELECT&quot; keyword for selecting data and the cursor fetches all (<strong>*</strong>)<strong> </strong>data from the table. Similarly, we can select one or more records using the <em>WHERE </em>keyword. The WHERE keyword can be use with SELECT to retrieve ONLY records that match the WHERE clause. This is illustrated in the <strong><em>db_select_specific_note(..)</em> </strong>function in Fig. 9 were we select only one record from the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4CQRo_TH9E8ByMo9ShzuvQ.png" /><figcaption>Fig. 10: Output of select queries</figcaption></figure><p>The select function returns the selected data as a two dimensional array. If we print out the return data (<em>see Fig. 9, Line 12–14) </em>the output (of executing both functions) is as shown in Fig. 10.</p><p>There are situations were we need to update records in our database. Let&#39;s see how to do this next.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd7e63ccec52ac6e591e6f7ec05b1405/href">https://medium.com/media/bd7e63ccec52ac6e591e6f7ec05b1405/href</a></iframe><p>Fig. 11 shows the function to update specific record in the database. The query uses the mysql &quot;UPDATE&quot; keyword with the &quot;WHERE&quot; clause to update record that matches the <em>note_id (Line 7)</em>. To test out the method, we invoke the method <em>(Line 10) </em>to update the record that has <em>note_id </em>of 5. We can verify the update via phpMyAdmin as shown in Fig. 12.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0tB6hqj-0ehL2aDcHrQe_w.png" /><figcaption>Fig. 12: Database table updated</figcaption></figure><p>Now that we are done with <strong>C</strong>reate <strong>R</strong>ead and <strong>U</strong>pdate, we have only <strong>D</strong>elete operation left. Let&#39;s see how to delete a record from the database table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/645a755cd3d4238885ce15e4506e556a/href">https://medium.com/media/645a755cd3d4238885ce15e4506e556a/href</a></iframe><p>The code snippet in Fig. 13 shows how to delete a record. The function uses the MySQL <em>DELETE</em> and <em>WHERE</em> keywords to select specific record to delete. Here, record with the specified <em>note_id</em> will be removed from our table. We invoke the function to delete the record with <em>note_id</em> of 3 from our table <em>(Line 10)</em>. If we check pypMyAdmin, we can confirm that the record with <em>note_id</em> of 3 has been removed. This is shown in Fig. 14 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3BSa6PxF6TA0OtGACAa-w.png" /><figcaption>Fig. 14: Database record deleted</figcaption></figure><p>Now that we know how to perform the CRUD database operations, we can apply the knowledge to building the frontend of our app.</p><h3>Frontend — Note-taking UI</h3><p>In the previous section, we have performed CRUD operations on our note using Python script. This is good for testing our backend but not user friendly. Therefore, we are going to create a UI from which we can perform the CRUD operations. For example, we want to be able to display the notes on a nice UI instead of the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*6ykHX1gMj0CxDCKXNl3Wbw.png" /><figcaption>Fig. 15: Note-taking app main window</figcaption></figure><p>Fig. 15 shows the app main window. It consist of a <em>listbox</em> widget (for displaying note titles), <em>entry</em> widget (for entering and displaying note title), <em>text</em> widget (for entering and displaying notes) and <em>button</em> widgets (for adding, editing, and deleting notes). Currently, we are displaying &quot;dummy&quot; titles (e.g. title 1, title 2, title 3 …). Wouldn&#39;t it be cool if we displayed data from our database table? Let&#39;s see how to do that next.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8e23063356f7842b20cdda0e7ba0adb/href">https://medium.com/media/f8e23063356f7842b20cdda0e7ba0adb/href</a></iframe><p>We rely on the <strong><em>init(..) </em></strong>function (shown in Fig. 16) to display data from our database on to the UI. The interesting thing here is that we leverage our backend functions here to create the database, table, and read data. We get all the notes in the db and store it in the <em>notes</em> variable <em>(Line 6)</em>. Then, we use a loop to append each <em>title </em>(note[0] returns the id while note[1] returns title) as seen in <em>Line 9. </em>We also save the <em>note_id </em>values in <em>notes_id </em>variable. This is because of the limitation of the Tkinter listbox widget (we need to manually map the titles on the <em>Listbox widget </em>to their respective id.)</p><p>When we select or click on any listbox item (title), an <strong><em>onselect() </em></strong>function shown in the code snippet in Fig. 17 is invoked.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04be182d5ddbc1e7f1c07f6cc397a41f/href">https://medium.com/media/04be182d5ddbc1e7f1c07f6cc397a41f/href</a></iframe><p>Here, we get the index and value of the item that was clicked from the <em>event </em>and pass it to the <strong><em>display_note(..) </em></strong>function. The display_note function is (hopefully) very easy to understand. First, we clear the fields <em>(Line 18–19)</em>. Next, we get the data we want to display from the database <em>(Line 15)</em>. The data (which is stored in the note variable) contains the <em>title</em> (data[0]) and the <em>note</em> (data[1]) retrieved from the db. We display the title and note on the UI <em>(Line 18–19)</em> and enable our edit and delete button. Next, let&#39;s see how to add a new note to the db from the UI.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/feb341d3364f4dd36be01a44c334c98b/href">https://medium.com/media/feb341d3364f4dd36be01a44c334c98b/href</a></iframe><p>When the &quot;Add&quot; button is clicked. The <strong><em>save_note() </em></strong>function shown in Fig. 18 is invoked. This function may appear long but it&#39;s simple to understand. First, we check that user enter a valid title and note <em>(Line 5–12)</em>. Then, we check to ensure the entered title is unique. If the above-mentioned conditions are fulfil, we save the data (title, note) into the database (using the db function we created earlier), update the UI — append the newly added list to the display area <em>(Line 32)</em>, and clear the text area. Next, let&#39;s see how to update the UI.</p><p>We invoke the <strong><em>update_note() </em></strong>function when the &quot;Edit&quot; button is clicked. This function is similar to the <em>save_note() </em>function we discussed earlier. The main difference is that we use the <strong><em>db_update_note()</em></strong> function. So, am not going to bore you with repetition :) The final step is to delete a db record when the delete button is clicked. Let&#39;s look at the logic behind that next.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83f88c5242991522a0590cdad90882ea/href">https://medium.com/media/83f88c5242991522a0590cdad90882ea/href</a></iframe><p>We call the <strong><em>date_note()</em> </strong>function when the delete button is clicked. This function is shown in Fig. 19. First, we ensure user select a note to delete <em>(Line 8–10)</em>. Then, we display a prompt for user to confirm the delete action <em>(Line 12)</em>. If the confirmation is &quot;yes&quot; <em>(Line 14), </em>we delete the record from the database table (using the db delete function — <em>Line 17</em>), and remove the record from the UI (<em>Line 21–23</em>). And, yes we are done :)</p><h3>Summary</h3><p>I have shown you how to perform database <strong>C</strong>reate <strong>R</strong>ead <strong>U</strong>pdate and <strong>D</strong>elete (CRUD) functions by building a note-taking app. It is my hope that you are now equipped with db principles and concepts that you can apply to developing awesome apps with db backend (web, mobile, desktop). I just cannot wait to see what you&#39;ll create next!</p><p>Wouldn&#39;t it be cool if we could not just view our notes, but view notes of other users? For improving this app and for your programming practice, I would suggest you add that functionality. <strong>Hint: </strong>You&#39;ll need at least two database tables (one for users info and the other for notes) and connect the two tables using <a href="https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html"><strong><em>foreign key </em></strong>relationship</a>.</p><p>You can download the <a href="https://github.com/effiongcharles/note-taking-app-python"><strong>complete project source code on my github</strong></a>. Feel free to try out the code and contact me if you have a question.</p><p>Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=927b4c5fad91" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/build-a-note-taking-app-with-mysql-backend-in-python-927b4c5fad91">Build a Note-Taking App with MySQL Backend in Python</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Python by Building a GUI Guessing Game with Tkinter]]></title>
            <link>https://levelup.gitconnected.com/learn-python-by-building-a-gui-guessing-game-with-tkinter-9f82291db6?source=rss-aaf7407e4abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f82291db6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tkinter]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[guessing-games]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Charles Effiong]]></dc:creator>
            <pubDate>Sat, 28 Mar 2020 14:29:58 GMT</pubDate>
            <atom:updated>2020-04-05T20:16:11.680Z</atom:updated>
            <content:encoded><![CDATA[<h4>Get Started with Python GUI App by Building a Simple Guessing Game</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*s9fZvcKtKRvsQ1aBFymDnQ.png" /></figure><p>I’m going to show you how to build a GUI-based guessing game in Python using <strong>Tkinter</strong> — which is a <strong>Python</strong> library for creating GUI widgets (buttons, labels, images, text area etc). This simple app will allow you to “get your feet wet” with core Python concepts/constructs. You can clone or download the complete <a href="https://github.com/effiongcharles/gui_guessing_game_in_python"><strong>source code on github</strong></a>. For more information about Tkinter and how to set it up please see Tkinter documentation: <a href="https://docs.python.org/3/library/tk.html">https://docs.python.org/3/library/tk.html</a>.</p><p>For this tutorial, I am going to assume that you have setup Tkinter as well as Python. So, let’s get started!</p><p>The movie below shows you an example game play session for our awesome Guessing Game App.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FNmfIrFpXneg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DNmfIrFpXneg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FNmfIrFpXneg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/527d852e8144603c249066525c85f95d/href">https://medium.com/media/527d852e8144603c249066525c85f95d/href</a></iframe><p>Let’s dive into the code. We’ll start with the GUI components and later move on to the actual game logic. The code snippet below shows the main Game Window.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ace3fcd92ed6a437136fb216e082c7a/href">https://medium.com/media/6ace3fcd92ed6a437136fb216e082c7a/href</a></iframe><p>The code is hopefully self-explanatory :) The Tkinter library is imported in line 1 and the library instance is created in Line 3. The window title e.g. “Guessing Game” is set in Line 4. Now we created “widgets” (labels) in Line 6 and 7 to add to the window. Note that the widgets are not automatically added after creation. Line 10 and 11 add the created labels to the window. Note that the grid method is used to layout the Widgets in rows/columns. The main loop in Line 11 is an infinite loop as it keeps the app running until the player closes the app window (x). Fig.3 below shows the output of the code snippet (Fig.2.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*bKiikTFmwZBX9alCLSY_xQ.png" /><figcaption>Fig. 3. Two Widgets (Labels) showing on the Main Window</figcaption></figure><p>Now that we have a basic understanding of how to create Widgets, let’s add the remaining Widgets to the window. Fig.4 shows the code snippet while Fig. 5 shows the corresponding output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a75713f1f24f8ed103e739edcbac888/href">https://medium.com/media/8a75713f1f24f8ed103e739edcbac888/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*IR0FtOgbgUY2MPZW5z-6fA.png" /><figcaption>Fig. 5: Main Game Window with all Widgets Added</figcaption></figure><p>Now that we have all the needed Widgets added to the Main Game Window, let’s focus on the actual game logic.</p><p>Fig. 6 below shows the entire code for this simple game. First, the “guess buttons” (i.e. buttons with text 0 to 9), for player guesses, are all enabled when a player clicks on the “Start Game” button — Line 118 to 119. When that happens, the “Start Game” button text changes to “Restart Game” — Line 121 to 125. This allows players to restart the game whenever they want. Also, the code automatically generates a “secret” random number between 0 and 9 (all inclusive) — Line 49.</p><p>Now players have three (3) attempts to guess the secret number by clicking on the guess button. If the guess was correct (guess is equal to secret number), then (1) the “totalNumberOfGuesses” variable is incremented and the label i.e. “lblNoGuess” text is updated according (2) A label stating that the “guess was correct…” (green colour) is displayed on the window and the Game session ends (the guess buttons are disabled when the game session ends) — Line 78 to 85.</p><p>The player can click on the “Restart Game” button to restart the Game. All variables are reset when that button is click — Line 126. On the other hand, if the player guess is not equal to the secret number, a “message hint” is displayed on the Window (in red colour — danger! ) — Line 88 to 97.</p><p>For example, if we assume the secret number is 5 and the player guessed 8. Then, a “message hint” stating that “Secret number is less than your current guess” is displayed (who doesn’t like a help hint!). Also, the total number of guesses is incremented. The game ends when the total number of guesses is equal to the maximum number of allowable guesses (i.e. static 3. Get ready to make this dynamic later!) — Line 101 to 110.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f8b3986367270671ee98ba99f2a8148/href">https://medium.com/media/3f8b3986367270671ee98ba99f2a8148/href</a></iframe><p>Fig. 7 through Fig. 11 show an example game play session. Here, the secret number was 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*y2Jac1T9j-jF_Y7OLxc1Vw.png" /><figcaption>Fig. 7: Game Window before the start button is clicked. The “Guess buttons” are disabled</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*eK3KXVwg8bm4HeUc-vbM6Q.png" /><figcaption>Fig. 8: The “Start Game” button is clicked and the “Guess buttons” are enabled</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*NiMBu9m4a0WR-Rxmlmj71w.png" /><figcaption>Fig. 9: First player guess is wrong. Player is notified and selected button is disabled</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*5T-g3JhbT76ezwZTAE0ZRg.png" /><figcaption>Fig. 10: Second guess is equally not the secret number</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*W8lSVIc3VRh49XwHI4XqbQ.png" /><figcaption>Fig. 11: Victor at last :) The “Guess buttons (0 to 9) are disabled and game is ended. Player can restart the game.</figcaption></figure><p>I have presented how to program a simple guessing game using Python and the Tkinter library in this tutorial. It introduces the reader to many Python concepts such as “variables, datatypes, if/else statements, loops, list, comments, functions, and the Tkinter library for implementing GUI.” It is my hope that cute little tutorial helps you get started programming in Python.</p><p>Here are some suggestions for improving the application. Let’s say your programming assignment: Implement additional features to:</p><ol><li>Allow player set the guess range e.g. from 10 to 20</li><li>All user to set the max number of guess. It’s currently set to 3 and not changeable</li><li>Dynamically create the “guess buttons” buttons depending on 1.</li><li>Dynamic Count down timer!</li></ol><p>Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f82291db6" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/learn-python-by-building-a-gui-guessing-game-with-tkinter-9f82291db6">Learn Python by Building a GUI Guessing Game with Tkinter</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Program Your First Multiple User Network Game in Python]]></title>
            <link>https://levelup.gitconnected.com/program-your-first-multiple-user-network-game-in-python-9f4cc3650de2?source=rss-aaf7407e4abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f4cc3650de2</guid>
            <category><![CDATA[game-network]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[tkinter]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[rock-paper-scissors]]></category>
            <dc:creator><![CDATA[Charles Effiong]]></dc:creator>
            <pubDate>Sat, 28 Mar 2020 14:06:15 GMT</pubDate>
            <atom:updated>2020-04-16T22:32:41.312Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build your very first multiple-user rock paper scissors network game using python.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ZhIwW3RNckFS2lbvFiWOw.png" /></figure><p>Hi guys, I&#39;m going to show you how to program your first multi user online or network game in Python. We will program the popular rock-paper-scissors game, which you can play with another online/network player. So, this is surely going to be so much fun!</p><p>As with other tutorials, my aim is not just to show you how to program this specific network game but to give you network programming concepts that you can apply to creating other cool network apps and games. One of the courses I took during my undergraduate studies (at the University of Greenwich, UK) was network programming (the teacher picked Java for the programming language) and we were required to program a network game for the coursework. That was so much fun as many of my classmates came up with cool network games. I’m going to apply some of the concepts learned in this tutorial.</p><p>In my <a href="https://medium.com/p/learn-python-by-building-a-multi-user-group-chat-gui-application-af3fa1017689?source=email-aaf7407e4abd--writer.postDistributed&amp;sk=af315050575d9a7bda095f4f5bf87a38">previous tutorial</a>, I showed you how to program a multi-user group chat application in Python. We are going to leverage much of the <a href="https://medium.com/p/learn-python-by-building-a-multi-user-group-chat-gui-application-af3fa1017689?source=email-aaf7407e4abd--writer.postDistributed&amp;sk=af315050575d9a7bda095f4f5bf87a38">previous tutorial</a> here. Thus, I would suggest that you have a look at that tutorial before continuing with this one, especially if you are not yet familiar with network programming (client/server model). We have, in the <a href="https://medium.com/p/learn-python-by-building-a-multi-user-group-chat-gui-application-af3fa1017689?source=email-aaf7407e4abd--writer.postDistributed&amp;sk=af315050575d9a7bda095f4f5bf87a38">previous tutorial</a>, covered the following:</p><ol><li>How to create client/server sockets</li><li>How the server listens for and accepts multiple clients connection requests</li><li>How clients connect and send messages to server</li><li>How the server receives and forwards clients messages</li></ol><p>We are not going to go over those in details in this tutorials as we will focus on how to efficiently handle clients/server interactions in network game programming. We will consider very important questions such as &quot;do we handle game scores on client or server side? What are the implications (in terms of speed and efficiency of both options? Where to put game logic — client or server side? Also, how to effectively coordinate players interactions?&quot;</p><p>I am going to assume that you have <a href="https://www.python.org/">installed and setup Python</a> on your computer. I will be using the popular Python GUI library: <a href="https://docs.python.org/3/library/tk.html">Tkinter</a> for the User Interfaces — This will allow us create an awesome UI for our players. Let&#39;s get started with our awesome rock-paper-scissors network game.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-WJN1uhbUhw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-WJN1uhbUhw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-WJN1uhbUhw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb72cd6b5d7bcfee8de95b901bf7e50f/href">https://medium.com/media/eb72cd6b5d7bcfee8de95b901bf7e50f/href</a></iframe><p>The video above shows a typical game session for our network game. It allows two players connect to the server and compete with each other. Notice that this is not a turn game (i.e. where players take turns) as the players can simultaneously play the game (make their choices). The game ends after a specific number of rounds (5 rounds in this game). Then, the winner is determined and a new game play session starts after the countdown. Let starts with the general game rule, then move on to the game client and server applications. The <strong>source codes</strong> for the entire project can be <a href="https://github.com/effiongcharles/network_rock_paper_scissors_game"><strong>downloaded/clone on github</strong></a>. So, fasten your seat belt and let&#39;s take off!</p><h3>Network Rock-Paper-Scissors</h3><p>Let&#39;s briefly discuss the rock-paper-scissors game rule before we move on to discussing the game client/server application. This classic fun game is commonly played by two people (although can be played by more). Later, you&#39;ll extend the game by adding feature support for more than two users — wouldn&#39;t that be a fun programming task for you? I bet it would!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*ZnG1siCKGD5GgzxTtZEG2w.png" /><figcaption>Fig. 1: Rock-paper-scissors game rule</figcaption></figure><p>Fig. 1 describes the game rule which I&#39;m hoping you&#39;re already already familiar with. If so, you could refresh your memory or simply continue to the next section i.e. The game client app. In simple terms, the rule states that &quot;rock&quot; defeats &quot;scissors&quot; and &quot;scissors&quot; defeats &quot;paper&quot; and &quot;paper&quot; defeats &quot;rock.&quot; Let&#39;s convert this game rule to code. Fig. 2 shows the code that implement the game rule.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed7574028ae5e1fb3dd9240d675aef83/href">https://medium.com/media/ed7574028ae5e1fb3dd9240d675aef83/href</a></iframe><p>The function takes in two arguments and using <em>if/else </em>statements decides if there’s a win, loss or even a draw. We will covert this classic game to a network game so you can play with your friends and family online. The game will have 5 rounds. We&#39;ll show the winner for each round and the final results at the last round. Then, the game session starts all over.</p><h3>The Game Client App</h3><p>The game client application allows a player to connect to the game server and play against another connected player (i.e. the opponent).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*vsCAYNKkpL9f02hWf7JCjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*UCGOogb9gADe-VulhChADQ.png" /><figcaption>Fig.3: Game client window — connections</figcaption></figure><p>Fig. 3 shows the Game client window for two connected clients (assuming the server is already running). When a player connects to the server, the server responds with a welcome message. Here, the welcome message depends on the number of connected players. After both players are connected. The game client receives the opponent&#39;s name and displays this information on the game window. Also, the &quot;Game log&quot; section is display on the game client window. This can be seen in Fig. 4 below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*11EifBGYRsf98LOwzFc-JQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*gns5LstJj1Vk6ogd7kunOg.png" /><figcaption>Fig. 4: Game client window — game session</figcaption></figure><p>Now that both clients are connected and we know who the opponent is. The game session can start. But how do we know when to start the game session? One possibility is for the server to send a &quot;start&quot; signal to the clients. The game session can start when the clients receive the start signal. You may say &quot;that&#39;s exactly what I was thinking.&quot; Yes, we could do that but could we find a better method? The answer is an absolute yes! We need to reduce &quot;network communications&quot; in order to improve our game speed and efficiency. In simple words, &quot;<em>it&#39;s best to handle logic in the client side (if possible)</em>.&quot; In this way, we avoid sending messages back and forth and clogging the network i.e. reducing network traffics. So, in our awesome game, we start the game session when we know that our opponent is ready i.e. when we receive our opponent&#39;s name from the server. Thus, eliminating the need for server communication in order to start the game. I&#39;m hoping you understand this principle.</p><p>We use a count-down timer and enabling/disabling of the &quot;choice buttons&quot;( i.e. rock paper scissors buttons at the bottom of the game window) to control when user can play. Initially the choice buttons are disabled and enabled when the counter decrements to 0. When this happens, the players make their choices. The choice buttons get disabled when a player clicks on them. In this way, we ensure our players do not make more than one choice for each game round. The selected choice is forwarded to the server and the server in turn forwards the opponent’s choice to the client (e.g. player 1 choice is forwarded to player 2 and vice versa). This info gets displayed on the game client window as seen in Fig. 2. It’s important to note that <em>we do not forward the player choices until we are sure both players have made their choices</em>. So, the server waits until it receives both choices before forwarding the info.</p><p>The next step is to determine who wins in the current game round. One possibility would be that the server determines who the winner is and forwards the info to the clients. This would absolutely work but not efficient in terms of speed. Remember, our principle is to reduce server/client communications by handling as much logic as possible on the client side. Think about it for a moment, if we handle the game logic on the server side then:</p><ol><li>Game server will send opponent&#39;s choice e.g. player 1 choice to player 2 and vice versa (i.e. 2 send function call multiply by 5 rounds)</li><li>Game server will compute the game score based on the players choice and send the info to the game clients (also 2 send function call multiply by 5)</li><li>Game server will have to keep track of the score so as to compute the final score at the last round (round 5 in our example. No network communication required)</li><li>Game server will have to compute final score and sends the result to the game clients (also 2 send function call. Sent only at the last round)</li></ol><p>This gives a total of <strong>22 server/clients communication steps</strong> just for determining the winner (for each rounds and the final result). Conversely, we can <strong>significantly </strong>reduce (by more than half — yes you read that correctly) all these communication steps by putting the game logic on the client side. Let&#39;s see how that&#39;s made possible</p><ol><li>Game server will send opponents choice e.g. player 1 choice to player 2 and vice versa (i.e. 2 send function call multiply by 5 rounds)</li><li>Game client determines the winner (runs the game logic that compares the two choices and determines if it&#39;s a win, loss or draw. No network communication required)</li><li>Game client keep track of the game scores for both players — no network communication required.</li><li>Game client compute the final score and determines the overall winner at the final round. Hence, no network communication is required.</li></ol><p>As you can see, this requires only <strong>10 server/clients communication steps</strong> in contrast to <strong>22</strong> if the game logic is on the server side. Imagine if we increase the number of our clients to 100000? We will save a lot of traffic by handling the logic in the client side. I hope you get the idea :)</p><p>Let&#39;s move on to the client side code now that you have a grasp of how the game client app works. In Fig. 3, when a player clicks on the &quot;<em>Connect</em>&quot; button, a <em>connect()</em> function is called. The connect function is shown in the code snippet in Fig. 5 below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb451211c0a7ae971447432a9f65884e/href">https://medium.com/media/cb451211c0a7ae971447432a9f65884e/href</a></iframe><p>The connect function is as simple as it looks. It ensures that the player enters a name and calls the <em>connect_to_server(arg) </em>function that does the actual connection to the server. This function is shown in the code snippet in Fig. 6 below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f1586cebbbd4b1896fb2b52b4c943c5/href">https://medium.com/media/8f1586cebbbd4b1896fb2b52b4c943c5/href</a></iframe><p>This function creates a client socket object<em>, </em>connects to the server<em>, </em>and sends the player&#39;s name to the server<em> (Line 4 through 6). </em>This has been explained in the <a href="https://medium.com/p/learn-python-by-building-a-multi-user-group-chat-gui-application-af3fa1017689?source=email-aaf7407e4abd--writer.postDistributed&amp;sk=af315050575d9a7bda095f4f5bf87a38">previous tutorial</a>. Please see the <a href="https://medium.com/p/learn-python-by-building-a-multi-user-group-chat-gui-application-af3fa1017689?source=email-aaf7407e4abd--writer.postDistributed&amp;sk=af315050575d9a7bda095f4f5bf87a38">previous tutorial</a> if at this stage you are unsure of what a <em>socket</em> is :) Next, we disable widgets i.e. connect, name, label widgets and start a new thread to handle receiving messages from server <em>(Line 16). </em>The code snippet in Fig. 7 shows the <em>receive_message_from_server(..)</em> function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e23ad6c39cb0fdee28e536317ac7d5bd/href">https://medium.com/media/e23ad6c39cb0fdee28e536317ac7d5bd/href</a></iframe><p>This function is at the heart of the game client application. It receives and decodes or interprets messages from the game server and updates the game client UI accordingly. The code may appear long but it&#39;s pretty self explanatory. Let&#39;s go through it together.</p><p>We run a continues loop to keep receiving messages from the server. For each message we first decode the message to know what action to perform. If the message received is either <em>welcome1 or welcome2 </em>we know it&#39;s a welcome message (sent to our players after connecting to the server). Next we update the game client UI with the appropriate welcome message (<em>Line 10 — Line15).</em></p><p>If the message received from the server starts with <em>opponent_name$ </em>we know this is the name of our opponent. We remove the <em>prefix</em> <em>(Line 18), </em>update the UI with our opponent&#39;s name <em>(Line 19) </em>and show our top frame (this frame hosts the player names and game countdown section of the UI — see Fig. 4) and middle frame (this frame hosts the &quot;game log&quot; section of the UI). Next, we start a new thread that run&#39;s our <em>countdown timer </em>code. The timer simply counts from 3 to 0. After which the game round begins <em>(Line 24).</em></p><p>When an opponent makes a choice, the choice gets sent to the game client so that the winner can be decided for each game round. We retrieve the opponent choice in <em>Line 30. </em>Then, we execute the <em>game rule logic</em> to decide who the winner (of the current round) is <em>(Line 33–Line 46).</em> The UI is updated depending on if the player wins, loss, or even draw. Notice that we keep record of both player score using the <em>&quot;your_score&quot; </em>and <em>&quot;opponent_score&quot; </em>variables. But why are we doing this? This is needed to compute the final score and decide the overall winner at the last round <em>(Line 49 to 65)</em>. For each round, we start a count down timer that is meant to coordinate the game play. Simply put, the &quot;<em>choice buttons&quot; </em>i.e. rock, paper, scissors gets enabled when <em>counter</em> value is 0 and disabled when the player makes a selection (clicks on any of the choice buttons). This is given in Fig. 8 below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a619bebeb9077340871d067c7a027b87/href">https://medium.com/media/a619bebeb9077340871d067c7a027b87/href</a></iframe><p>Before we complete the client side of things, let&#39;s see the function that handles sending players choice to the server. This function is given in Fig. 9 below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d3ad89db89d787bbbfbb588f1a2adf8/href">https://medium.com/media/9d3ad89db89d787bbbfbb588f1a2adf8/href</a></iframe><p>When a player clicks any of the &quot;<em>choice buttons&quot;</em>, we retrieve the choice <em>(Line 3), </em>send it to the server <em>(line 7) </em>and prevent multiple choices by immediately disabling the buttons (<em>Line 8</em>).</p><p>Now that we are done with the game clients, let&#39;s move on to the server side of our awesome game application.</p><h3>The Game Server App</h3><p>The game server application is responsible for handling game clients connections and forwarding messages to the clients. The game server is identical to that of the <a href="https://medium.com/p/learn-python-by-building-a-multi-user-group-chat-gui-application-af3fa1017689?source=email-aaf7407e4abd--writer.postDistributed&amp;sk=af315050575d9a7bda095f4f5bf87a38">previous tutorial</a>. Again, go have a look if you haven&#39;t or are not familiar with client/server programming model. In this section, I&#39;m only going to focus on the server code section that&#39;s unique to our game application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*qRvYkutCOCxBGU7IOmalGA.png" /><figcaption>Fig. 10: Game server window</figcaption></figure><p>Fig. 10 shows the game server window. The server is started using the <em>&quot;start&quot; </em>button, after which the clients (players) can connect and start playing. The window displays the list of connected client names. We limit the number of connected clients to two as we only want two players playing our cool game.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fccf9274b2e5b30d216d8a65a0cbd4b/href">https://medium.com/media/2fccf9274b2e5b30d216d8a65a0cbd4b/href</a></iframe><p>Accepting game clients connection requests is handled in the <em>accept_clients(..) </em>function shown in the code snippet in Fig. 11. Notice that we start a new thread to handle communications (sending and receiving messages) with the connected clients <em>(Line 8)</em>.</p><p>Next, let&#39;s look at the function responsible for handling sending and receiving of clients messages. This is shown by the code snippet in Fig. 12.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9a7861f51db0719cd0135a94c23309a/href">https://medium.com/media/d9a7861f51db0719cd0135a94c23309a/href</a></iframe><p>This function is at the heart of the game server application. When a client connects, the player name is sent to the game server. This name is retrieved in <em>Line 8. </em>Next, we send a welcome message to the connected client. The message depends on how many clients are connected. Here, the first clients get <em>&quot;welcome1&quot;</em> while the second clients gets <em>&quot;welcome2&quot; (Line 10 — Line 13) </em>The game client is able to decode the message and update its UI accordingly. We have seen this earlier :)</p><p>Next we check if two clients are connected. If that is the case, then we send the opponent&#39;s name to each clients e.g. player1 name to player2 and vice versa <em>(Line 22 — Line 23)</em>. We enter an infinite while loop to handle continuous communication with the game clients.</p><p>For each connected clients, we retrieve the choice and connection (socket) information. Then, after ensuring that both players have made their choices, we send player1 choice to player2 and vice versa <em>(Line 43 — Line 44). </em>Notice that the the server doesn&#39;t need to know about the game information such as which rounds, who&#39;s winning and final results. This is because those are handled at the client side for efficiency as explained earlier.</p><h3>Conclusion and further improvements</h3><p>This tutorial shows you how to create a network or online game in python by implementing the classic rock paper scissors game. This tutorial provides best practices and principles for creating network/online games and applications. It&#39;s my hope that you are now ready and equipped to apply these principles to creating other cool network apps and games.</p><p>We have limited the number of players to two for this tutorial. However, rock paper scissors game can be played by more than two players. In that case, the game rule changes. For improving this code and for your practice, I would suggest you extend this game app to support more than two players. For example, you could support 5 users to begin with.</p><p>I have provided the<a href="https://github.com/effiongcharles/network_rock_paper_scissors_game"> <strong>complete source code on my github repository for download/clone</strong></a><strong>.</strong> Feel free to try out the code and reach me if you have any question.</p><p>Bye for now and have lots of fun programming with Python.</p><p>Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f4cc3650de2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/program-your-first-multiple-user-network-game-in-python-9f4cc3650de2">Program Your First Multiple User Network Game in Python</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Python by Building a Multi-user Group Chat GUI Application]]></title>
            <link>https://levelup.gitconnected.com/learn-python-by-building-a-multi-user-group-chat-gui-application-af3fa1017689?source=rss-aaf7407e4abd------2</link>
            <guid isPermaLink="false">https://medium.com/p/af3fa1017689</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[chat]]></category>
            <category><![CDATA[tkinter]]></category>
            <dc:creator><![CDATA[Charles Effiong]]></dc:creator>
            <pubDate>Mon, 17 Feb 2020 10:41:50 GMT</pubDate>
            <atom:updated>2020-04-05T20:20:07.575Z</atom:updated>
            <content:encoded><![CDATA[<h4>Get started with network programming in Python by building</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjHwyPJJgAkVW0e5AVomNA.png" /></figure><p>Hey guys, I am going to show you how to build a multi-user group chat application in Python. The goal of this tutorial is to get you started with Network Programming (client/server application model) in Python. The good news is that the concepts are also applicable to other programming languages. I think it&#39;s always best to approach programming as a concept instead of a language.</p><p>I am going to assume that you have Python installed and setup on your computer. To learn more about python and how to set it up, please see the <a href="https://docs.python.org/3/">official documentation</a>. You can use an IDE of your choice. I personally prefer <a href="https://www.jetbrains.com/pycharm/">PyCharm</a>. I will be using the popular Python GUI library: <a href="https://docs.python.org/3/library/tk.html">Tkinter</a> for the User Interfaces — who likes boring command-line apps anyways :) If you haven&#39;t, then you should see my first tutorial titled &quot;<a href="https://medium.com/@ceffiong/learn-python-by-building-a-gui-guessing-game-with-tkinter-9f82291db6?sk=4154727ca3623ac1a98f9aa1dbb4a565">Learn Python by Building a GUI Guessing Game with Tkinter</a>&quot; where I covered how to use the Tkinter library in greater detail. I promise, creating GUI components using Tkinter is a breeze especially if you have worked with Java Swing, C# Window Form or HTML/CSS. In any case, it&#39;s still very easy to understand.</p><p>The group chat application will allow multiple users to connect to the server and chat with all other online users. The app works in a broadcast fashion. This means that messages from a user are broadcasted to other users. The video below shows the running application for four connected clients/users.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMEKBzxL8xHI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMEKBzxL8xHI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMEKBzxL8xHI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/33ad9ec53b8cc0007b74fb1c99736500/href">https://medium.com/media/33ad9ec53b8cc0007b74fb1c99736500/href</a></iframe><p>I know what you&#39;re thinking &quot;let&#39;s get coding.&quot; Yes, I completely agree :) We will begin with the server code and then move on to the client side.</p><h3>The Server Application</h3><p>Let&#39;s start with the GUI component layout before moving on to the actual server side network logic. The code snippet for the server side main window is provided in Fig. 1 below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a801d45e5f7241510312002ea1a5d66/href">https://medium.com/media/7a801d45e5f7241510312002ea1a5d66/href</a></iframe><p>The code is as simple as it looks :) Frames are used to place a group of widgets in specific areas in the main window. Notice that the &quot;topFrame&quot; consists of the &quot;Connect&quot;, and &quot;Stop&quot; button. A similar comment can be made for the &quot;middleFrame&quot; and the &quot;clientFrame.&quot; Notice that the piece of code for creating a button (e.g. Line 7) includes a function (e.g. &quot;start_server&quot;) that is called when the button is clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*EPaHc_Z1Kqyb-FQEjRXQpw.png" /><figcaption>Fig. 2: Server Application Window</figcaption></figure><p>Fig. 2 shows the output of the code. At the moment, when the &quot;Connect&quot; button is clicked, we are enabling the &quot;Stop&quot; button and disabling the &quot;Connect&quot; button&#39;. But we want to do more than just enabling/disabling buttons right? Let&#39;s dive into the server side logic. I&#39;m going to discuss individual server functions instead of freaking you out with many lines of codes at once :) You can clone/download the entire app <a href="https://github.com/effiongcharles/multi_user_chat_application_in_python">source code on github</a>. Let&#39;s begin with the <strong><em>start_server</em></strong> function which is invoked when the &quot;Connect&quot; button is clicked. Fig. 3 below shows the code snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34272cb40b7377682ccce7dd3d67ae3e/href">https://medium.com/media/34272cb40b7377682ccce7dd3d67ae3e/href</a></iframe><p>Line 1 imports the socket library. This is important for handing network communication. But, what&#39;s a socket? you may ask. In simple terms, a socket provides us with a bi-direction communication channel for sending and receiving data. See the <a href="https://docs.python.org/3/library/socket.html">official documentation</a> for more info on the subject. Our awesome server will be able to accept new client connection requests while processing messages from connected clients. Thus, we need &quot;threads&quot; for such parallel tasks if we do not want to clog the Main and GUI thread. Still not sure why we need threads? Then see the official <a href="https://docs.python.org/3/library/threading.html">python documentation.</a> The thread library is imported in Line 2. The server socket is created in Line 21 for IPv4 (<em>socket.AF_INET</em>) and TCP protocol (<em>socket.SOCK_STREAM).</em></p><p>We bind the server to the host address and port number in Line 22 and start listening for clients connection in Line 23. As stated earlier, we want to be able to keep listening for and accepting new clients connection requests while sending and receiving messages from already connected clients. Thus, we need a new thread for accepting new clients connection requests (Line 25) and another thread for handling sending/receiving clients messages.</p><p>Next, let&#39;s look at the <strong><em>accept_clients</em></strong> function. The code snippet is shown in Fig. 4 below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03ce888199b9934e26906c105da06485/href">https://medium.com/media/03ce888199b9934e26906c105da06485/href</a></iframe><p>The server accepts a new client connection request and stores the client information (connection object) in a list (i.e. <em>clients). </em>This enables us to keep track of all connected clients. Of course, we&#39;ll need to remove the client object from the list when the client disconnects. Next, we start a new thread to handle sending/receiving clients messages. Let&#39;s see the code snippet for the function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/742417ba3e2621c6f0fa1bc649c23cdf/href">https://medium.com/media/742417ba3e2621c6f0fa1bc649c23cdf/href</a></iframe><p>Fig. 5 shows the code snippet for sending/receiving clients messages. I have also included two helper functions which are (hopefully) self explanatory :). The first helper function i.e. <strong><em>get_client_index(…)</em></strong> returns the current client index in the clients list. This is particularly useful for handing two scenarios: (i) When a client disconnects, we need to know the client index in the client list so we can safely remove the client (ii) We want to send a client message to ALL other connect clients EXCEPT the client that sends the message (i.e. no echo). The server has an area for displaying connected clients name — let&#39;s call that &quot;clients name display&quot;. The second helper function i.e. <strong><em>update_client_names_display(…)</em></strong><em> </em>basically updates the clients name display when a client connects (add) or disconnects (remove). Let&#39;s go through the actual sending/removing function now that we&#39;ve got the helper functions out of the way.</p><p>When a new client connects, it sends its name to the server. The server receives the client&#39;s name using the <em>socket.recv </em>method (Line 11 where <em>socket </em>is the connected client socket) and sends a welcome message using the <em>socket.send</em> method to the client (Line 12). The newly connected client name is stored in the client names list and the &quot;client name display&quot; is updated in Line 16. Next, the server enters into a loop which allows it to keep receiving and sending messages to clients. We break out of this loop if client connection is lost or client message is &quot;exit.&quot; In either case, we remove the disconnected client (name and socket) from the respective list, close the client connection and remove the client name from the server (clients name) display area (Line 35 through Line 38). Otherwise, the client message is forwarded to all the other connected clients (except the sender — Line 26 to 31). This concludes the server side of our amazing multi-user chat application. Next, let&#39;s look at the client side.</p><h3>The Client Application</h3><p>The client application is responsible for initiating a connection to the server and sending messages which are forwarded (by the Server) to all other connected clients. Let&#39;s start by looking at the client GI before discussing the client logic. Fig. 6 below shows the code snippet for the client GUI, while Fig. 7 shows the corresponding output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*BQR_kkEcYfbpkCYd3MBRuA.png" /><figcaption>Fig. 7: Client GUI Application</figcaption></figure><p>Now, let&#39;s discuss the individual Client functions for connecting, sending and receiving messages from our awesome sever app. When the connect button is click it triggers a function called <strong><em>connect().</em></strong> The implementation of this function is provided in Fig. 8</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b37a196c5a10f56011c4ed11d87a0d88/href">https://medium.com/media/b37a196c5a10f56011c4ed11d87a0d88/href</a></iframe><p>The function checks if the username has been entered before attempting to connect to the server. It then calls a <strong><em>connect_to_server</em></strong> function where the actually sever connection request is initiated. The code snippet for this function is given in Fig. 9</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/517e70e9cdb0858f053996eeec8d52ca/href">https://medium.com/media/517e70e9cdb0858f053996eeec8d52ca/href</a></iframe><p>The function is (hopefully) self explanatory. First, we create the client socket (similar to the server socket). Using the socket object, we initiate a connection request to the server (via address and port number). Then, the client name is sent to the server. Recall that our awesome server responds by sending a &quot;sweet&quot; welcome message back to the client. We also enable the message area so our client can start sending messages to the server (Line 17). Next, we start a thread to keep receiving message from the server. Recall that we use a thread here because we do not want to clog the GUI thread. The GUI will freeze without this thread — try it! Let&#39;s now see the function that receives messages from the server. This is provided in the code snippet in Fig. 10 below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c3ea956c07c30688eab1980f0d0233a/href">https://medium.com/media/6c3ea956c07c30688eab1980f0d0233a/href</a></iframe><p>I promise, this code is as simple as it looks. We run a continuous loop that keeps receiving message from the server (via the client socket). Received server messages are appended to the client chat display area (Line 14 — 22) and we are done. Yes! I told you it was simple!</p><p>So, we have seen how to connect to the server, send our username to the server and receive messages from the server. Next, let&#39;s see how to retrieve and send a message (entered in the chat message area) to our super awesome server. If you take a second look at our Client GUI, you may notice that there&#39;s an area (Text widget) where user can enter chat messages but there&#39;s no &quot;send&quot; button. How then do we forward entered message in the Text widget to the server? Well, we could have used a button and bind the button to a click event. But in this case we bind the Text widget to a Return event so that an event is fired when our users press the &quot;Enter/Return&quot; key on their keyboard. When they do, we call a function to get the message. The code snippet for the function is provided in Fig. 11 below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc38bafb09d97280d00aec41aa78ad72/href">https://medium.com/media/fc38bafb09d97280d00aec41aa78ad72/href</a></iframe><p>The function itself is actually self explanatory. We get the message entered into the Text widget and append the message to the chat window display area. Notice the tags in Line 12 and 14? They are used to configure the inserted message — in this case, to change the inserted text colour blue. Simply, user message is displayed in blue text while messages from other connected clients are displayed in black. As we want other connected clients to see our message, we send the message to the server (so the server can forward the message to all other connected clients). For this purpose, we call the <strong><em>send message_to_server</em></strong> function. The code snippet for this function is given in Fig. 12</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/665af6b5a371e9568300ed2ae166ee7e/href">https://medium.com/media/665af6b5a371e9568300ed2ae166ee7e/href</a></iframe><p>I&#39;m sure you can figure out what the code does :) It sends messages to the server using the &quot;send&quot; function of the socket object. Then, it closes the client socket and destroys the chat window if user message is exit and yes, we are done!</p><p>This tutorial shows how to create a multi-user group chat application in Python. We have covered very important concepts such as networking and threads in this tutorial. It&#39;s my hope that you&#39;ll be able to use the knowledge gained in this tutorial to create super cool network apps/games. <a href="https://github.com/effiongcharles/multi_user_chat_application_in_python"><strong>You can clone/download the entire source code on my github</strong></a><strong>.</strong></p><p>Here are some suggestions for improving the app — or let&#39;s say your programming assignment :)</p><ol><li>Align user message right side of the client window — it is currently aligned left.</li><li>Display list of connected clients in the client window. Like a &quot;users online&quot; area</li><li>Enable client select and communicate with another client instead of &quot;broadcasting&quot;</li><li>Good luck!</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af3fa1017689" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/learn-python-by-building-a-multi-user-group-chat-gui-application-af3fa1017689">Learn Python by Building a Multi-user Group Chat GUI Application</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>