Deploy Flask App On Pythonanywhere

In today’s blog, we are going to Deploy a Flask app online using Pythonanywhere. The app we are going to deploy will be a sketch-making Flask app that we created in the previous blog.

This is going to be a very interesting project because learning how to deploy an app online is a very important skill nowadays. So without any further due, let’s do it…

Deploy a Flask web app on PythonAnywhere
  1. Make sure you have signed up for a free PythonAnywhere account, and you’re logged in.
  2. Go to the Web menu item and then press the Add new web app button.
  3. Click Next, then click on Flask and click on the latest version of Python that you see there.

Cloning the application to the PythonAnywhere console

Next, clone the application from GitHub to the PythonAnywhere console. This is an important step because it also sets up the remote push and pull GitHub links that we will later on use to pull changes from GitHub. Run this command on the console:

git clone https://github.com/mwaz/automating-flask-deployments-with-pythonanywhere.git

Change directory: cd automating-flask-deployments-with-pythonanywhere Install pipenv package manager using: pip install pipenv

Install all dependencies with: pipenv install

After cloning the Flask application, you need to tell PythonAnywhere where your project is located. To do this, configure the location using the Web tab. Without closing the bash console (on the hamburger menu at the far right), open the Web tab and set the source code path for the project, the virtual environment path, and the static files, including the Swagger UI YAML file.

Set the source code path to: /home//

After creating the virtual environment, you can open the console with it. For now you can ignore this option.

Note: To get the working directory path, use the bash $pwd command to find the parent directory.

Congratulations! Your Flask project has been set up and successfully hosted on PythonAnywhere. Open the link to your web application to review the default PythonAnywhere screen.

Great work so far, but there are still a few more steps to go.

The page for your application displays PythonAnywhere’s default welcome message. To open your Flask application, you need to make a few changes to the PythonAnywhere’s config file.

Open the WSGI configuration file from the dashboard and modify the configuration.

WSGI (Web Server Gateway Interface) is a Python interface to the web server. It allows you to write Python code that can be run on the server and is used to configure the web server. With WSGI you can forward requests from a web server to the Flask backend and from the web server back to the requestor.

To enable execution of your Flask application, remove the hello world code in the config file.

Also, configure the path to your project directory and the entry point of your application:

Save the changes and close the file. Next, you need to reload the app and append the suffix api-docs to the URL. That loads your Flask Swagger documentation page.

You have successfully deployed your Flask application to PythonAnywhere.

Next you will need to configure your application to be automatically deployed by CircleCI every time you make deployments to the main branch.

To set up CI/CD in this project, use ssh to connect to the PythonAnywhere server. This ensures that once CircleCI executes, you can pull the latest changes from the main GitHub branch if the pipeline run was successful.

Note: SSH also known as Secure Shell or Secure Socket Shell, is a network protocol for operating network services to securely connect over an unsecure network. Applications of ssh include; remote command-line login and remote command execution.

The following diagram shows how CI/CD is applied with CircleCI and PythonAnywhere using ssh.

The illustration shows that when you push your code to GitHub, it kick starts a process to deploy the code to PythonAnywhere. Once the deployment is complete, you can then connect to the PythonAnywhere server and pull the latest code from the main branch. Now that you know how it works, your next step is to write a CircleCI configuration file to achieve it.

To set up any project in CircleCI, start on the CircleCI dashboard. Go to the Projects section. All the GitHub repositories associated with your GitHub username or organization are listed. For this tutorial, the repository you want to set up is automating-flask-deployments-with-pythonanywhere.

On the Projects dashboard, select the option to set up the selected project. Select the option for using an existing configuration. The first configuration step is complete.

Note: This is not a mandatory step if you have already cloned this repository, but is an important one for you to learn how you would set it up in your own project.

First, create a .circleci directory in your root directory and add a config.yml file. The config file will contain the CircleCI configuration for every project. When this has been set up, you can use CircleCI orbs in the configuration to execute your Python API tests.

Your CircleCI configuration file will execute your tests and deploy your application to PythonAnywhere. In the .circleci/config.yaml file, enter:

In this CircleCI configuration, you are creating two jobs. The first job is a build job responsible for installing the dependencies and running the tests. The deploy job is responsible only for deploying the application to PythonAnywhere. Running the build and test job followed by the deploy job ensures deployment happens only after successful tests.

After the tests pass, you can deploy your application to PythonAnywhere using the deploy job. To allow deployment of the application you need to generate SSH keys in your PythonAnywhere account, and then add that private key to your GitHub account.

