<p dir="auto">This tutorial is part of a series where different aspects of quickly creating and deploying STEEM web applications by using the Django framework as well as Beem are discussed. Knowledge of programming with Python is advised, as well as HTML and CSS, Javascript and Bootstrap.
<hr />
<h4>Repository
<p dir="auto"><span><a href="https://github.com/django/django" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">https://github.com/django/django
<h4>What will I learn
<ul>
<li>Fetching STEEM and SBD ticker prices
<li>Create an APIview and path
<li>Parse the prices into a html <div>
<li>Automatically updating the ticker prices
<li>Pitfalls with regards to scaling
<h4>Requirements
<ul>
<li>Python 3.7
<li>Django 2.1.5
<li>Beem 0.20.17
<li>Gunicorn 19.9.0
<li>Git
<li>Heroku
<li>Pipenv
<h4>Difficulty
<ul>
<li>basic
<hr />
<h3>Tutorial
<h4>Preface
<p dir="auto">Django allows for quick development of web applications and since it uses Python as it's main programming language it also allows for easy combition with the steem-python library to develop STEEM web applications. This part is a continuation on <a href="https://steemit.com/utopian-io/@steempytutorials/part-2-using-a-bootstrap-template-to-parse-steem-posts-via-beem-api" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Part 2 and continues with the code: <a href="https://github.com/Juless89/django-steem-account" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Github. In this tutorial a live STEEM/SBD ticker will be added to the blog page.
<h4>Setup
<p dir="auto">Download the base files via Github and branch to commit <code>e3b2d6f86b3191f9ca448ddcac43ab41f2bdc7cd to follow along side the tutorial. Install the virtual environment from the <code>Lockfile, enter the virtual environment and install the <code>django rest-framework that will be used for this tutorial.
<pre><code>$ cd ~/
$ git clone https://github.com/Juless89/django-steem-blog.git
$ cd django-steem-blog
$ git checkout e3b2d6f86b3191f9ca448ddcac43ab41f2bdc7cd
$ pipenv install
$ pipenv shell
(django-steem_blog) $ pip install djangorestframework==3.9.1
<p dir="auto">Register the rest_framework inside settings.py.
<pre><code>INSTALLED_APPS = [
.
.
'rest_framework', # new
}
<p dir="auto">Run the server, it should look as following:
<pre><code>(django-steem_blog) $ python manage.py runserver
<p dir="auto"><center><img src="https://images.hive.blog/768x0/https://cdn.steemitimages.com/DQmXH7Pwaw7X2dBGpiSph6NjqbF3sodzafXy7aEvgam7aH6/Screenshot%202019-02-05%2016.38.31.png" alt="Screenshot 2019-02-05 16.38.31.png" srcset="https://images.hive.blog/768x0/https://cdn.steemitimages.com/DQmXH7Pwaw7X2dBGpiSph6NjqbF3sodzafXy7aEvgam7aH6/Screenshot%202019-02-05%2016.38.31.png 1x, https://images.hive.blog/1536x0/https://cdn.steemitimages.com/DQmXH7Pwaw7X2dBGpiSph6NjqbF3sodzafXy7aEvgam7aH6/Screenshot%202019-02-05%2016.38.31.png 2x" />
<h4>Fetching STEEM and SBD ticker prices
<p dir="auto">Ticker prices can either be fetched directly from a specific exchange or another option is to use the weighted average of all exchanges via a service like coinmarketcap.com. This website hosts an API that can be accessed for current ticker prices.
<p dir="auto">To display the ticker prices on the webpage an Ajax call can be made to the API directly and process the data requested. A cleaner solution would be to make this call inside a python function to process the data and only return the required data via an <code>APIview to Ajax to parse to html. The file <code>services.py is used to house any additional python functions.
<pre><code># posts/services.py
# Get request for coinmarketcap, returns a string of the current price
def get_market_price(token):
api_url = 'https://api.coinmarketcap.com/v1/ticker/{}/'.format(token)
response = requests.get(api_url)
if response.status_code == 200:
return json.loads(response.content.decode('utf-8'))[0]['price_usd']
else:
return None
<p dir="auto">This function requests the data for a specific ticker from coinmarketcap.com and returns only the <code>price_usd data variable. When the response fails <code>None is returned.
<h4>Create an APIview and path
<p dir="auto">The django rest_framework is build to handle everything with regard to <code>RESTful API. For this tutorial the same could be accomplished by returning the data from <code>get_market_price in a <code>Jsonrepsonse. It is good practise to use the framework as it allows for many additional features like user authentication when this is required.
<p dir="auto">Import the <code>APIView and response from the framework, create a new APIView <code>TickerData and overwrite the <code>get method. Also import <code>get_market_price from <code>services.py.
<pre><code># posts/view.py
from .services import get_market_price
from rest_framework.views import APIView
from rest_framework.response import Response
# APIview for coinmarketcap STEEM and SBD ticker prices.
class TickerData(APIView):
# Unused user authentication classes
authentication_classes = []
permission_classes = []
# Retrieve STEEM and SBD market prices, return a dict
def get(self, request, format=None):
data = {
"STEEM": '{:.3f}'.format(float(get_market_price('steem'))),
"SBD": '{:.3f}'.format(float(get_market_price('steem-dollars'))),
}
return Response(data)
<p dir="auto">Register the path <code>'api/ticker/data/' where the api can be accessed inside <code>urls.py.
<pre><code># pages/urls.py
from .views import TickerData
urlpatters = [
.
path('api/ticker/data/', TickerData.as_view()),
.
]
<p dir="auto"><span>Access the path directly to see if everything is working. <a href="http://127.0.0.1:8000/api/ticker/data/" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">http://127.0.0.1:8000/api/ticker/data/
<p dir="auto"><center><img src="https://images.hive.blog/768x0/https://cdn.steemitimages.com/DQmXCN7Z56EA3VWGrgsU8fxaa47c9xbM76Q2TAWZLADJes3/Screenshot%202019-02-05%2017.09.03.png" alt="Screenshot 2019-02-05 17.09.03.png" srcset="https://images.hive.blog/768x0/https://cdn.steemitimages.com/DQmXCN7Z56EA3VWGrgsU8fxaa47c9xbM76Q2TAWZLADJes3/Screenshot%202019-02-05%2017.09.03.png 1x, https://images.hive.blog/1536x0/https://cdn.steemitimages.com/DQmXCN7Z56EA3VWGrgsU8fxaa47c9xbM76Q2TAWZLADJes3/Screenshot%202019-02-05%2017.09.03.png 2x" />
<h4>Parse the prices into a html <div>
<p dir="auto">In order to fetch and parse the data into the html Ajax is required. This code needs to be inserted into <code>album.html between <code><script></script> tags. The ticker prices will be displayed in the header so place the <code><scripts></scripts> tags below <code><header></header>
<p dir="auto">Additionally a <code>div tag has to be created with an id so that is can be referenced to. Add a new div tag inside the container that is in the header. Behind the the <code><a></a> tag. Set its <code>id to <code>ticker and the <code>class to <code>navbar-brand.
<pre><code># templates/album.html
<div id="ticker" class="navbar-brand"></div>
<header>
<div class="collapse bg-dark" id="navbarHeader">
</div>
<div class="navbar navbar-dark bg-dark shadow-sm">
<div class="container d-flex justify-content-between">
<a href="#" class="navbar-brand d-flex align-items-center">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-2" focusable="false" aria-hidden="true"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path><circle cx="12" cy="13" r="4"></circle></svg>
<strong>Blog</strong>
</a>
<div id="ticker" class="navbar-brand"></div>
</div>
</div>
</header>
<p dir="auto">To perform a Ajax GET request use the following code structure. The <code>endpoint is the path to the <code>APIView. When the request is successful a <code>data object is returned. Which can be accessed by adding a <code>. and the name of the requested variable. In this case <code>data.STEEM and <code>data.SBD. A string is created by concatenating the variables with text strings. <code>$('#ticker').html(string); inserts the created string into the div tag with <code>id=ticker.
<pre><code># templates/album.html
var endpoint = '/api/ticker/data'
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
var string = 'STEEM $' + data.STEEM + ' SBD $' + data.SBD
$('#ticker').html(string);
},
error: function(error_data){
console.log(error_data)
}
})
<p dir="auto"><span>Loading the webpage should now display the STEEM and SBD price tickers in the top right corner. <a href="http://127.0.0.1:8000" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">http://127.0.0.1:8000
<p dir="auto"><center><img src="https://images.hive.blog/768x0/https://cdn.steemitimages.com/DQmfLRSAWgvaNBozZeRE798VvxYmzfiYAe78CNxpKkwtBXx/Screenshot%202019-02-05%2017.25.58.png" alt="Screenshot 2019-02-05 17.25.58.png" srcset="https://images.hive.blog/768x0/https://cdn.steemitimages.com/DQmfLRSAWgvaNBozZeRE798VvxYmzfiYAe78CNxpKkwtBXx/Screenshot%202019-02-05%2017.25.58.png 1x, https://images.hive.blog/1536x0/https://cdn.steemitimages.com/DQmfLRSAWgvaNBozZeRE798VvxYmzfiYAe78CNxpKkwtBXx/Screenshot%202019-02-05%2017.25.58.png 2x" />
<h4>Automatically updating the ticker prices
<p dir="auto">At the moment when the page is loaded the ticker prices are pulled from coinmarketcap's API and displayed on the webpage. Automatically refreshing the prices can be achieved with several changes to the script.
<p dir="auto">Create a function from the Ajax call <code>get_ticker and then set an interval for this function <code>setInterval("get_ticker();",5000). The time is in milliseconds so 1000 equals 1 second.
<pre><code># templates/album.html
function get_ticker()
{
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
var string = 'STEEM $' + data.STEEM + ' SBD $' + data.SBD
$('#ticker').html(string);
},
error: function(error_data){
console.log(error_data)
}
})
}
setInterval("get_ticker();",5000);
<p dir="auto">However, the code does not process until the first interval is met. To load the function initially on page load add the following line $(document).ready(get_ticker);
<pre><code># templates/album.html
// Load on page load, then load every 5000/1000 seconds.
$(document).ready(get_ticker);
setInterval("get_ticker();",5000);
<h4>Pitfalls with regards to scaling
<p dir="auto">Currently every time the ticker prices are reloaded an API call from the server to coinmarketcap is made. Most public APIs have a limit to how often they can be called from a unique IP address. Imagine a refresh time of 5 seconds and 100 users active on the webpage. This would mean that on average 100 calls would be made per second. For scaling it would be better to create a separate service that uploads the ticker prices into a database every x seconds and then an APIView that loads the data from the database instead.
<h3>Curriculum
<ul>
<li><a href="https://steemit.com/@steempytutorials/part-0-create-steem-web-applications-with-django-and-steem-python" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Part 0: Create STEEM web applications with Django and Steem-Python
<li><a href="https://steemit.com/utopian-io/@steempytutorials/part-1-using-the-url-to-dynamically-pull-data-via-the-steem-api-and-parse-to-html" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Part 1: Using the URL to dynamically pull data via the Steem API and parse to html
<li><a href="https://steemit.com/utopian-io/@steempytutorials/part-2-using-a-bootstrap-template-to-parse-steem-posts-via-beem-api" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Part 2: Using A Bootstrap Template To Parse STEEM Posts Via Beem API
<li><a href="https://steemit.com/utopian-io/@steempytutorials/part-3-combing-charts-js-and-django-rest-framework" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Part 3: Combing Charts.js And Django Rest Framework
<hr />
<p dir="auto">The code for this tutorial can be found on <a href="https://github.com/Juless89/django-steem-blog" target="_blank" rel="nofollow noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Github!
<p dir="auto"><span>This tutorial was written by <a href="/@juliank">@juliank.
After analyzing your tutorial we suggest the following:Thank you for your contribution @steempytutorials.
Put more comments in the sections of your code, for example, the ajax call has no comments to help the reader understand what is developed.
This tutorial is a bit basic, in the next tutorial bring something more innovative.
Looking forward to your upcoming tutorials.
Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here.
Need help? Chat with us on Discord.
[utopian-moderator]
Thank you for your review, @portugalcoin! Keep up the good work!
Hi @steempytutorials!
Feel free to join our @steem-ua Discord serverYour post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation! Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Congratulations @steempytutorials! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :
<table><tr><td><span><img src="https://images.hive.blog/768x0/https://steemitimages.com/60x70/http://steemitboard.com/@steempytutorials/posts.png?201902051741" srcset="https://images.hive.blog/768x0/https://steemitimages.com/60x70/http://steemitboard.com/@steempytutorials/posts.png?201902051741 1x, https://images.hive.blog/1536x0/https://steemitimages.com/60x70/http://steemitboard.com/@steempytutorials/posts.png?201902051741 2x" /><td>You published more than 70 posts. Your next target is to reach 80 posts. <p dir="auto"><sub><em><a href="https://steemitboard.com/@steempytutorials" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Click here to view your Board<br /> <sub><em>If you no longer want to receive notifications, reply to this comment with the word <code>STOP <p dir="auto">To support your work, I also upvoted your post! <blockquote> <p dir="auto">Support <a href="https://steemit.com/@steemitboard" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">SteemitBoard's project! <strong><a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1" target="_blank" rel="noreferrer noopener" title="This link will take you away from hive.blog" class="external_link">Vote for its witness and <strong>get one more award!Hey, @steempytutorials!
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!
Get higher incentives and support Utopian.io!
SteemPlus or Steeditor). Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!