Group doesn't get client roles - python

I'm trying to assign a client role 'edit' to a group 'abc'.
All entities exists(clients, roles, group)
group_id = admin.get_group_by_path('/abc')['id']
id_client = admin.get_client_id('myclient')
admin.assign_group_client_roles(group_id, id_client,
{'name': 'edit'})
I get an error keycloak.exceptions.KeycloakPostError: 404: b'{"error":"Role not found"}'
Where can be an error?

Looking a bit a the open source code, I think you can try the following:
group_id = admin.get_group_by_path('/abc')['id']
id_client = admin.get_client_id('myclient')
clt_role = admin.get_client_role(client_id=id_client, role_name="edit")
admin.assign_group_client_roles(group_id, id_client, clt_role)

Related

how to use backref in peewee

basically im trying to write a index route that returns the posts of a business that a user is subscribed to
the last line is throwing an error for the backref (business.posts)
# query that finds all the subscriptions of the logged in user
subscriptions_query = models.Subscription.select().join(models.User).where(models.User.id == current_user.id)
# gets the businesses being followed from the subscriptions
businesses_being_followed = [subscription.following for subscription in subscriptions_query]
post_dicts = [model_to_dict(business.posts) for business in businesses_being_followed]
this is my posts model
class Post(BaseModel):
business = ForeignKeyField(Business, backref='posts')
image = CharField()
content = CharField()
date = DateTimeField(default=datetime.datetime.now)
Your example is REALLY inefficient.
Can you just do:
(Post
.select()
.join(Business)
.join(Subscription)
.where(Subscription.user == the_user_id))

Problem with continuation token when querying from Cosmos DB

I'm facing a problem with continuation when querying items from CosmosDB.
I've already tried the following solution but with no success. I'm only able to query the first 10 results of a page even though I get a token that is not NULL.
The token has a size of 10733 bytes and looks like this.
{"token":"+RID:gtQwAJ9KbavOAAAAAAAAAA==#RT:1#TRC:10#FPP:AggAAAAAAAAAAGoAAAAAKAAAAAAAAAAAAADCBc6AEoAGgAqADoASgAaACoAOgBKABoAKgA6AE4AHgAuAD4ASgAeACoAPgBOAB4ALgA+AE4AHgAqAD4ASgAeAC4APgBOAB4ALgA+AE4AIgA2AEYAFgAmADYARgAaACYAPgBKABYAKgA6AE4AHgAuAD4ATgAeAC4APgBOAB4ALgA+AE4AIgAuAD4ATgAeAC4APgBOACIAMgA+AFIAIgAyAD4AUgAmADIAQgAWACIALgBCABIAIgAyAEIAEgAiADIAQgAOACYANgBKAB4AJgA6AEYAGgAqADoATgAeAC4APgB....etc...etc","range":{"min":"","max":"05C1BF3FB3CFC0"}}
Code looks like this. Function QueryDocuments did not work. Instead I had to use QueryItems.
options = {}
options['enableCrossPartitionQuery'] = True
options['maxItemCount'] = 10
q = client.QueryItems(collection_link, query, options)
results_1 = q._fetch_function(options)
#this is a string representing a JSON object
token = results_1[1]['x-ms-continuation']
data = list(q._fetch_function({'maxItemCount':10,'enableCrossPartitionQuery':True, 'continuation':token}))
Is there a solution to this? Thanks for your help.
Please use pydocumentdb package and refer to below sample code.
from pydocumentdb import document_client
endpoint = "https://***.documents.azure.com:443/";
primaryKey = "***";
client = document_client.DocumentClient(endpoint, {'masterKey': primaryKey})
collection_link = "dbs/db/colls/coll"
query = "select c.id from c"
query_with_optional_parameters = [];
q = client.QueryDocuments(collection_link, query, {'maxItemCount': 2})
results_1 = q._fetch_function({'maxItemCount': 2})
print(results_1)
token = results_1[1]['x-ms-continuation']
results_2 = q._fetch_function({'maxItemCount': 2, 'continuation': token})
print(results_2)
Output:

Django ORM multiple distinct and order by

