<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Python on 4rkal&#39;s Dev Blog</title>
    <link>https://4rkal.com/tags/python/</link>
    <description>Recent content in Python on 4rkal&#39;s Dev Blog</description>
    <image>
      <url>https://4rkal.com/4rkal.png</url>
      <link>https://4rkal.com/4rkal.png</link>
    </image>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Fri, 20 Sep 2024 11:54:29 +0300</lastBuildDate><atom:link href="https://4rkal.com/tags/python/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>How to deploy django to production</title>
      <link>https://4rkal.com/posts/django-prod/</link>
      <pubDate>Fri, 20 Sep 2024 11:54:29 +0300</pubDate>
      
      <guid>https://4rkal.com/posts/django-prod/</guid>
      <description>In this article I will show you how to deploy django to production. We will be using nginx, gunicorn and cloudflare tunnels</description>
      <content:encoded><![CDATA[<p>I recently deployed my very own django application to production. The website is called <a href="https://videiro.com">videiro.com</a> and was developed in django + HTML/CSS/JS + Tailwind.</p>
<h2 id="setup">Setup</h2>
<p>I am using a debian 12 server which will expose my application via cloudflare tunnels. All of the static files are being served via nginx and the Django project is being ran by gunicorn.</p>
<p>In this guide I will show you how I set this up.</p>
<h2 id="preparing-the-django-project">Preparing the Django project</h2>
<p>The first thing you will have to do is open the settings.py and change the following</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span>Debug <span style="color:#f92672">=</span> <span style="color:#66d9ef">False</span>
</span></span><span style="display:flex;"><span>ALLOWED_HOSTS <span style="color:#f92672">=</span> [<span style="color:#e6db74">&#39;yourdomain.tld&#39;</span>]
</span></span><span style="display:flex;"><span>CSRF_COOKIE_SECURE <span style="color:#f92672">=</span> <span style="color:#66d9ef">True</span>
</span></span><span style="display:flex;"><span>CSRF_TRUSTED_ORIGINS <span style="color:#f92672">=</span> [
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#39;yourdomain.tld&#39;</span>,
</span></span><span style="display:flex;"><span>]
</span></span></code></pre></div><p>You should also change the <code>SECRET_KEY</code> to a long random string, that you should never share with anyone.</p>
<p>After that create a new file called <code>.gitignore</code> and paste the following:</p>
<pre tabindex="0"><code class="language-gitignore" data-lang="gitignore">db.sqlite3
*.pyc
</code></pre><p>This will make sure that the database is not uploaded to our server and that no pyc files are either.</p>
<p>Now you can upload your project to a new github repository (or gitea repository). If you don&rsquo;t want everyone to have access to your source code make sure to set the repository as private.</p>
<p>If you want to make sure that your source code stays private I recommend you setup a selfhosted gitea instance, read  <a href="https://4rkal.com/posts/gitea/">Selfhost your own gitea instance - selfhosted, lightweight github alternative</a>, to learn how to do that.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>git init
</span></span><span style="display:flex;"><span>git branch -M main
</span></span><span style="display:flex;"><span>git add .
</span></span><span style="display:flex;"><span>git commit -m <span style="color:#e6db74">&#34;initial commit&#34;</span>
</span></span><span style="display:flex;"><span>git remote add origin https://...
</span></span><span style="display:flex;"><span>git push -u origin main
</span></span></code></pre></div><p>Now that you we have done that you should login to your server</p>
<h2 id="server-setup">Server setup</h2>
<p>Before configuring anything make sure that you don&rsquo;t allow any ssh logins with a password. Follow <a href="https://4rkal.com/posts/sssh/">Securing ssh with Key-Based authentication</a> to secure your server from those kinds of attacks.</p>
<p>Login to your server</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>ssh user@server.ip
</span></span></code></pre></div><p>Make sure that your packages are up to data</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>sudo apt update <span style="color:#f92672">&amp;&amp;</span> sudo apt upgrade
</span></span></code></pre></div><p>Now install python, pip, git and nginx</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>sudo apt install python3 python3-pip git nginx
</span></span></code></pre></div><p>Now clone your project into your home directory.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>git clone https://...
</span></span><span style="display:flex;"><span>cd my-project
</span></span></code></pre></div><p>Once you&rsquo;re in install the following:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>pip install django django-crispy-forms 
</span></span></code></pre></div><p>Now try to run the project:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>python3 manage.py runserver
</span></span></code></pre></div><p>if you get an error that a package is missing install it and re run.</p>
<h2 id="configuring-gunicorn">Configuring gunicorn</h2>
<p>Now we will setup gunicorn</p>
<p>First install it</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>pip install gunicorn
</span></span></code></pre></div><p>Now create a new file called gunicorn.service with your favorite text editor:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>sudo vim /etc/systemd/system/gunicorn.service
</span></span></code></pre></div><p>And paste the following:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span><span style="color:#f92672">[</span>Unit<span style="color:#f92672">]</span>
</span></span><span style="display:flex;"><span>Description<span style="color:#f92672">=</span>gunicorn daemon
</span></span><span style="display:flex;"><span>After<span style="color:#f92672">=</span>network.target
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">[</span>Service<span style="color:#f92672">]</span>
</span></span><span style="display:flex;"><span>User<span style="color:#f92672">=</span>YOURUSER
</span></span><span style="display:flex;"><span>Group<span style="color:#f92672">=</span>www-data
</span></span><span style="display:flex;"><span>WorkingDirectory<span style="color:#f92672">=</span>/home/YOURUSER/PROJECT
</span></span><span style="display:flex;"><span>ExecStart<span style="color:#f92672">=</span>/path/to/gunicorn --access-logfile - --workers <span style="color:#ae81ff">3</span> --bind 127.0.0.1:8000 PROJECTNAME.wsgi:application
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">[</span>Install<span style="color:#f92672">]</span>
</span></span><span style="display:flex;"><span>WantedBy<span style="color:#f92672">=</span>multi-user.target
</span></span></code></pre></div><p>Change <code>YOURUSER</code> to your user.</p>
<p>To find the path to <code>gunicorn</code> run:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>which gunicorn
</span></span></code></pre></div><p>And your project name is the name of the folder inside of your project that contains the <code>settings.py</code> file.</p>
<p>Now run the following commands to start and enable gunicorn (start on boot)</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>sudo systemctl daemon-reload
</span></span><span style="display:flex;"><span>sudo systemctl start gunicorn.service
</span></span><span style="display:flex;"><span>sudo systemctl enable gunicorn.service
</span></span></code></pre></div><p>Now if you head to 127.0.0.1:8000 you should see your project running.</p>
<p>But were not finished yet</p>
<h2 id="setting-up-nginx">Setting up nginx</h2>
<p>Now we need to serve our static content via nginx.</p>
<p>First create a new file nginx configuration file with your favorite text editor:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>sudo vim /etc/nginx/sites-available/PROJECT
</span></span></code></pre></div><p>Change PROJECT to whatever you want</p>
<p>Now paste the following content:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-nginx" data-lang="nginx"><span style="display:flex;"><span><span style="color:#66d9ef">server</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">listen</span> <span style="color:#ae81ff">80</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">server_name</span> <span style="color:#e6db74">YOURDOMAIN</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">location</span> <span style="color:#e6db74">/static/</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#f92672">alias</span> <span style="color:#e6db74">/var/www/staticfiles/</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">location</span> <span style="color:#e6db74">/</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">proxy_pass</span> <span style="color:#e6db74">http://127.0.0.1:8000</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">proxy_set_header</span> <span style="color:#e6db74">Host</span> $host;
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">proxy_set_header</span> <span style="color:#e6db74">X-Real-IP</span> $remote_addr;
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">proxy_set_header</span> <span style="color:#e6db74">X-Forwarded-For</span> $proxy_add_x_forwarded_for;
</span></span><span style="display:flex;"><span>        <span style="color:#f92672">proxy_set_header</span> <span style="color:#e6db74">X-Forwarded-Proto</span> $scheme;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Just change YOURDOMAIN to the domain that this will be hosted on.</p>
<p>Create a symbolic link to enable your website:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>sudo ln -s /etc/nginx/sites-available/PROJECT /etc/nginx/sites-enabled/
</span></span></code></pre></div><p>Start and enable nginx:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>sudo systemctl start nginx
</span></span><span style="display:flex;"><span>sudo systemctl enable nginx
</span></span></code></pre></div><h2 id="setup-static-files">Setup static files</h2>
<p>The first thing you will have to do is cd into your (django) project</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>cd project
</span></span></code></pre></div><p>Now run the following command:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>python3 manage.py collectstatic
</span></span></code></pre></div><p>This will create a new folder called <code>staticfiles</code></p>
<p>Now to set up the static files we have two options:</p>
<ol>
<li>Change the user in  <code>/etc/nginx/nginx.conf</code> to your user (less secure)</li>
<li>Copy over the staticfiles to <code>/var/www/</code> (more secure)</li>
</ol>
<p>I will be doing the 2nd option:</p>
<p>First create a new file called staticfiles in /var/www</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>sudo mkdir -p /var/www/staticfiles
</span></span></code></pre></div><p>Now copy over all of the staticfiles from your project there:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>sudo cp staticfiles/* /var/www/staticfiles
</span></span></code></pre></div><p>Now cd into /var/www</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>cd /var/www
</span></span></code></pre></div><p>Change the ownership of all the files</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>sudo chown www-data:www-data staticfiles
</span></span><span style="display:flex;"><span>sudo chown www-data:www-data staticfiles/*
</span></span></code></pre></div><p>Restart the nginx service:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>sudo systemctl restart nginx
</span></span></code></pre></div><p>Now if you head to:</p>
<p><code>127.0.0.1</code></p>
<p>You should see your website running with all of the static files being served!</p>
<h2 id="exposing-via-cloudflare-tunnels">Exposing via cloudflare tunnels</h2>
<p>Now to make your website publicly accessible.</p>
<p>To do this you will need a cloudflare account and a domain pointed to cloudflare.</p>
<p>First head to the <a href="https://one.dash.cloudflare.com/">Zero Trust Dashboard</a></p>
<p>Under <code>Networks</code> click on <code>Tunnels</code> and then <code>Create a tunnel</code></p>
<p>Once created you should <code>Install and run a connector</code>, follow the instructions on the page for your specific setup.</p>
<p>After the connector is running you should click on the <code>Public Hostname</code> tab and <code>Add a public hostname</code>.</p>
<p>Now you should see something like this:
<img loading="lazy" src="/../assets/gitea2.png" type="" alt="Cloudflare dashboard"  /></p>
<p>Fill in the info as I have.
The service type should be <code>HTTP</code> and the url should be <code>127.0.0.1:80</code> or <code>localhost:80</code></p>
<p>Now if you head to the domain that you specified you should see your app up and running.</p>
<p>Congratulations!</p>
<p><strong>If you enjoyed this post and want to support my (mostly unpaid) work , you can <a href="https://4rkal.com/donate">donate here</a>.</strong></p>
<h2 id="join-my-free-newsletter">Join my free newsletter!</h2>
<div style="text-align: left; margin: 0 auto;">
    <form method="post" action="https://newsletter.4rkal.com/subscription/form" style="background: #2c2c2c; color: #f0f0f0; border-radius: 8px; padding: 15px; max-width: 500px; box-shadow: 0 3px 6px rgba(0, 0, 0, 0.2); font-family: Arial, sans-serif;">
        <div style="display: flex; flex-direction: column; gap: 10px;">
            <h3 style="margin: 0; color: #f0f0f0; font-size: 18px;">Subscribe</h3>
            <input type="hidden" name="nonce"/>
            <input type="email" name="email" required placeholder="E-mail" style="width: 100%; padding: 10px; border: 1px solid #666; border-radius: 4px; background: #333; color: #f0f0f0; box-sizing: border-box;"/>
            <div style="display: flex; flex-direction: column; gap: 8px;">
                <label style="margin: 0; color: #f0f0f0; display: none;">
                    <input id="78a75" type="checkbox" name="l" checked value="78a75b30-472d-4790-a5d5-7f2ed49662a4" style="accent-color: #fff;"/>
                    Weekly Roundup
                </label>
                <span style="color: #d0d0d0; display: none;">Where I share what I’ve been up to that week, including articles I’ve published, cool finds, tips and tricks, and more!</span>
                <label style="margin: 0; color: #f0f0f0; display: none;">
                    <input id="b3964" type="checkbox" name="l" checked value="b3964560-37b0-43d3-9df9-26589fd6bf8d" style="accent-color: #fff;"/>
                    New Posts
                </label>
                <span style="color: #d0d0d0; display: none;">Receive an email every time I post something new on my blog</span>
            </div>
            <input type="submit" value="Subscribe" style="width: 100%; padding: 10px; border: none; border-radius: 4px; background: #fff; color: #007bff; font-size: 14px; cursor: pointer; transition: background-color 0.3s ease, box-shadow 0.3s ease; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);"/>
        </div>
        <p style="text-align: center; margin-top: 10px; color: #d0d0d0; font-size: 10px; margin-bottom:0px;">
            No spam, no ads. Unsubscribe at any time.
        </p>
    </form>
</div>]]></content:encoded>
    </item>
    
    <item>
      <title>Python for Complete Beginners</title>
      <link>https://4rkal.com/posts/python/</link>
      <pubDate>Mon, 06 Mar 2023 20:52:42 +0300</pubDate>
      
      <guid>https://4rkal.com/posts/python/</guid>
      <description>Why you should use Python. Going over the basics of Python.
In this course/article I will be talking about why someone should use Python. Later on, I will be tackling the basics of Python. But let&amp;rsquo;s start by explaining what coding is.
What is coding? Coding means writing instructions for computers and a finished set of instructions is known as a program. Computer programs control everything from smartphones to space rockets.</description>
      <content:encoded><![CDATA[<p>Why you should use Python. Going over the basics of Python.</p>
<p>In this course/article I will be talking about why someone should use Python. Later on, I will be tackling the basics of Python. But let&rsquo;s start by explaining what coding is.</p>
<h2 id="what-is-coding">What is coding?</h2>
<p>Coding means writing instructions for computers and a finished set of instructions is known as a program. Computer programs control everything from smartphones to space rockets.</p>
<h2 id="what-is-python">What is Python?</h2>
<p>Python is a text-based computer language which means it’s made up of words and symbols (such as * and = ). Its language elements and object-oriented approach are meant to assist programmers in writing clear, logical code for both small and large-scale projects.</p>
<h2 id="why-python">Why Python?</h2>
<p>Python is one of the most popular computer languages and it’s very concise — that is, you don&rsquo;t need to type much in order to create programs that do a lot.</p>
<h2 id="advantages-of-python">Advantages of python</h2>
<ol>
<li>Simple to read, learn, and write</li>
</ol>
<p>Python is a high-level programming language with a syntax that is similar to English. This makes the code easier to read and comprehend.</p>
<p>Python is really simple to pick up and understand, which is why many people suggest it to newcomers. When compared to other prominent languages like C/C++ and Java, you require fewer lines of code to accomplish the same purpose.</p>
<ol start="2">
<li>Improved Productivity</li>
</ol>
<p>Python is an extremely useful programming language. Python’s simplicity allows developers to concentrate on solving the problem.</p>
<p>They don’t need to spend a lot of time learning the programming language’s syntax or behaviour. You write less code and accomplish more.</p>
<ol start="3">
<li>Free and Open-Source</li>
</ol>
<p>Python comes under the OSI-approved open-source license. As a result, it is both free to use and distribute. You can get the source code, change it, and even share your own Python version.</p>
<ol start="4">
<li>Portability</li>
</ol>
<p>In many languages like C/C++, you need to change your code to run the program on different platforms. With Python, however, this is not the case. You only have to write it once and it may be used wherever.</p>
<h2 id="downloading-python">Downloading Python</h2>
<p><strong>On Linux</strong>
You probably already know how to install it but I&rsquo;m gonna show it anyways.</p>
<p>Open your terminal and type python or python3; if it does not work then run: (depending on your distro)
<code>sudo apt install python3</code></p>
<p><strong>Windows 10</strong>
1 . First check if you already have Python installed. Go to the ‘Start’ menu and click on the ‘All programs’. If you see the word “Python” it means that you already have it installed. If you don&rsquo;t already have it installed go to <a href="https://python.org">https://python.org</a>, download the correct version for your computer and then install it.</p>
<ol start="2">
<li>Python comes in different versions. This course uses version 3 and upwards. I recommend always installing the latest version.</li>
</ol>
<h2 id="what-is-an-ide">What is an IDE?</h2>
<p>IDE stands for the integrated development environment (IDE) and is software for building applications that combine common developer tools into a single Graphical User Interface (GUI).</p>
<p>The IDE that we will be using in this series is called VS Code.</p>
<h2 id="downloading-vs-code">Downloading VS Code</h2>
<p>Go to <a href="https://code.visualstudio.com/">https://code.visualstudio.com/</a> and download the version that you want. Vs Code is available for Windows, Mac, and Linux. Follow the instructions on the website for installation.</p>
<h2 id="starting-in-python">Starting in Python</h2>
<p>It&rsquo;s traditional in the programming world to make the computer say ‘Hello World’ with your very first piece of code. In Python, this is very simple.</p>
<ol>
<li>Open Vs Code and click on File &gt; New File and name your file helloworld.py. The .py tells the computer that this is a Python program.</li>
<li>In your project, in VS Code type :
<code>print(&quot;Hello World!&quot;)</code></li>
<li>Save your project and click on the run button at the top of your screen</li>
<li>If you have done everything correctly you should see a Hello World message in your terminal.</li>
</ol>
<p>If it didn&rsquo;t work you should get a red error message something like this:</p>
<p><code>SyntaxError: invalid syntax</code></p>
<p>If that happens make sure that you have copied it exactly like above.</p>
<h2 id="playing-with-numbers-in-python">Playing With numbers in Python</h2>
<p>Python makes it easy to do maths. You just type in a question and get the answer</p>
<p><strong>Adding Up</strong></p>
<p>Open an empty project and type:</p>
<p><code>print(2+2)</code></p>
<p>You should see the answer:
<code>4</code></p>
<p><strong>Subtracting(and more)</strong>
If you want to subtract, use the ‘-’ symbol like this:</p>
<p><code>print(2 - 2)</code></p>
<p>To multiply use the ‘*’ symbol:</p>
<p><code>print(2 * 2)</code></p>
<p>To divide, use the ‘/’ symbol</p>
<p><code>print(2 / 2)</code></p>
<h2 id="variables">Variables</h2>
<p>A variable is like a labelled box that stores information. You can change this information but the label stays the same.</p>
<h2 id="creating-a-variable">Creating a variable:</h2>
<p>To tell the computer what you want your variable to be, you use the = sign. This is called assigning a value to a variable. It’s very simple, here&rsquo;s an example using fish.</p>
<ol>
<li>Open a new VS Code project and type:
<code>fish = 5</code></li>
</ol>
<p>Imagine a cat gets hungry and eats two fish. To create another variable for the amount eaten, write the following:</p>
<p><code>fishEaten = 2</code></p>
<p>Press enter and then type:</p>
<p><code>print(fish - fishEaten)</code></p>
<p>Save and run your code and you should get the answer:
<code>3</code></p>
<h2 id="input-in-python">Input in Python</h2>
<p>You can use the input() function to ask for information from the user.</p>
<ol>
<li>Open a new VS Code project and type:</li>
</ol>
<p><code>name = input(&quot;What is your name? &quot;)</code></p>
<ol start="2">
<li>Run the program and you should get the following message:</li>
</ol>
<p><code>What is your name? </code>
3. Now let&rsquo;s try printing your name.</p>
<p>Add the following to your program:</p>
<p><code>print(name)</code></p>
<p>You have successfully created an input field!</p>
<p>This can be very useful in creating decision games.</p>
<h2 id="making-decisions">Making Decisions</h2>
<p>To write a program that allows you to make decisions the computer needs to react differently to different answers. For this, you need conditions to compare pieces of information, and conditionals to create different paths through the program.</p>
<h2 id="what-are-conditions">What are Conditions?</h2>
<p>A condition is a bit of code that compares two pieces of information. Conditions use operators to make these comparisons. For example, the operator == checks if two pieces of information are the same.</p>
<ol>
<li>Open a new Vs Code project and type:</li>
</ol>
<pre tabindex="0"><code>age = 10
if age == 12:
 print(&#34;True&#34;)
else:
 print(&#34;False&#34;)
</code></pre><ol start="2">
<li>Save and run and you should get False</li>
</ol>
<p>That is because ‘age’ is set to 10 and not 12</p>
<h2 id="what-are-conditionals">What are conditionals</h2>
<p>To use a condition in your code you need a command called a condition. Conditionals use conditions. Conditions show if something is True or False.</p>
<h2 id="if">IF</h2>
<p>One important condition is known as an if statement which tests whether a condition is true. If it is, the computer will follow the instructions after the if statement. If not, the computer will just skip it. In Python, if is a keyword. Dont use it as a variable name because the computer will think that it&rsquo;s an if statement and get confused.</p>
<h2 id="implementing-the-if-condition">Implementing the if condition</h2>
<ol>
<li>Create a new VS Code project and type the following:</li>
</ol>
<p><code>user_reply = (&quot;Do you like python? (Type yes or no) &quot;)</code></p>
<ol start="2">
<li>Then we will implement the if condition by typing the following:</li>
</ol>
<pre tabindex="0"><code>if user_reply == &#34;yes&#34;
   print(&#34;Python likes you to ! &#34;)
</code></pre><h2 id="elif">ELIF</h2>
<p>elif is short for else if. If the conditions of the if code isn’t met it “sweeps up” whatever is left.</p>
<ol start="3">
<li>Now type the following:</li>
</ol>
<pre tabindex="0"><code>elif user_reply == &#34;maybe&#34;:
  print(&#34;Make up your mind!&#34;)
</code></pre><h2 id="else">ELSE</h2>
<p>When conditions for the if and elif code arent met, else goes into action and “sweeps up” whatever is left.</p>
<p>Let&rsquo;s implement that:
4. Now type the following:</p>
<pre tabindex="0"><code>else:
  print(&#34;Well python doesn&#39;t like you either&#34;)
</code></pre><p>The complete code should look something like this:</p>
<pre tabindex="0"><code>user_reply = (&#34;Do you like python? (Type yes or no) &#34;)
if user_reply == &#34;yes&#34;
   print(&#34;Python likes you to ! &#34;)
elif user_reply == &#34;maybe&#34;:
  print(&#34;Make up your mind!&#34;)
else:
  print(&#34;Well python doesn&#39;t like you either&#34;)
</code></pre><p><strong>Don&rsquo;t forget to press the tab after if statements.</strong></p>
<h2 id="randomness-in-python">Randomness in python</h2>
<p>In python we can use the random function in order to generate random numbers. This can be extremely useful in a variety of things.</p>
<p>The first thing we will have to do is import the random function</p>
<p><code>import random</code></p>
<p>After that we can print out a random number with the following</p>
<p><code>print(random.randint(1,10))</code></p>
<p>This will output a random number from 1–10</p>
<p>randint stands for random integer.</p>
<p>Here is the full code.</p>
<pre tabindex="0"><code>import random
print(random.randint(1,10))
</code></pre><h2 id="loops-in-python">Loops in python</h2>
<p>There are two types of loops in python</p>
<ol>
<li>While loop</li>
<li>For loop</li>
</ol>
<p>While loops only stop when something changes. If it doesn&rsquo;t change they could go on forever.</p>
<p>With for loops on the other hand you can define exactly when you want them to stop</p>
<p>The most popular example of a while loop is</p>
<p><code>while True:</code></p>
<p>Which will run forever eg</p>
<pre tabindex="0"><code>while True:
    print(&#34;hi&#34;)
</code></pre><p>This will run forever.</p>
<p>With while loops on the other hand you can define exactly how many times you want the loop to run.</p>
<pre tabindex="0"><code>for x in range(0,10):
   print(&#34;Hi&#34;)
</code></pre><p>This will print Hi exactly 10 times</p>
<h2 id="guessing-game">Guessing game</h2>
<p>Now lets combine what learned from above and from our previous articles to create a game</p>
<p>The computer will select a random number from 1–10 and you will have to guess it.</p>
<p>The first thing we will have to do is</p>
<p><code>import random</code></p>
<p>After that we will create a variable called number</p>
<p><code>number = random.randint(1,10)</code></p>
<p>After that we will create another variable called your_guess</p>
<p><code>your_guess = int(input(&quot;Im thinking of a number from 1 to 10, can you guess which one?&quot;))</code></p>
<p>We are using int as you will have to enter a number</p>
<p>Now we will create a while loop that will keep the game running until you guess the number</p>
<p><code>while your_guess != number:</code></p>
<p>The code so far is</p>
<pre tabindex="0"><code>import random
number = random.randint(1,10)
your_guess = int(input(&#34;Im thinking of a number from 1 to 10, can you guess which one?&#34;))
while your_guess != number:
    if your_guess &lt; number:
        print(&#34;Your number was too low&#34;)
    else:
        print(&#34;You number was to high&#34;)
</code></pre><p>And the following</p>
<p><code>print(&quot;GG you found it&quot;)</code></p>
<p>You code should now look like this</p>
<pre tabindex="0"><code>import random
number = random.randint(1,10)
your_guess = int(input(&#34;Im thinking of a number from 1 to 10, can you guess which one?&#34;))
while your_guess != number:
    if your_guess &lt; number:
        print(&#34;Your number was too low&#34;)
    else:
        print(&#34;You number was to high&#34;)
    your_guess = int(input(&#34;Please try again... &#34;))
print(&#34;GG you found it&#34;)
</code></pre><p><strong>Thats it for now</strong></p>
<p>Stay tuned for more</p>
<p><em><strong>If you enjoyed this article consider <a href="../../donate">supporting me</a></strong></em></p>
]]></content:encoded>
    </item>
    
    <item>
      <title>Automating your web browser with selenium</title>
      <link>https://4rkal.com/posts/selenium/</link>
      <pubDate>Wed, 22 Feb 2023 21:23:38 +0300</pubDate>
      
      <guid>https://4rkal.com/posts/selenium/</guid>
      <description>Selenium is a very good skill to have as you can automate almost everything that you can do with a web browser.
In this tutorial, we’ll learn how to use Python and Selenium to automate a web browser. This is an updated version of my previous article which unfortunately doesn&amp;rsquo;t work anymore. If you’re a complete beginner, read my python article to understand the basics. (https://4rkal.com/posts/python/)
What is selenium? Selenium is an open source umbrella project for a range of tools and libraries aimed at supporting browser automation.</description>
      <content:encoded><![CDATA[<p><strong>Selenium is a very good skill to have as you can automate almost everything that you can do with a web browser.</strong></p>
<p>In this tutorial, we’ll learn how to use Python and Selenium to automate a web browser. This is an updated version of my previous article which unfortunately doesn&rsquo;t work anymore. If you’re a complete beginner, read my python article to understand the basics. (<a href="https://4rkal.com/posts/python/">https://4rkal.com/posts/python/</a>)</p>
<h2 id="what-is-selenium">What is selenium?</h2>
<p>Selenium is an open source umbrella project for a range of tools and libraries aimed at supporting browser automation. You can use selenium in multiple programming languages including JavaScript (Node.js), C#, Groovy, Java, Perl, PHP, Python, Ruby and Scala and with multiple web browsers including firefox, internet explorer, safary, opera, chrome and edge. Selenium can be very useful for web scraping, automating boring and manual tasks and so much more.</p>
<h2 id="setup">Setup</h2>
<p>To install selenium you first have to install a browser driver. Here is the list of supported web browsers :</p>
<ul>
<li>Firefox</li>
<li>Internet Explorer?</li>
<li>Safari</li>
<li>Opera</li>
<li>Chrome</li>
<li>Edge
In this article we will be using firefox geckodriver. But you can use any of the browser drivers above.</li>
</ul>
<h2 id="downloading-geckodriver">Downloading geckodriver</h2>
<p>To get started go to github.com/mozilla/geckodriver/releases
Scroll down and select the package for your computer.
I’ll use geckodriver-v0.31.0-linux64.tar.gz because I’m using a linux 64-bit computer.</p>
<h2 id="installing-geckodriver">Installing geckodriver</h2>
<p>The setup varies depending on your operating system.</p>
<p>If you are using Arch Linux:
You can install geckodriver from the aur. Using your favourite aur helper</p>
<p>On linux:</p>
<ol>
<li>Unzip the file</li>
<li>Make the file executable
<code>chmod +x geckodriver</code></li>
<li>Add the driver to your PATH so other tools can find it:
<code>export PATH=$PATH:/path-to-extracted-file/</code>
On windows:</li>
<li>Unzip the file</li>
<li>Paste the file in the directory that your script will run</li>
</ol>
<h2 id="installing-selenium">Installing selenium</h2>
<p>To install selenium you have to have python and pip installed.Check out my article on python for <a href="https://4rkal.com/posts/python">more</a>
To install selenium open your cmd or terminal and type:<br>
<code>pip install selenium</code>
That should install it.\</p>
<h2 id="basics-of-selenium">Basics of selenium</h2>
<p>The first thing we have to do is to create a new file with the .py ending eg. main.py<br>
After you have created it open it in your ide or editor of choice.\</p>
<p>The first thing that we have to do is to import the selenium webdriver :
<code> from selenium import webdriver</code><br>
After that we have to specify what webdriver we are using. In our case its firefox
<code> browser = webdriver.Firefox()</code><br>
Now we need to specify the url that we want it to go to eg python.org</p>
<pre tabindex="0"><code>browser.get(&#39;https://python.org&#39;)
The full code so far is:\
import selenium
from selenium import webdriver
browser = webdriver.Firefox()
browser.get(&#39;https://python.org&#39;)
</code></pre><p>Now we might want it to click on the Downloads button</p>
<p>There are a few ways to do this</p>
<h2 id="method-1-of-clicking-a-button">Method 1 of clicking a button</h2>
<p>The first is with XPATH<br>
To find the xpath of a button / object on a website you have to open your web browser go to the desired website and hit F12 to get the development tools. Now you should click on the select tool (See below)
<img loading="lazy" src="/../assets/inspect.png" type="" alt="Inspect element"  />
Click on it and after that hover above the downloads button with your mouse and click it. After that you should see a bit of code getting highlighted. Right click on the bit of code and select Copy then select Xpath
<img loading="lazy" src="/../assets/copy.png" type="" alt="1"  />
Now go back to the python file and type:<br>
<code>driver.find_element(By.XPATH, 'XPATH_HERE')</code><br>
This will throw an error, to fix that error simply add this at the top of the file<br>
<code> from selenium.webdriver.common.by import By</code><br>
Your code so far should look like this</p>
<pre tabindex="0"><code>import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
browser = webdriver.Firefox()
browser.get(&#39;https://python.org&#39;)
browser.find_element(By.XPATH, &#39;/html/body/div/header/div/nav/ul/li[2]/a&#39;).click()
</code></pre><h2 id="method-2">Method 2</h2>
<p>XPATH with text
The second method is a bit simpler but not as reliable as the first as there might be many objects with the same name.<br>
To use this method type:
<code>browser.find_element(By.XPATH, &quot;//*[contains(text(), 'Downloads')]&quot;).click()</code>
Your code should look something like this</p>
<pre tabindex="0"><code>import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
browser = webdriver.Firefox()
browser.get(&#39;https://python.org&#39;)
browser.find_element(By.XPATH, &#34;//*[contains(text(), &#39;Downloads&#39;)]&#34;).click()
</code></pre><p>. . . . .</p>
<p>There many methods on how to locate elements but the above i believe are the easiest.
The methods are the following</p>
<ul>
<li>By.ID</li>
<li>By.NAME</li>
<li>By.XPATH</li>
<li>By.LINK-TEXT</li>
<li>By.TAG_NAME</li>
<li>By.CLASS_NAME</li>
<li>By.CSS_SELECTOR\</li>
</ul>
<p>Read more here: <a href="https://selenium-python.readthedocs.io/locating-elements.html">https://selenium-python.readthedocs.io/locating-elements.html</a></p>
<h2 id="typing-text-into-input-fields">Typing text into input fields.</h2>
<p>Typing text into input fields is pretty straight forward.<br>
For that we will use any of the above methods. I&rsquo;m going to use xpath.<br>
Find the xpath of any input field, I&rsquo;m going to use the google.com search field<br>
Copy the xpath and type:<br>
<code>a = browser.find_element(By.XPATH, &quot;XPATH_HERE&quot;)</code>
Paste the xpath in XPATH_HERE</p>
<p>To send keys we need to import the selenium.webdriver.common.keys library for that paste this line of code at the top of your file<br>
<code>from selenium.webdriver.common.keys import Keys</code><br>
Now type:<br>
<code>a.send_keys(&quot;python&quot;)</code><br>
After that we want to press the enter key for that type:<br>
<code>a.send_keys(Keys.RETURN)</code><br>
The full code should look something like this:</p>
<pre tabindex="0"><code>import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox()
browser.get(&#39;https://google.com&#39;)
a = browser.find_element(By.XPATH, &#34;/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input&#34;)
a.send_keys(&#34;python&#34;)
a.send_keys(Keys.RETURN)
</code></pre><p>GG you just automated your first google search!
You might first need to accept cookies for that just follow the steps on how to click a button from above.<br>
Read more about selenium here: <a href="https://selenium-python.readthedocs.io/">https://selenium-python.readthedocs.io/</a>\</p>
<p>*<strong>If you enjoyed this article consider <a href="../../donate">supporting me</a></strong></p>
]]></content:encoded>
    </item>
    
  </channel>
</rss>
