Does Django RestFramework supports async views and class? - python-3.x

It will be helpful if someone helps me with a clear cut answer. If Yes any suggestion how to approach... coz, I try to use async with DRF but I am always ending with
"AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'coroutine'>" this error

Short answer: no.
(as for 02.12.2021, djangorestframework==3.12.4)
asnyc is not mentioned once in DRF docs.
Documentation search async No results found
Django does "support" async so DRF should too but all DRF features were programmed with non-async in mind and are not ready to work with async. By making your DRF code async you won't be able to use all DRF features flawlessly.

Just use fastapi, you will thank me later

Related

How to verifyZeroInteractions on a mock with ts-mockito

I am searching for an analogous to verifyZeroInteractions(mockObject) or verifyNoMoreInteractions(mockObject) with ts-mockito, but with no success so far. Is there a functionality to validate that no calls on any method have been done on a mock?
Thanks,

Dynamically generate Flask-RESTPlus routes

I am trying to abstract away some of the route class logic (i.e. I am looking to dynamically generate routes). api.add_resource seemed like the right place to do this.
So this is what I am trying to do:
# app.py
from flask import Flask
from flask_restplus import Api, Resource, fields
from mylib import MyPost
# Define my model
json_model = api.schema_model(...)
api.add_resource(
MyPost,
'/acme',
resource_class_kwargs={"json_model": json_model}
)
And then in mylib:
# mylib.py
def validate_endpoint(f):
def wrapper(*args, **kwargs):
return api.expect(json_fprint)(f(*args, **kwargs))
return wrapper
class MyPost(Resource):
def __init__(self, *args, **kwargs):
# Passed in via api.add_resource
self.api = args[0]
self.json_model = kwargs['json_model']
# I can't do this because I don't have access to 'api' here...
# #api.expect(json_model)
# So I am trying to make this work
#validate_endpoint
def post(self):
return {"data":'some data'}, 200
I don’t have access to the global api object here so I can’t call #api.expect(json_model). But I do have access to api and json_model inside of the post method. Which is why I am trying to create my own validate_endpoint decorator.
This does not work though. Is what I am trying to do here even possible? Is there a better approach I should be taking?
Stop using flask-restplus. Thats the most valuable answer I can give you (and anyone else).
Ownership is not there
Flask-restplus is a fork of flask-restful. Some engineers started developing features that suited them. The core guy has ghosted the project so its been officially forked again as Flask-Restx.
Poorly designed
I used to love flask when I was a yout’. I’ve realized since then that having global request, application, config that all magically update is not a good design. Their application factory pattern (to which flask-restplus conforms) is a style of statefully mutating the application object. First of all, Its hard to test. Second of all, it means that flask-restplus is wrapping the app and therefore all of the requests/handlers. How can anyone thing thats a good thing? A library whose main feature is endpoint documentation has its filthy hands all over every one of my requests?? (btw, this is whats leading to your problem above) Because my post is serious and thoughtful I’m skipping my thoughts on the Resource class pattern as it would probably push me into the waters of ranting.
Random Feature Set
A good library has a single purpose and it does that single thing well. Flask-restplus does 15 things (masking, swagger generation, postman generation, marshaling, request arg validation). Some features you can’t even tell are in the libraries code by reading the docs.
My solution to your problem
If you want to document your code via function decorators and models use a tool that does that alone and does it well. Use one that won’t touch your handlers or effect your actual request decorators. Use oapispec for swagger generation. For the other features of flask-restplus you’ve got marshmallow for marshaling request/response data, pydantic for validating request objects and args, and so on.
btw, I know all this because I had to build an api with it. After weeks of fighting the framework I forked it, ripped it apart, created oapispec, and trashed it from the project.

Using Sinon SinonStubbedInstance with Typescript

