guide api requests   0   448
Get latest Bitcoin and other crypto-currencies rates using python Django

Everybody is investing in bitcoins. 

James Howells is trying to dig a landfill site to get 7500 bitcoins that were dumped there in 2013.

To be a good investor, it is necessary that you keep track of ups and downs in the market. '

There are multiple platforms where you can track the price of bitcoin. But for a python programmer that is no fun. Being a python programmer we will develop our own project where we can get latest bitcoin and other crypto-currency prices.

Let's start.



Virtual environment setup:

It is always recommended to use virtual environment for all your python and Django projects.

Create a virtual environment using python3 using below command.

virtualenv -p /usr/bin/python3 crypto


Now activate the virtual environment.

source crypto/bin/activate


Install the latest Django version and other required libraries.

For now only requests package is required. We will add other packages later if required.

pip install django requests


This will install Django 2.0 and requests package along with some other package.

You can verify the same by running command pip freeze .

(crypto) rana@Brahma: crypto$ pip freeze
certifi==2017.11.5
chardet==3.0.4
Django==2.0
idna==2.6
pytz==2017.3
requests==2.18.4
urllib3==1.22


Creating new Django Project:

Once virtual environment has been setup and activated, create a new django project.

django-admin startproject crypto


Go to crypto project directory and list the files.

get latest bitcoin and other crypto currencies rates using python django

Since we are working on Django 2.0 , we need to take care of few things which we will highlight as we progress.

Now create a new app 'bitcoin'.

python manage.py startapp bitcoin


Add this app to the list of installed apps in settings.py  file.



Project Setup:

URLs:

Create urls.py  file in new app bitcoin.

from django.urls import path
from . import views

app_name = 'bitcoin'

urlpatterns = [
    path('', views.index, name="index"),
]


Django 2.0 Note: Adding app_name  in urls.py  is require now, otherwise you will get the below error.

'Specifying a namespace in include() without providing an app_name '
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.
 

Include urls of bitcoin app in project's urls.py  file.  


Teamplate:

Create a directory templates/bitcoin  in bitcoin app.

Inside this directory create a new html file, index.html . You can leave this file empty as of now or to make sure things are working fine, put some text there.  


Views:

Create a new function index in views.py  file.

For now this function will only render the index.html  created in previous step.

We will add more functionality in coming steps.

from django.shortcuts import render


def index(request):
    data = {}
    return render(request, "bitcoin/index.html", data)
 


Verifying basic setup:

Once above steps are completed, run the django server.

$python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

December 28, 2017 - 09:00:43
Django version 2.0, using settings 'crypto.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.


Go to localhost:8000  and you can see the text which you putted in index.html  file.  



Getting bitcoin prices:

We will use the coinmarktecap api to fetch the latest data.

In views.py  file add a new function to get bitcoin data. This function will call the api url and get the currency data. Data returned is Json string. Convert it to Json Object.

# return the data received from api as json object
def get_crypto_data():
    api_url = "https://api.coinmarketcap.com/v1/ticker/?limit=10"

    try:
        data = requests.get(api_url).json()
    except Exception as e:
        print(e)
        data = dict()

    return data


Make a call to get_crypto_data  in index function and return the rendered response.

Complete views.py  file :

from django.shortcuts import render
import requests


def index(request):
    data = {}
    data["crypto_data"] = get_crypto_data()
    return render(request, "bitcoin/index.html", data)


# return the data received from api as json object
def get_crypto_data():
    api_url = "https://api.coinmarketcap.com/v1/ticker/?limit=10"

    try:
        data = requests.get(api_url).json()
    except Exception as e:
        print(e)
        data = dict()

    return data
 

Rendering Data in Template:

Render the coins data row wise using a for loop in template as shown in html code below.

<html>
    <head>
        <title>Latest Bitcoin Price - ThePythonDjango.Com</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    </head>
    <body style="margin:20px;">
    
        <div class="alert alert-dark" role="alert">
            <span style="font-size:30px;">Bitcoin Latest Price</span> <span style="font-size:15px;">by <a href="http://ThePythonDjango.Com" target="_blank">ThePythonDjango.Com</a></span>
        </div>
        
        <div class="list-group">
            <div class="list-group-item list-group-item-primary">
                <div class="row">
                    <div class="col-md-3">
                        <label>Name</label>
                    </div>
                    <div class="col-md-3">
                        <label>USD Price</label>
                    </div>
                    <div class="col-md-3">
                        <label>BTC Price</label>
                    </div>
                    <div class="col-md-3">
                        <label>Change in Last Hour</label>
                    </div>
                </div>
            </div>
            {% for coin in crypto_data %}
            <div class="list-group-item list-group-item-{% if coin.percent_change_1h.0 == '-'%}danger{% else %}success{% endif %}">
                <div class="row">
                    <div class="col-md-3">
                        {{coin.name}}
                    </div>
                    <div class="col-md-3">
                        {{coin.price_usd}}
                    </div>
                    <div class="col-md-3">
                        {{coin.price_btc}}
                    </div>
                    <div class="col-md-3">
                        {{coin.percent_change_1h}}
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </body>
</html>


We are using bootstrap.css  for styling. Now if you go to localhost:8000  you can see the details as in below image.

get latest bitcoin and other crypto currencies rates using python django

Complete code is available on Github.

Download and setup the project on your machine. Experiment with it and let us know in case of any query.  


References:
[1] https://coinmarketcap.com/api/
[2] Django 2.0 official documentation
guide api requests   0   448

Related Articles:
How to develop a distributable Django app to block the crawling IP addresses
How to create reusable django app which can block crawling IPs from accessing your app. Creating distributable python package and upload on pypi....
Automatically updating Django website hosted on PythonAnyWhere server with every git push
How to automate the process of updating website hosted on python any where server everytime you commit and push code to git repository....
Iterator and Generators in Python: Explained with example
understanding iterators and generators in python, creating python generators, using generators and iterators in python code...
How to create completely automated telegram channel with python
Creating a completely automated telegram channel to generate and post content using python code on regular basis. Automating the Telegram channel using python script...

0 thoughts on 'Get Latest Bitcoin And Other Crypto-Currencies Rates Using Python Django'
Leave a comment:


*All Fields are mandatory. **Email Id will not be published publicly.


SUBSCRIBE
Please subscribe to get the latest articles in your mailbox.



Recent Posts:






© pythoncircle.com 2018-2019