Documenting Django using UML - django

Hello Stack Overflow Community
I'm trying to document my project and I have doubled on how to translate Django Views into UML Class Diagrams.
I have to mention that I'm not using class views, just normal views.
Can you please tell me if this is ok? Do I need to let know the reader what I'm trying to achieve or it is clear what the diagram says?
Many thanks in advance for your feedback
This is the code
def index_crypto(request):
import requests
import json
#Api Call
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1'
headers = {'Accepts': 'application/json','X-CMC_PRO_API_KEY':'xxxxxxxxxx',}
params = {'convert' :'USD'}
api_request = requests.get(url, headers= headers,params= params) #Request Object
try:
data = json.loads(api_request.content) #JSON file containing data.
except Exception as e:
data = "Error...."
print(e)
api_assets= []
for i in data["data"]:
api_assets.append(i)
return render(request,'index_crypto.html',{'api_assets': api_assets})

By defining index_crypto as an operation in a class you would be fully compatible with UML.
Because url, headers and params have a constant value and are only visible in index_crypto you can declare them as read-only ({readOnly}) static attribute (the name is underlined) with the visibility private rather than public
For api_request (Request in your diagram ?) it is not clear to use an attribute, it is a pure local working variable as we have in operations, better to remove it for me.
If I am not wrong index_crypto returns a HttpResponse

Related

Django Rest Framework - Object of type <> is not Json seralizable

I'm new to django rest framework and need some help.
I have ApiView:
class SomeApiView(APIView):
def get_url(self, some_id):
return generate_url(Choices.BOOK, some_id)
def get(self,request):
id = request.query_params.get("some_id")
result_url = self.get_url(id)
return Response({'result_url': result_url})
here when sending request I get next error:
Object of type Choices is not Json serializable.
Choices looks like this:
class Choices(Enum):
BOOK="book"
MOVIE="movie"
GAME="game"
how can I fix this error? Thank you in advance
The error is saying that Choice is not able to be converted to json. Your ideal outcome is {'result_url': 'book'} for example (I assume), but right now it's {'result_url': Choice} which cannot be converted to json.
My point is that instead of Choice you need to return something json serializable (like a string). My best guess is that you need {'result_url': result_url.value}, but I do not know if this will work as I do not know the rest of your code.

flask_restx - api.expect from two sources for swagger

Hei there!
I have a flask restx api and I have an endpoint that essentially needs to do the following
filters = api.model('filters', {
x = fields.Raw('x')
}
parser = reqparse.RequestParser()
parser.add_argument('b', type=int, location='args')
class Process(Resource):
#api.expect(filters)
#api.expect(parser)
def get()
.
.
why?
I have a large set of endpoints that all accept the same filter design, but some endpoints also need query parameters
The code works just fine, I can access the json payload and the query parameters inside the method.
The problem
I need everything documented by swagger but I need to "mix" the api.model object with the parser object into the #api.expect()
#api.expect(filters,parser) should work

How to capture and modify Google Protocol Buffers in a Django view?

Here is a link to the proto file.
Please can someone help me understand how to make this work:
from django.views.decorators.csrf import csrf_exempt
from bitchikun import payments_pb2
#csrf_exempt
def protoresponse(request):
xpo = payments_pb2.Payment.ParseFromString(request)
t = type(xpo)
xpa = request.PaymentACK
xpa.payment = xpo.SerializeToString()
xpa.memo = u'success'
return HttpResponse(xpa.SerializeToString(), content_type="application/octet-stream")
All input appreciated :)
OK so I think I understand what is happening now. You have a system which is POSTing a serialized protobuf to your Django app, and you need to return another protobuf in response.
In Django, you can access the data from a POST in request.body. That is probably what you need to pass to ParseFromString.
You have some other errors too: you refer to request.PaymentACK, which doesn't exist - you mean payments_pb2.PaymentACK - and you never actually instantiate it. Also, you are trying to pass the serialized version of the original request protobuf to that response one, when you should be passing the actual message.
So, altogether it would look like this:
xpo = payments_pb2.Payment.FromString(request.body)
xpa = payments_pb2.PaymentACK()
xpa.payment = xpo
xpa.memo = u'success'
return HttpResponse(xpa.SerializeToString(), content_type="application/octet-stream")

Importing django model methods in json

I am trying to output a set of database records in JSON as follows:
def json_dbtable(request, p):
t = MyModel.objects.filter({some query})
s = serializers.get_serializer("json")()
re = s.serialize(t, ensure_ascii=False)
return HttpResponse(re, mimetype="application/json")
However, one of the fields i'm trying to return needs to change if it is null, and to remedy this the model has a definition that is used as a property .e.g:
name = property(_get_useful_name)
So, to get to the crux of the question. How can I include this "name" property in my json serialization as well as the raw field data?
The short answer is no, the long answer, is you could serialize your MyModel instance yourself:
simplejson.dumps([{'pk': m.pk, 'name': m.name} for m in MyModel.objects.filter(...)])
I have written a serialization framework for Python called any2any
which include (de)serializers for Django
and which allows you to do that easily.
It will be way cleaner than the DIY way.
Hope that helps !

implementing a custom UploadHandler in django

We've got some clients sending a custom POST of a data blob to our django servers.
They do things in a rather funky way that I'd rather not get into - and we've since moved on from making that particular format the norm. To make further implementations of our upload protocol more streamlined, I was looking to roll a custom UploadHandler in django to make our data handling in the views a bit more streamlined.
So, moving forward, we want all code in the views to access our POSTs via the:
data = request.FILES['something']
So, for our new submissions, we're handling that dandily.
What I'd like to be able to do is get the upload handler we've made, affectionately called LegacyUploadHandler(), to populate the request.FILES dictionary with the right parts, so the code in our view can access the parts the same way.
So, my question:
How does a custom uploadhandler actually populate the request.FILES dictionary? The django documentation doesn't really give a descriptive example of doing that.
Our particular desire is that we have a singular blob of data coming in. We custom parse it and want it to appear as the request.FILES dictionary.
The current code as it stands right now does this:
def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
files_dict = {}
files_dict = magic_parser(input_data.read())
#now what do I do?
I see examples of setting a files MultiValueDict in the http.MultiPartParser, but that seems to be outside the scope/control of where I am in my handlers.
Any ideas of how to actually do the return value? Or am I trying to populate the request.FILES object the completely wrong way?
From handle_raw_input you have to return a tuple of what will be POST and FILES on the requst. So in your case it's something like:
def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
files_dict = magic_parser(input_data.read())
return QueryDict(), files_dict
The magic_parser should return a MultiValueDict of the form {'filename': fileobj}. A fileobj is an instance of some suitable django.core.files.File subclass (or may be that class itself).