I'm using sinon to stub an instance of express-Request.
It looks something like this:
let req = sinon.createStubInstance(Request);
My method accepts req: Request but my IDE complains about me using SinonStubbedInstance<Request> rather than Request.
I've tried using req as Request but I still get a warning about 'may be a mistake' and that I should first cast to unknown and only then to Request.
I actually don't need anything from this parameter so I really just want to stub it quickly and easily.
When using it in the call to your method, just cast it:
myMethod(req as any);
I understand that this was posed 3 years ago, but since the only answer given is wrong, I feel obliged to comment, for someone else might benefit from it.
It's strongly discouraged to use as any and your compiler should complain about this (unless you have a very good reason not to, you should use strict compiler option).
Casting to unknown and then to your type seems unintuitive, but it is a cleaner way than casting to any. If you use any you might be better off not using typescript at all.
https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#any
Consider doing
let req: SinonStubbedInstance<Request> & Request = sinon.createStubInstance(Request);
instead.
P.S.: Also, the use of let seems suspicious (sure cannot use const?), but that's a different topic.

What is the preferred way to call synchronous code from async routes in Sanic?

I'm researching Sanic as we're looking for alternatives to our flask-based rest services. I'm intriguied by the async nature of sanic, but I know that we'll bump into a lot of code that simply won't support async (we use a ton of boto3 and also some ORMs on top of DynamoDB for example, none of which support awaiting).
So: I need to find the cleanest way of being able to run synchronous code inside an async framework like Sanic. In python 3.7 there's the asyncio.create_task call which I'm finding interesting.
Wondering if this would be a possible way to go:
main.py:
#default boilerplate sanic code excluded for brevity
from app_logic import AppLogic
#app.route("/")
async def test(request):
task = await asyncio.create_task(AppLogic.sync_request('https://stuff.com'))
return json({"hello": "world", 'status_code': task.status_code})
app_logic.py:
import requests
class AppLogic(object):
#staticmethod
async def sync_request(url='https://myurl.com'):
#Some non-async library/code thingy
print('requesting the thing')
return requests.get(url)
This seems to work, and the the returned task object is a regular requests response.
However, I have no idea if this is "safe" - eg I'm not sure how I can investigate the event loop and verify that it's not blocking in any way. I'm sure there's also other reasons for this approach being completely dumb, so lay them on me :-)

ServiceStack ProtoBuff Serialization to custom stream

a few days ago i posted a question about Serializing the ResponseStatus property with BinaryFormatter. Mythz pointed out it wasnt the fastest way to go, so i decided to switch to another formatter. Tried ProtoBuff and MsgPack, and am on ProtoBuf now.
My real question is: im trying to grasp how Protobuf knows how ServiceStack Dto's should be serialized. I tried adding all the possible attributes to my existing dto, ProtoContract and ProtoMember(0,1,2,3,etc), but also DataContract and DataMember.
On top of that i dont use ServiceStack's own client, but try to serialize the request to an existing stream.
If i dont do this:
ServiceStack.ProtoBuf.ProtoBufFormat.Model.Add (typeof(NameSpacePlaceholder.Service.Dto.GetNodes), false);
i get an error about Types and Contracts that cannot be infered,
If i do add that piece of code, all continues great, but the deserialized object is empty.
Im using this to Serialize:
ServiceStack.ProtoBuf.ProtoBufFormat.Model.Serialize (ms, myObject);
and to Deserialize:
ServiceStack.ProtoBuf.ProtoBufFormat.Model.Deserialize (ms, null, deserializationType);
I think im missing something here. Could it have something to do with namespaces? I looked into some code from ServiceStack.ProtoBuff, it isnt so hard to understand, but i cannot get it going.
Things that are unclear to me now:
Is there a need to add Attributes to the existing DTO's ? (in ProtoBuf V2 i can also do it in code, i read, but for now i can also alter the existing DTO's)
Do i need to initialize the Request(and response) DTO's, in my Client(Serialize) as wel in my Server(Deserialize)
Is there some reason why i should not be serializing to my own Stream ?
Many thanks,
I hate it to post an answer myself, it means i havent searched enough in the first place
I learned the following attributes are very important:
[ProtoContract]
[ProtoMember(X)]
[ProtoInclude(X,typeof(DerivingClass))]
For now i learned something new: why class inheritance in DTO's is not advisable.
I've got it going now, and will try to make it real-life friendly..

Resources