Automatically deploying Django app to PythonAnywhere through GitHub.
Tags: django, github, python, pythonanywhere
Published: 2020-04-03 14:28:31

This post will explain how to setup automatic deployments to a Django Web-App hosted on PythonAnywhere.

What people normally do:
**1. Everyone does this:**

   Local -> GitHub

**2. People with *PAID* account do this(using ssh access):**

   Local -> PythonAnywhere

**3. What I do(with a free or paid account):**

   Local -> GitHub -> PythonAnywhere

Let me first explain why I do this and then I will explain how to do this stuff. 

_Note: You are free to Jump to the Implementation section_

#**Why?**

Putting it simply GitHub is great place to collaborate and they have a better UI than PythonAnywhere to view code. Setting up PythonAnywhere's ssh access for everyone who will be working on the project is just too time taking for me and then again explain them what I did is another difficult task and that too if I have a paid account.

So, I thought it would be amazing if we can just push code onto GitHub and GitHub automatically updates the code on PythonAnywhere and not to mention the default features that are provided by GitHub like Pull Requests, Issues, Actions(haven't used them till now still a feature) and everything else that GitHub offers.

#**How**

We will be using something known as __Deploy Keys__ and __Webhooks__ provided by GitHub to tell our Django Web-App tha it has been updated so it pulls the latest code.

###__First__: 
Install the Python package named GitPython by using the following command:

```bash
$ pip install GitPython
```

###__Second__:
Write the view function that will receive the update and update the code on the server.

Go to your ___views.py___ and add the following code:

```python
import git
from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def update(request):
    if request.method == "POST":
        '''
        pass the path of the diectory where your project will be 
        stored on PythonAnywhere in the git.Repo() as parameter.
        Here the name of my directory is "test.pythonanywhere.com"
        '''
        repo = git.Repo("test.pythonanywhere.com/") 
        origin = repo.remotes.origin

        origin.pull()

        return HttpResponse("Updated code on PythonAnywhere")
    else:
        return HttpResponse("Couldn't update the code on PythonAnywhere")
```
You can also send response codes with them by passing the parameter "status" within the "HttpResponse" that will be returned.

###__Third__:
Set the URL where the Payload from GitHub will be sent.

To add the payload URL add the following lines into ___urls.py___ file of your Django Project:

```python
from django.urls import path

'''
here the name of my app is updater so I add the import my view from there
replace updater with your app-name where you have your views.py
'''
from updater import views

urlpatterns = [
    path("update_server/", views.update, name="update"),
]

```

###__Fourth__:
Now push this code to GitHub and login to our account on PythonAnywhere.

Now follow the following steps:

_Step 1_: Open a bash terminal on PythonAnywhere.

_Step 2_: Issue the following command:
```
$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
```
after this command you will be shown the following prompt:
```
> Generating public/private rsa key pair.
```

_Step 3_: When you're prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location.
```
> Enter a file in which to save the key (/home/you/.ssh/id_rsa): [Press enter]
```
_Step 4_: At the prompt, type a secure passphrase.
```
> Enter passphrase (empty for no passphrase): [Type a passphrase]
> Enter same passphrase again: [Type passphrase again]
```

_Step 5_: Issue the following command on the bash terminal of PythonAnywhere to get your key.
```
$ cat ~/.ssh/id_rsa.pub 
```
then press CTRL+C to copy the key.

###__Fifth__:
Go to your GitHub Account and then Go to the Repository in which you have your Django Project.

Then follow the following steps:

_Step 1_: From your repository, click Settings as shown below.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7ej7tula7p3uswybzmfp.png)

_Step 2_: In the sidebar, click Deploy Keys, then click Add deploy key.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/yqm9vqm29n4l6gy67tmz.png)

_Step 3_: Provide a title, paste in your public key.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/b9r5drrg23od6hfgx0is.png)

_Step 4_: Select Allow write access if you want this key to have write access to the repository. A deploy key with write access lets a deployment push to the repository.

_Step 5_: Click Add key.

###__Sixth__:
Go to your PythonAnywhere account and go to the bash terminal and setup your Web-App but __use the SSH instead of HTTPS for cloning your Repository from GitHub__.

_Note: I would suggest to use the automated script_ __pa_autoconfigure_django.py__ _available in pythonanywhere package which can be installed via pip to automatically setup my project on PythonAnywhere._

If you already have a project setup on PythonAnywhere using HTTPS then open a bash terminal and edit the remote URL to set SSH by using the following command :
```
$ git remote set-url origin git@github.com:USERNAME/REPOSITORY.git
```

###__Seventh__:
Go back to the settings tab of your Repository on GitHub and follow the following steps :

_Step 1_: In the sidebar, click Webhooks, then click Add webhook.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/p5sdbtm71rquv6hu3enw.png)

_Step 2_: Fill in the Payload URL and set the "Content type" to "application/json" as shown below.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jv61nox1yw5gbozwbgjm.png)

_Step 3_: click "Add webhook".

#__Finally__: 
You will see the following when it is success

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lz3oyvckcs0itbgrnlmr.png)

If it show some other icon in place of a green tick then click on edit and at the bottom you can see the "Recent Deliveries" here you can click on the button shown below to see the details of that delivery.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gtzbld6lrmuyt8feitkr.png)

After clicking you will see two tabs "Request" and "Response" to see the details of failure you can click on response and you will get the details as shown below

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jdgj2gbdocedykbot9uz.png)

If you get any __response code other than 200__ then go to the error log on your PythonAnywhere account and check what's the problem.

The most common mistake that I make is when I return something else instead of HttpResponse it will throw some Attribute error.

If you get stuck somewhere then feel free to contact me on telegram using the link https://t.me/soumya_r .