I work on a simple chat app. I need to query db for an user to get last message of user conversation to other users. Same as main page of whatsapp and telegram.
Model:
class CHAT(models.Model):
sender_uid = models.CharField(max_length=150, db_index=True)
receiver_uid = models.CharField(max_length=150, db_index=True)
message = models.TextField(verbose_name='Message Text')
created = models.IntegerField(default=created_time_epoch)
I tried this query:
message_list = self.model.objects.filter(Q(sender_uid=user_uid)|Q(receiver_uid=user_uid)).order_by('receiver_uid', 'sender_uid', '-created').distinct('receiver_uid', 'sender_uid')
Output:
<QuerySet [<CHAT: ted#ted.com Message: hello 4 To: saeed#saeed.com>, <CHAT: marshal#marshal.com Message: hello6 To: saeed#saeed.com>, <CHAT: saeed#saeed.com Message: hello 5 To: ted#ted.com>]>
My problem is I get two last message from each conversation (if both user send message to each other), In one of them user is sender and in other one user is receiver.
For now I handle it with below code:
message_send_list = list(self.model.objects.filter(sender_uid=user_uid).order_by('receiver_uid', '-created').distinct('receiver_uid'))
message_receive_list = list(self.model.objects.filter(receiver_uid=user_uid).order_by('sender_uid', '-created').distinct('sender_uid'))
temp_list = []
for s_message in message_send_list:
r_message = next((item for item in message_receive_list if item.sender_uid == s_message.receiver_uid), None)
if r_message is not None:
message_receive_list.pop(message_receive_list.index(r_message))
if s_message.created > r_message.created:
temp_list.append(s_message)
else:
temp_list.append(r_message)
else:
temp_list.append(s_message)
temp_list.extend(message_receive_list)
Output:
[<CHAT: saeed#saeed.com Message: hello 5 To: ted#ted.com>, <CHAT: marshal#marshal.com Message: hello6 To: saeed#saeed.com>]
My question is how can I get this result in one query? Problem is user can be sender and receiver of message and I can't distinguish which one is last message of conversation. How to filter or distinct on that?
Based on the description of the problem, you make it a bit too complex. You can obtain the other person with a conditional expression [Django-doc]. So by first making a "reduction" where we take the other person, we can then use a uniqueness filter for that:
from django.db.models import Case, F, When
last_messages = self.model.objects.filter(
Q(sender_uid=user_uid) | Q(receiver_uid=user_uid)
).annotate(
other=Case(
When(sender_uid=user_uid, then=F('receiver_uid')),
default=F('sender_uid'),
output_field=CharField()
)
).order_by('other', '-created').distinct('other')
Furthermor all Chat objects will have an extra attribute: other that thus contains the non-user_uid side.

Python - iterate through a list

I'm trying to automate email reporting using python. My problem is that i cant pull the subject from the data that my email client outputs.
Abbreviated dataset:
[(messageObject){
id = "0bd503eb00000000000000000000000d0f67"
name = "11.26.17 AM [TXT-CAT]{Shoppers:2}"
status = "active"
messageFolderId = "0bd503ef0000000000000000000000007296"
content[] =
(messageContentObject){
type = "html"
subject = "Early Cyber Monday – 60% Off Sitewide "
}
}
]
I can pull the other fields like this:
messageId = []
messageName = []
subject = []
for info in messages:
messageId.append(str(info['id']))
messageName.append(str(info['name']))
subject.append(str(info[content['subject']]))
data = pd.DataFrame({
'id': messageId,
'name': messageName,
'subject': subject
})
data.head()
I've been trying to iterate though content[] using a for loop, but i can't get it to work. Let me know if you have any suggestions.
#FamousJameous gave the correct answer:
That format is called SOAP. My guess for the syntax would be info['content']['subject'] or maybe info['content'][0]['subject']
info['content'][0]['subject'] worked with my data.

How to fix a KeyError in django?

print user_dic[id] displays the right result PersonA. This is when I input the id manually.
user_stream = {u'2331449': u'PersonB', u'17800013': u'PersonA'}
user_dic= {}
for item in user_stream:
user_dic[item['id']] = item['name']
id = '17800013'
print user_dic[id] #returns the right value
However, when I try to put the user_id through a for loop that iterates through json I get an error: KeyError at 17800013 for the line name = user_dic[user_id]. I don't understand why the user_dic[id] works when manually inputting the id, but user_dic[user_id] doesn't work when going through the for loop even though the input is the same.
#right fql query
fql_query = "SELECT created_time, post_id, actor_id, type, updated_time, attachment FROM stream WHERE post_id in (select post_id from stream where ('video') in attachment AND source_id IN ( SELECT uid2 FROM friend WHERE uid1=me()) limit 100)"
fql_var = "https://api.facebook.com/method/fql.query?access_token=" + token['access_token'] + "&query=" + fql_query + "&format=json"
data = urllib.urlopen(fql_var)
fb_stream = json.loads(data.read())
fb_feed = []
for post in fb_stream:
user_id = post["actor_id"]
name = user_dic[user_id] #this is the line giving me trouble
title = post["attachment"]["name"]
link = post["attachment"]["href"]
video_id = link[link.find('v=')+2 : link.find('v=')+13]
fb_feed.append([user_id, name, title, video_id])
There is no need for user_dic. What you are doing in first part is just a redundant work and you are also doing it wrong. Your user_stream is already in a form how you wanted it. Your first part should contain this line:
user_stream = {u'2331449': u'PersonB', u'17800013': u'PersonA'}
And in second part (at line where you are facing problem) you should do:
name = user_stream[user_id]
If you think that you will face KeyError then dict has a method .get, which returns None if the Key is not found. You can specify your value instead of None to return if there is KeyError
name = user_stream.get('user_id')
#returns None by default
name = user_stream.get('user_id', '')
#returns empty string now
#on both cases exception will not raised

Categories

Resources