List users connected to django-channels Group (channels 1.x) - python

So, I got as far as finding the group_channels function, but this doesn't seem to store user info. Example:
channel_layer = get_channel_layer()
context['players_list'] = channel_layer.group_channels('lobby')
I get {'players_list': ['daphne.response.WbZyUfNixL!sbzfJEzdPp', 'daphne.response.KfDHQnHLdw!DpoOqdGute', 'daphne.response.JqlcVVMuny!xHLDSaCzUz', 'daphne.response.mWrYVXDKoI!AjkyadSsPe']} as a response.
How can I list users connected to Group('lobby')? Thanks in advance

You are in the right path to the solution, that is how it is actually done. Perhaps what you're missing is adding the proper procedures to the consumer, so it adds the required data.
In django-channels v.2.x the consumer includes this information automatically, but you have to add it manually in v.1.x, using for that a decorator or a proper declaration inside a Generic Consumer, as explained in the documentation.

Related

When the get_user(..) function is called, additional information cannot be loaded

I'm having a similar problem, but I haven't been able to find a solution.
api.get_user with Tweepy will not give description
I use tweepy (4.8.0) and auth 2.0 (bearer_token)
I tried to load user information by using get_user(...) like this
client = tweepy.Client(
bearer_token=bearer_token
)
result = client.get_user(username="name", user_fields=['created_at'])
I expected to get additional data put in the user_fields, but only simple basic data was passed.
Response(data=<User id=1234 name=NAME username=name>, includes={}, errors=[], meta={})
Maybe I'm missing something or made a mistake?
save me plz...
My answer to that question applies here as well.
From the relevant FAQ section in Tweepy's documentation:
Why am I not getting expansions or fields data with API v2 using Client?
If you are simply printing the objects and looking at that output, the string representations of API v2 models/objects only include the default attributes that are guaranteed to exist.
The objects themselves still include the relevant data, which you can access as attributes or by key, like a dictionary.

FIX 4.4 MarketDataRequest Conditionally Required Field Missing (299)

I wrote a program that sends the following
to App: 8=FIX.4.4|9=156|35=V|34=2|49=id|52=sometime|56=id1|146=1|55=EURUSD|460=4|167=FOR|262=1|263=1|264=1|265=0|267=2|269=0|269=1|10=114|
I receive this. I get the bid and the offer as expected:
from App 8=FIX.4.4|9=217|35=W|34=4|49=id1|52=sometime|56=id|42=sometime1|55=EURUSD|262=1|268=2|269=0|270=1.12438|271=50000|269=1|270=1.12442|271=50000|10094=sometime2|10=002|
But as I request snapshot + update on full refresh, it sends back the following;
to App: 8=FIX.4.4|9=118|35=j|34=3|49=id|52=sometime|56=id1|45=2|58=Conditionally Required Field Missing (299)|372=W|380=5|10=210|
Data Dictionary of my broker is the following: DataDictionary
UseDataDictionary=Y
ValidateUserDefinedFields=N # tried with Y, same
DataDictionary=C:\Users\Documents\FIX44.xml
Any idea of what I did wrong please?
Thank you folks!
Check your counterparty's documentation for what fields they expect you to send in the MarketDataRequest (35=V) message.
In the default DataDictionary, QuoteEntryID (tag 299) doesn't belong to MarketDataRequest or in any of the repeating groups it contains. This means that your counterparty has made a DD customization and added it somewhere.
So your main mistake is that you are not looking at your counterparty's docs, and your local DD is not in sync with theirs. That latter part is not burning you here in this question, but it will burn you later. Get your DD in sync!
Back to this issue: Sure, you're adding QuoteEntryID to the message, but you're adding it to the top-level of the message body, and your counterparty probably isn't looking for it there. If you look again at the default DataDictionary, QuoteEntryID always belong to a group, so your counterparty probably wants it in in a group also. You just need to read their docs to find out which group it is.
TLDR: Counterparties always customize the DataDictionary -- always read your counterparty's docs!

Preserving value of variables between subsequent requests in Python Django

