visit
Let's start with creating new project named cryptocurrencytracking and inside your project create app named trackingAPI
django-admin startproject cryptocurrencytracking
cd cryptocurrencytracking
django-admin startapp trackingAPI
pip install djangorestframework
INSTALLED_APPS = [
...
'rest_framework',
'trackingAPI',
]
pip install Celery
sudo apt-get install rabbitmq-server
sudo systemctl enable rabbitmq-server
sudo systemctl start rabbitmq-server
Once installation completed, add the CELERY_BROKER_URL configuration to the end of settings.py file:
CELERY_BROKER_URL = 'amqp://localhost'
Then, create celery.py inside your project.
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cryptocurrencytracking.settings')
app = Celery('cryptocurrencytracking')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
Now inside your __init__.py import the celery:
from .celery import app as celery_app
__all__ = ['celery_app']
In your models.py:
from django.db import models
class Cryptocurrency(models.Model):
cryptocurrency = models.CharField(max_length=100)
price = models.CharField(max_length=100)
market_cap = models.CharField(max_length=100)
change = models.CharField(max_length=100)
def __str__(self):
return self.cryptocurrency
We are going to crawl website named and if you visit the site you can see the field names there.
pip install beautifulsoup4
Now, create new file named tasks.py inside our app trackingAPI.
# tasks.py
from time import sleep
from celery import shared_task
from bs4 import BeautifulSoup
from urllib.request import urlopen, Request
from .models import Cryptocurrency
@shared_task
# do some heavy stuff
def crawl_currency():
print('Crawling data and creating objects in database ..')
req = Request('//coinranking.com', headers={'User-Agent': 'Mozilla/5.0'})
html = urlopen(req).read()
bs = BeautifulSoup(html, 'html.parser')
# Find first 5 table rows
rows = bs.find('tbody', class_="table__body").find_all('tr', class_="table__row")[0:5]
for row in rows:
cryptocurrency = row.find('span', class_="profile__name").get_text().strip().replace('\n', '')
values = row.find_all('div', class_="valuta")
price = values[0].get_text().strip().replace('\n', '')
market_cap = values[1].get_text().strip().replace('\n', '')
change = row.find('div', class_="change").find('span').get_text().strip().replace('\n', '')
print({'cryptocurrency': cryptocurrency, 'price':price, 'market_cap':market_cap, 'change':change})
# Create object in database from crawled data
Cryptocurrency.objects.create(
cryptocurrency = cryptocurrency,
price = price,
market_cap = market_cap,
change = change
)
# Sleep 3 seconds to avoid any errors
sleep(3)
#tasks.py
@shared_task
def update_currency():
print('Updating data ..')
req = Request('//coinranking.com', headers={'User-Agent': 'Mozilla/5.0'})
html = urlopen(req).read()
bs = BeautifulSoup(html, 'html.parser')
rows = bs.find('tbody', class_="table__body").find_all('tr', class_="table__row")[0:5]
for row in rows:
cryptocurrency = row.find('span', class_="profile__name").get_text().strip().replace('\n', '')
values = row.find_all('div', class_="valuta")
price = values[0].get_text().strip().replace('\n', '')
market_cap = values[1].get_text().strip().replace('\n', '')
change = row.find('div', class_="change").find('span').get_text().strip().replace('\n', '')
print({'cryptocurrency': cryptocurrency, 'price':price, 'market_cap':market_cap, 'change':change})
data = {'cryptocurrency': cryptocurrency, 'price':price, 'market_cap':market_cap, 'change':change}
Cryptocurrency.objects.filter(cryptocurrency=cryptocurrency).update(**data)
sleep(3)
# Run this function if database is empty
if not Cryptocurrency.objects:
crawl_currency()
while True:
sleep(15)
update_currency()
celery -A cryptocurrencytracking worker -l info
Now, create serializers.py inside our app.
Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.#serializers.py
from rest_framework import serializers
from .models import Cryptocurrency
class CryptocurrencySerializer(serializers.ModelSerializer):
class Meta:
model = Cryptocurrency
fields = ['cryptocurrency', 'price', 'market_cap', 'change']
The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields.
For more information take look
Next step is building API views, so open views.py:
#views.py
from django.shortcuts import render
from rest_framework import generics
from .models import Cryptocurrency
from .serializers import CryptocurrencySerializer
class ListCryptocurrencyView(generics.ListAPIView):
"""
Provides a get method handler.
"""
queryset = Cryptocurrency.objects.all()
serializer_class = CryptocurrencySerializer
and finally configure urls.py
#urls.py
from django.contrib import admin
from django.urls import path
from trackingAPI.views import ListCryptocurrencyView
urlpatterns = [
path('admin/', admin.site.urls),
path('', ListCryptocurrencyView.as_view()),
]
I hope you learned something from this tutorial and make sure you are following me on social media. Also check for more.
Stay Connected!