You do not want to always use a password to connect to PythonAnywhere. To allow connection to PythonAnywhere without entering a password every time, you can generate SSH keys on the PythonAnywhere console. From the PythonAnywhere console, run this command:

You will be prompted to enter a passphrase for additional security. You can add this or leave it blank.

Great! You have generated your keys. Now you can use them in CircleCI to automatically connect to PythonAnywhere. I will cover that in the next section.

First though, you need PythonAnywhere to know that your public key is an authorized key. Add the public key to ~/.ssh/authorized_keys in PythonAnywhere’s console using this command:

You will be prompted to enter your password. Once authorized, you can connect to PythonAnywhere without having to use a password ever again. Cool right? Test by running this command in the PythonAnywhere console:

This command should log you into the PythonAnywhere server from the console without entering a password. Your next step is adding SSH keys to CircleCI.

Following steps in the previous section you were able to generate both the private and public keys for the PythonAnywhere account. Now you can copy your private key to CircleCI.

To avoid adding overhead to the server, you can just display the private key and then copy it to the clipboard. In the PythonAnywhere console, enter this command:

Once you have your private key copied to the clipboard, navigate to the CircleCI project settings for your project and add the private key there.

The basic setup for deployment to CircleCI is complete. Go back to the Deploy Over SSH configuration step in your CircleCI config.yml file. Use the keyscan step ssh-keyscan -H ssh.pythonanywhere.com >> ~/.ssh/known_hosts. This fetches the SSH keys for your PythonAnywhere account and adds them to the runners ~/.ssh/known_hosts file of your deploy job.

Then authenticate using SSH and pull the code from GitHub with this command:

Note that we are using the $SSH_USER and $SSH_HOST variables to do the authentication while at the same time masking the SSH user and hostname. We did this by adding SSH_USER and SSH_HOST to the CircleCI Settings page under the Environment variables. You can read more about adding variables here .

The SSH_HOST to access PythonAnywhere via SSH is ssh.pythonanywhere.com. SSH_USER is the username of your PythonAnywhere account.

You should now be able to deploy your application to PythonAnywhere using CircleCI.

As described previously, the deploy job is run after the build-and-test job. This is because the deploy job requires the build and test job to pass and will fail if the build-and-test job fails.

To verify that your application is successfully deployed to PythonAnywhere, you need to manually reload using the PythonAnywhere dashboard. You can avoid this step by creating a bash script inside the PythonAnywhere account. The script automatically reloads the application after a deployment. Call this script reload.sh, and add the command to either recreate or update the _pythonanywhere_com_wsgi.py file. This command controls reloading the application.

After you add the script to reload.sh in root folder, make it executable using the PythonAnywhere console. In the console, run this command:

This command makes the script executable in bash every time changes are detected in PythonAnywhere. Now, every time you start a deploy, the script will be executed and the application will be reloaded. Congratulations on achieving our goal of automating deployments with PythonAnywhere!

Through this tutorial you have been able to learn how to prepare an application for deployment, configure a PythonAnywhere environment, and automate deployment using SSH. This tutorial also explained the importance of SSH keys in deploying to PythonAnywhere. You added to your knowledge of CI/CD practices by setting up your application to deploy if all parameters, including passing tests and CircleCI jobs, are met. And you learned how to do auto-reloads on PythonAnywhere after each deployment. I hope you enjoyed this tutorial can use it with your team to level up your CI/CD practice. Until next time, keep coding!

Waweru Mwaura is a software engineer and a life-long learner who specializes in quality engineering. He is an author at Packt and enjoys reading about engineering, finance, and technology. You can read more about him on his web profile.

Get the latest posts in your inbox

By submitting this form, you are agreeing to our Terms of Use and Privacy Policy.

Step 1 Open a Bash console and clone the repository.

git clone https://github.com/amaanabbasi/Python-Flask-Blog.git

DEV Community ‍ ‍ is a community of 909,780 amazing developers

Were a place where coders share, stay up-to-date and grow their careers.

language: Bahasa Indonesia

Source code: github

Deploy di PYAW paling mudah karena tidak membutuhkan kita untuk menginstall aplikasi tertentu di komputer, tidak seperti Heroku yang membutuhkan aplikasi Heroku dan Git.

