Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send floats as paramters in Django 2.0 using path()?

Tags:

I have developed a Python script with arguments. It has functions to perform the differents operations depending on the arguments received. Now I am trying to pass that arguments or parameters through the API. I am using path() new function of Django 2.0 (specifically this is the version I am using: 2.2.9) What is the way that passing floats in url in Django? It is working with integers but not with float.

What is the best ways to pass float? Do you convert to HEX for example?

Example using GET to point to the API anf fire a task:

Not working: http://x.x.x.x:8000/proveedores/api/pruebascelery/buy/0/1.1287 (last parameter is a float)

works with integer: http://x.x.x.x:8000/proveedores/api/pruebascelery/buy/0/2

Django: (urls.py)

path('pruebascelery/<slug:post_id>/<slug:post_id2>/<slug:post_id3>', lanzador_task_start)

Django: (views.py)

def lanzador_task_start(request, post_id, post_id2, post_id3):
    comando = "python /home/developer/venvpruebas/recibirparametros.py " + str(post_id) +str(" ")+ 
str(post_id2)+str(" ")+ str(post_id3)
    lanzar.delay(comando)
    return HttpResponse('<h1>Done</h1')

python side:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import struct


def RecibirParametros(recibir_todo):

    print("Received: ", recibir_todo)

if __name__ == "__main__":
    recibir_todo = sys.argv[1], sys.argv[2], sys.argv[3]
    #--------------------------------------------------------------
    #[1] test1
    #[2] test2
    #[3] test3
    #--------------------------------------------------------------
    RecibirParametros(recibir_todo)
like image 955
Kentron.dna Avatar asked May 18 '20 01:05

Kentron.dna


1 Answers

You can use Path converters for customize url parameters.

in converts.py

class FloatUrlParameterConverter:
    regex = '[0-9]+\.?[0-9]+'

    def to_python(self, value):
        return float(value)

    def to_url(self, value):
        return str(value)

in urls.py

from django.urls import path, register_converter

from . import converters, views

register_converter(converters.FloatUrlParameterConverter, 'float')

urlpatterns = [
    ...
    path('pruebascelery/<float:post_id>/<float:post_id1>/...', views.year_archive),
    ...
]

For alternative methods:

You can use regular expressions inside urls.py directly with re_path function like that:

re_path(r'^[0-9]+\.?[0-9]+$', blog_articles)

Also, you can retrieve your parameters from url as query params. Example url for this:

http://x.x.x.x:8000/proveedores/api/pruebascelery/buy/?post_id=1.5&post_id2=2.5...
like image 52
kamilyrb Avatar answered Nov 15 '22 06:11

kamilyrb