Django Server — Part 2

Gonzalo Galante
4 min readMay 30, 2022

--

In this article we will cover how to implement functions.

For the explanation I will divide myself into two large groups, main functions (they are the ones that will receive the fetches), and auxiliary functions (they cannot be fetches but they add functionalities to the main functions).

Secondly we will use the “urllib” library, thanks to this we will send parameters to our main functions.

Then let’s get started

Main functions

All main functions are declared in views.py (not required). I use this configuration because it is easier for me, the structure is cleaner and with this I know that all the functions in views.py must be in my url.py inside the application.

Why should it be in url.py? because these functions can be searched, and for that we need to add a specific path for each one.

We will create a function that receives some parameters and returns a json with data.

This project throughout several articles because will contain a structure with recommendations about cryptocurrencies.

Suppose we want to know the real price of some crypto, well for that we can create a function that gets a parameter (Crypto) and returns the real value.

We need install requests library, so…

pipenv install requests

In views.py write this

from django.http import JsonResponse
import urllib
import requests
def cryptoPrice(request):
obj = dict(request.GET)
symbol = urllib.parse.unquote("".join(obj.get("symbol")))
key = f"<https://api.binance.com/api/v3/ticker/price?symbol={symbol}USDT>" data = requests.get(key)
data = data.json()
response = f"{data['symbol']} price is {data['price']}"
return JsonResponse({"price": response})

In url.py (the url of our App)

urlpatterns = [
path("cryptoPrice", views.cryptoPrice),
]

Let’s go by parts

Libraries used

  • request That we use to get data through an http request, in this case binance.
  • urllib: This is the most important to know why we use it. We start from the fact that we want to make a request to our microservice and for this we need to communicate through a url, but we also want to send a parameter, in this case about which crypto we want to know the price. Thanks to urllib we can send parameters through the url

Where the function was created, as a parameter we use “request”, in this variable is where the parameters will be loaded through the url.

To get the parameters first, we instantiate a variable “dict(request.GET)”. Then create a variable (one for each parameter we want to use) and pass it “urllib.parse.unquote(“”.join(obj.get(“{PARAMETER}”)))”.

The name of the variable and the parameter is not necessary, but I recommend that they be the same.

Finally the return we can use JsonResponse or HttpResponse

The rest of code is simple, we send a request to the binance API and process the data into a json file.

When we want make a request the url will be

http://localhost:8000/cryptoPrice?cryptos=BTC

http://localhost:8000/cryptoPrice?cryptos=CRYPTO

Let’s make the function a bit more “complex” and pass it a list of cryptos

from django.http import JsonResponse
import urllib
import requests
import json
def test(request):
return JsonResponse({"response": "test"}, status=200)
def cryptoPrice(request):
obj = dict(request.GET)
cryptos = urllib.parse.unquote("".join(obj.get("cryptos")))
cryptos = json.loads(cryptos)
response = []
for n in cryptos:
key = f"<https://api.binance.com/api/v3/ticker/price?symbol={n}USDT>"
data = requests.get(key)
data = data.json()
response.append(f"{data['symbol']} price is {data['price']}")
return JsonResponse({"price": response})

In this case we can send a request with multiple cryptos and get the prices

The url will be:

http://localhost:8000/cryptoPrice?cryptos=["BTC","ETH"]

http://localhost:8000/cryptoPrice?cryptos=[CRYPTOS]

One last example on multiple parameters.

Now we want to make a request but not only with the crypto but also select if we want the price or more details like last price, offer price, open price etc.

To make this possible, we need to pass two parameters, the crypto and the price option or more details.

def crypOptions(request):
obj = dict(request.GET)
detail = urllib.parse.unquote("".join(obj.get("detail")))
#detail can be 24hr or price
cryptos = urllib.parse.unquote("".join(obj.get("cryptos")))
cryptos = json.loads(cryptos)
response = []
for n in cryptos:
key = f"<https://api.binance.com/api/v3/ticker/{detail}?symbol={n}USDT>"
data = requests.get(key)
data = data.json()
if detail == "price":
response.append(f"{data['symbol']} price is {data['price']}")
else:
response.append(f"{data['symbol']} information: {data}")
return JsonResponse({"response": response})

The url will be:

http://localhost:8000/crypOptions?cryptos=["BTC","ETH"]&detail=24hr

http://localhost:8000/crypOptions?cryptos=["BTC","ETH"]&detail=price

In the next article we will do more complex functions, but if you want to know more about the binance API you can go to the following link

--

--