Catatan:

  • Kalau aplikasinya tidak perlu memakai package dengan versi tertentu, saran saya tidak perlu membuat virtualenv karena memori yang disediakan sangat terbatas (500 MB). Ketika menggunakan virtualenv memori akan termakan banyak untuk install package.
  • File yang dibutuhkan untuk project kita tinggal di-upload ke PYAW. Jika project terdiri dari beberapa folder dan file (seperti project pada umumnya), akan lebih mudah jika satu kesatuan folder project kita (atau folder tertentu, misal hanya folder static) di-zip terlebih dahulu lalu di-upload di lokasi yang diinginkan.
  • Contoh: untuk project nyc311 yang membutuhkan file static dalam folder static, upload folder static yang sudah di-zip ke direktori /home/azukacchi/nyc311. File zip dapat di-unzip dengan cara: (1) membuka folder tempat file zip berada lalu “Open Bash console here”, atau (2) buka bash console dimana pun lalu ubah direktori ke tempat file zip berada cd /home/azukacchi/nyc311. Setelah bash console terbuka, ketik unzip namafile.zip (dalam kasus ini namafile adalah static). File zip yang terekstrak akan menjadi folder berisi file-file.
  • Jangan lupa isi detail aplikasi di halaman Web.
  • diadaptasi dari tutorial resmi: Getting Started on Heroku with Python

    Asumsi:

  • Heroku dan Git sudah ter-install (jika belum, lihat link tutorial)
  • folder project sudah tersedia dengan (dengan atau tanpa menggunakan virtual environment), aplikasi Flask sudah berjalan OK di komputer dan siap di-deploy
  • Langkah-langkah:

  • Di dalam folder project, buat beberapa file dengan menggunakan Notepad bernama Procfile, requirements.txt, runtime.txt, .gitignore dengan rincian isi file sebagai berikut:
    1. Procfile
       web: gunicorn app:app 
    2. requirements.txt Semua package yang dibutuhkan untuk project kita. Tambah juga gunicorn untuk webserver (install dengan pip terlebih dahulu). Contoh untuk project saya
       gunicorn flask==1.1.2 imblearn plotly==4.14.3 pandas==1.2.2 numpy==1.19.2 sklearn 
    3. runtime.txt Isi dengan versi python yang digunakan untuk project. Misal untuk project ini saya menggunakan virtual environment dengan python versi 3.8.5, maka isi file sebagai berikut.
       python-3.8.5 
    4. .gitignore Sesuaikan dengan project. Misal:
       ## Cache __pycache__/ 
  • Dengan asumsi seluruh file sudah final, langkah selanjutnya adalah menjadikan folder project kita menjadi repository git. Buka command prompt lalu buka direktori folder project kita dan ubah folder menjadi repository git. Lalu buat aplikasi heroku baru di folder tersebut. Contoh:
    cd "C:UsersazukaDrive FolderDash311-nyc" git init heroku create 
  • Commit dan push. Perhatikan baik-baik log pada command prompt jika terdapat error pada langkah terakhir. Error bisa datang dari versi python yang tidak sesuai di file runtime.txt atau ada package yang tidak tertera di file requirements.txt.
    git add . git commit -m "lalalayeyeye isi bebas" git push heroku master 
  • Jika deploy sudah berhasil, pastikan satu instance app berjalan
    heroku ps:scale web=1 
  • Ganti nama app lama (secara default di-generate random oleh Heroku) dengan nama yang diinginkan
    heroku apps:rename newname 
  • Jika kita membuat perubahan pada aplikasi, cukup ulangi deploy dengan mengulangi langkah nomor 3.
  • FAQ

    How do I host my Flask app on PythonAnywhere for free?

    In this article, I will guide you throughout the process of hosting your Flask Application live on PythonAnywhere for free.
    1. Step 1: Create a requirements. txt. …
    2. Step 2: Create a PythonAnywhere account. …
    3. Step 3: Configuration for your Web App. …
    4. Step 4: Editing our default website. …
    5. Step 5: Configuring the root file.

    How do I host my Flask app online?

    How to Serve a Flask App
    1. Step 1: Prerequisites. Complete the following prerequisites before you get started with your Flask app. …
    2. Step 2: Create the Flask application. …
    3. Step 3: Build your container image. …
    4. Step 4: Create a container service. …
    5. Step 5: Deploy the container. …
    6. Step 6: Cleanup.

    Which is better Heroku or PythonAnywhere?

    Heroku and PythonAnywhere can be primarily classified as “Platform as a Service” tools. “Easy deployment” is the top reason why over 694 developers like Heroku, while over 4 developers mention “Web apps” as the leading cause for choosing PythonAnywhere.

    Where can I host a Flask server?

    Hosting Platforms
    1. PythonAnywhere.
    2. Google App Engine.
    3. Google Cloud Run.
    4. AWS Elastic Beanstalk.
    5. Microsoft Azure.

    Related Posts