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…
- Make sure you have signed up for a free PythonAnywhere account, and you’re logged in.
- Go to the Web menu item and then press the Add new web app button.
- 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
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
cd automating-flask-deployments-with-pythonanywhere Install pipenv package manager using:
pip install pipenv
Install all dependencies with:
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:
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
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_HOST variables to do the authentication while at the same time masking the SSH user and hostname. We did this by adding
SSH_HOST to the CircleCI Settings page under the Environment variables. You can read more about adding variables here .
SSH_HOST to access PythonAnywhere via SSH is
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
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
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.
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.
diadaptasi dari tutorial resmi: Getting Started on Heroku with Python
.gitignoredengan rincian isi file sebagai berikut:
web: gunicorn app:app
- requirements.txt Semua package yang dibutuhkan untuk project kita. Tambah juga
gunicornuntuk 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
- 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.
- .gitignore Sesuaikan dengan project. Misal:
## Cache __pycache__/
cd "C:UsersazukaDrive FolderDash311-nyc" git init heroku create
runtime.txtatau ada package yang tidak tertera di file
git add . git commit -m "lalalayeyeye isi bebas" git push heroku master
heroku ps:scale web=1
heroku apps:rename newname
How do I host my Flask app on PythonAnywhere for free?
- Step 1: Create a requirements. txt. …
- Step 2: Create a PythonAnywhere account. …
- Step 3: Configuration for your Web App. …
- Step 4: Editing our default website. …
- Step 5: Configuring the root file.
How do I host my Flask app online?
- Step 1: Prerequisites. Complete the following prerequisites before you get started with your Flask app. …
- Step 2: Create the Flask application. …
- Step 3: Build your container image. …
- Step 4: Create a container service. …
- Step 5: Deploy the container. …
- Step 6: Cleanup.
Which is better Heroku or PythonAnywhere?
Where can I host a Flask server?
- Google App Engine.
- Google Cloud Run.
- AWS Elastic Beanstalk.
- Microsoft Azure.