how to apply two serializers in one action in rails 5? - active-model-serializers

I want to serialize incoming_requests and outgoing_requests with a few column values with customized name.
Without serializer, I wrote codes like below.
def index
incoming_requests = FriendRequest.select('id', 'user_id', 'created_at').where(:friend => current_user).order(created_at: :desc)
outgoing_requests = current_user.friend_requests.select('id', 'friend_id', 'created_at')
render json: {
incoming_requests: incoming_requests,
outgoing_requests: outgoing_requests
}
end
However, I want to replace 'select' with serializers. After applying serializers on the output for the codes below, I want to achieve the same result as the result from the above codes.
def index
incoming_requests = FriendRequest.where(:friend => current_user).order(created_at: :desc)
outgoing_requests = current_user.friend_requests
render json: {
incoming_requests: incoming_requests, // want to apply serializer
outgoing_requests: outgoing_requests // want to apply serializer
}
end
So, how can I serialize these incoming and outgoing request objects seperately?

Related

NLog formatting as JSON using BeginScope

How do you get NLog to format data as JSON when using ILogger.BeginScope? It appears the the # symbol is ignored, or just not coded to work with begin scope? ref documentation
I've tried every combination I can think of and they all result in the object being ToString'd rather than converted to JSON. The end result is that the data is not searchable as "structured" data because it's just a string.
1st Attempt:
using (_logger.BeginScope(new Dictionary<string, object>
{
["CacheValue"] = value
}))
{
_logger.LogInfo("howdy");
}
Result in Seq:
howdy
CacheValue MyApp.ViewModels.EntityIssueQueueGetModel
2nd Attempt:
using (_logger.BeginScope(new Dictionary<string, object>
{
["#CacheValue"] = value
}))
{
_logger.LogInfo("howdy");
}
Result in Seq:
howdy
#CacheValue MyApp.ViewModels.EntityIssueQueueGetModel
3rd Attempt:
using (_logger.BeginScope(new Dictionary<string, object>
{
["{#CacheValue}"] = value
}))
{
_logger.LogInfo("howdy");
}
Result in Seq:
howdy
{#CacheValue} MyApp.ViewModels.EntityIssueQueueGetModel
4th Attempt:
using (_logger.BeginScope("{#CacheValue}", value))
{
_logger.LogInfo("howdy");
}
Result in Seq:
howdy
#CacheValue MyApp.ViewModels.EntityIssueQueueGetModel
This next bit works, but is not what I need. This prints the JSON out along with the friendly message. I only want the JSON data to be associated with the log for querying purposes; not shown as part of the message.
Working example:
_logger.LogInfo("howdy. {#CacheValue}", value);
Result in Seq:
howdy. {"Issues":[],"TotalRecords":0,"Success":true,"TraceId":"00-3b8ef0c2d84714e0c81a07cbb5d50444-8269922e21923478-00","Errors":[]}
CacheValue {
"Issues": [],
"TotalRecords": 0,
"Success": true,
"TraceId": "00-3b8ef0c2d84714e0c81a07cbb5d50444-8269922e21923478-00",
"Errors": []
}
NLog doesn't recognize message-template-syntax for Scope-Context-Properties.
NLog JsonLayout can format Scope-context Properties like this:
<layout xsi:type="JsonLayout" includeScopeProperties="true" maxRecursionLimit="1">
</layout>
See also: https://github.com/NLog/NLog/wiki/JsonLayout
It is also possible to format a single Scope-context Property as Json like this:
layout="${scopeproperty:CacheValue:format=#}"
See also: https://github.com/NLog/NLog/wiki/ScopeProperty-Layout-Renderer
It is also possible to format the entire Scope-Nested-Stack as Json like this:
layout="${scopenested:format=#}"
See also: https://github.com/NLog/NLog/wiki/ScopeNested-Layout-Renderer
Maybe consider posting your question at https://github.com/datalust/nlog-targets-seq

DRF how to return multiple datas inside the same serializer

I will try to make my problem as simple as possible:
I have this serializer:
class DatesSerializer(serializers.Serializer):
date = serializers.CharField(max_length=10)
... bunch of stuff and Others serializers
and on my view.py I have this piece of code:
dates = ["2021-05-02", "2021-06-28", "2021-07-02"]
...
for date in dates:
faults = DatesSerializer({
"date":date,
...
})
return Response({"faults":faults.data, status=200})
I receive a response like these:
{
"faults":{
"date":"2021-07-02"
....
}
}
what I wanted was a response like this one
{
"faults":{
"date":"2021-07-02"
....
},
{
"date":"2021-06-28"
....
}, {
"date":"2021-05-02"
....
}
}
I understand that on my loop I'm overwriting my serializer and that's why I just have the last entry, but I have tried to overcome this by adding on a dict and got nowhere since the key will always be the same, and I'm stuck on how to fix this
What you want is not a valid object. You want a list, and this easily can be accomplished in a loop by appending serializer data on each iteration.
res = []
for date in dates:
serializer = DatesSerializer({
"date":date,
...
})
res.append(serializer.data)
return Response({ "faults": res }, status=200)

How can I store data coming from Binance Websocket?

I am currently trying to store some data streaming from a Binance Miniticker Websocket, but I can't figure out a way to do so.
I would like to append the data to an existing dictionary, so that I can access it as historical data.
def miniticker_socket(msg):
''' define how to process incoming WebSocket messages '''
if msg[0]['e'] != 'error':
for item in msg:
miniticker["{0}".format(item['s'])] = {'low': [],'high': [], 'open': [], 'close':[],'timestamp':[], 'symbol':[] }
miniticker[item['s']]['close'].append(msg[msg.index(item)]['c'])
print(miniticker[item['s']])
else:
print('there has been an issue')
bsm = BinanceSocketManager(client)
#ticker_key = bsm.start_symbol_ticker_socket(crypto, ticker_socket)
miniticker_key = bsm.start_miniticker_socket(miniticker_socket)
bsm.start()
The issue I'm having in the code above is that the data does not get appened, because every time the Websocket calls back the function, it also defines the dictionary as empty. I can't define the dictionary outside the Websocket because the name of the dictionary is given by the item['s'] element inside the socket.
I also tried returning the whole data and calling the callback function in another function but this generates another error saying "msg is not defined."
I would appreciate your feedback on this!
Thanks
Also, you can try to check if a key already exists in the dictionary miniticker:
key = "{0}".format(item['s'])
if key not in miniticker.keys():
miniticker["{0}".format(item['s'])] = {...}
So you will not redefine it as an empty dictionary each time
I think what you might want is a global variable dictionary containing dictionary values that come in from the ticker. You will need something unique for the keys of the global dictionary.
For example, you could use a string datetime:
timestamp_key = datetime.datetime.now().isoformat()
global_dict[timestamp_key] = miniticker["{0}".format(item['s'])] = {'low': [],'high': [], 'open': [], 'close':[],'timestamp':[], 'symbol':[] }
global_dict[timestamp_key][item['s']]['close'].append(msg[msg.index(item)]['c'])
The global dict would end up something like this:
{
"2020-03-25T17:14:19.382748": {
"your_data_key1": { "more": "data" }
},
"2021-03-25T17:15:19.249148": {
"your_data_key1": { "more": "data_from_another_update" }
}
}

How to apply filter on finch endpoint without using finagle filters?

I have more than one endpoints.I am able to apply common filters on endpoints using finagle filter.But now I want to apply a filter on a specific endpoint.
How can I achieve this?
I had a similar question (for basic authentication filtering) that popped up while playing with redbubble's finch template which I partially solved in the following way:
class AuthenticatedEndpoint[A](e: Endpoint[A]) extends Endpoint[A] { self =>
final def apply(mapper: Mapper[A]): Endpoint[mapper.Out] = mapper(self)
final def apply(input: Input): Endpoint.Result[A] =
if (checkSession(input.request)) {
e(input)
} else {
// TODO return something meaningful to the caller (if possible?)
EndpointResult.Skipped
}
}
object AuthenticatedEndpoint {
def validSession[A](e: Endpoint[A]): Endpoint[A] = new AuthenticatedEndpoint(e)
}
(with checkSession returning true if all is well with the request). Then my api is defined as:
val api = "v1" :: loginApi :+: validSession(peopleApi :+: healthApi :+: adminApi)
This works well in the sense that requests without a session won't have access to the endpoints passed to validSession, but I have yet to find an easy way to return an error message to the caller, and I'd be curious to know if I chose the right path here.
This is how I got around it. It's probably not ideal but works.
class AuthenticatedEndpoint[A](e: Endpoint[A])(implicit auth: Request => Boolean) extends Endpoint[A] { self =>
final def apply(mapper: Mapper[A]): Endpoint[mapper.Out] = mapper(self)
final def apply(input: Input): Endpoint.Result[A] =
if (auth(input.request)) {
e(input)
} else {
EndpointResult.Matched[Nothing](input, Rerunnable( Unauthorized(new Exception(s"Authentication Failed."))) )
}
}
object AuthenticatedEndpoint {
def validSession[A](e: Endpoint[A]): Endpoint[A] = new AuthenticatedEndpoint(e)
}

Convert WebService Response into Json Arrary and Jsobobject using Groovy

I am testing RESTful webservice using SoapUI. We use Groovy for that.
I am using jsonslurper to parse the response as Object type.
Our reponse is similar to this:
{
"language":[
{
"result":"PASS",
"name":"ENGLISH",
"fromAndToDate":null
},
{
"result":"FAIL",
"name":"MATHS",
"fromAndToDate": {
"from":"02/09/2016",
"end":"02/09/2016"
}
},
{
"result":"PASS",
"name":"PHYSICS",
"fromAndToDate":null
}
]
}
After this, I stuck up on how to.
Get Array (because this is array (starts with -language)
How to get value from this each array cell by passing the key (I should get the value of result key, if name='MATHS' only.)
I could do it using Java, but as just now learning Groovy I could not understand this. We have different keys with same names.
You can just parse it in to a map, then use standard groovy functions:
def response = '''{
"language":[
{"result":"PASS","name":"ENGLISH","fromAndToDate":null},
{"result":"FAIL","name":"MATHS","fromAndToDate":{"from":"02/09/2016","end":"02/09/2016"}},
{"result":"PASS","name":"PHYSICS","fromAndToDate":null}
]
}'''
import groovy.json.*
// Parse the Json string
def parsed = new JsonSlurper().parseText(response)
// Get the value of "languages" (the list of results)
def listOfCourses = parsed.language
// For this list of results, find the one where name equals 'MATHS'
def maths = listOfCourses.find { it.name == 'MATHS' }

Resources