I have a Django application to log the character sequences from an autocomplete interface. Each time a call is made to the server, the parameters are added to a list and when the user submits the query, the list is written to a file.
Since I am not sure how to preserve the list between subsequent calls, I relied on a global variable say query_logger. Now I can preserve the list in the following way:
def log_query(query, completions, submitted=False):
global query_logger
if query_logger is None:
query_logger = list()
query_logger.append(query, completions, submitted)
if submitted:
query_logger = None
While this hack works for a single client sending requests I don't think this is a stable solution when requests come from multiple clients. My question is two-fold:
What is the order of execution of requests: Do they follow first come first serve (especially if the requests are asynchronous)?
What is a better approach for doing this?
If your django server is single-threaded, then yes, it will respond to requests as it receives them. If you're using wsgi or another proxy, that becomes more complicated. Regardless, I think you'll want to use a db to store the information.
I encountered a similar problem and ended up using sqlite to store the data temporarily, because that's super simple and easy to manage. You'll want to use IP addresses or create a unique ID passed as a url parameter in order to identify clients on subsequent requests.
I also scheduled a daily task (using cron on ubuntu) that goes through and removes any incomplete requests that haven't been completed (excluding those started in the last hour).
You must not use global variables for this.
The proper answer is to use the session - that is exactly what it is for.
Simplest (bad) solution would be to have a global variable. Which means you need some in memory location or a db to store this info

Python-eve: Combine role based and user-restricted access?

I have a fairly simple use case but can't figure out how to stitch it together.
Basically I want to use user-restricted access for regular users, i.e. they can upload files via an API and other users cannot touch those files via the API.
At the same time I want a special user (admin/super-user) to be able to use the API to GET e.g. all files for a specific user.
Does anybody have any pointers to examples of this or can help point me in the right direction to do this?
One idea I thought of was to pass an additional (optional) parameter to check_auth containing the _id of the user that the admin wants to look at, so if the admin passes in that parameter it will override the admins own _id. Would this work or does check_auth have a set parameter list? any security issues with this approach?
Or is there a better approach - a separate API instance perhaps that uses the same mongoDB collections (is that even possible?).
Regards,
Anton

Protocols list in Twisted app

I would like to know which is best way to manage the protocols active in Twisted or if there is no concrete way.
In my current app I created a dictionary where there are two fields. At one I put the remote user and the local user to another. Both fields are lists so I can add several items.
The method I'm using is the following. First I check by a try-except if the dictionary exists. If there is no dictionary, I create it.
try:
if self.factory.active_protocols:
log.msg('Active protocols dictionary already created')
except Exception as e:
log.err(e)
self.factory.active_protocols = {}
self.factory.active_protocols.setdefault('localUsr', [])
self.factory.active_protocols.setdefault('remoteUsr', [])
Then I check if the local user is in the local users list. If there is no user I adds it to the list of local users. If the list exists, it throws an error.
if sUsername in self.factory.active_protocols['localUsr']:
log.err('Client already logged in')
raise UnauthorizedLogin('Client already logged in')
else:
# Attach local user to active protocols list.
self.sUsername = sUsername
self.factory.active_protocols['localUsr'].append(self.sUsername)
If the conditions are right the remote user is also added to the list of remote users using the following code.
# If time is correct, attach remote user to active_protocols
self.factory.active_protocols['remoteUsr'].append(remoteUsr)
When I disconnect users, I delete the lists using the following code.
if self.sUsername in self.factory.active_protocols['localUsr']:
self.factory.active_protocols['localUsr'] = []
if self.remoteUsr in self.factory.active_protocols['remoteUsr']:
self.factory.active_protocols['remoteUsr'] = []
Is there a more correct way to do it? Should implement some special kind of dictionary? To Create a list? Does using a proprietary method of Twisted?
I have been looking for information about internet and I have not found anything conclusive about it.
Thank you!
No, there is no special type of list or dictionary in Twisted you can use for this.
Twisted's job is turning network events into method calls on your objects. Once you you are implementing those methods on those objects, as much as possible, you want to use regular Python data structures. There are certain things in Twisted, like Deferreds, which are data structures you can use to implement certain asynchronous data-flow patterns, but for something as simple as a basic observer pattern with multiple entities in a list, regular lists and dictionaries and such are just fine.

Categories

Resources