Using class as a phonebook dictionary - class

class PhoneBook:
def __init__(self):
self.contacts = {}
def __str__(self):
return str(self.contacts)
def add(self, name, mobile=None, office=None, email=None):
self.contacts["Name"] = name
self.contacts["Mobile"] = mobile
self.contacts["Office"] = office
self.contacts["Email"] = email
obj = PhoneBook()
obj.add("Kim", office="1234567", email="kim#company.com")
obj.add("Park", office="2345678", email="park#company.com")
print(obj)
I tried to make PhoneBook class to add up the dictionary lists as I put .add method to the class variable but every time the class variable calls the PhoneBook() class, the dictionary initialization occurs and only the last data remains in the dictionary(I suppose :S)
Is there any way to solve this problem? Thank you.

The issue is, you're using the same dictionary key "Name" to store your contacts. Instead, put real name as a key to dictionary and this key will hold another dictionary. For example:
import pprint
class PhoneBook:
def __init__(self):
self.contacts = {}
def __str__(self):
return pprint.pformat(self.contacts, width=30)
def add(self, name, mobile=None, office=None, email=None):
self.contacts[name] = {
"Mobile": mobile,
"Office": office,
"Email": email,
}
obj = PhoneBook()
obj.add("Kim", office="1234567", email="kim#company.com")
obj.add("Park", office="2345678", email="park#company.com")
print(obj)
Prints:
{'Kim': {'Email': 'kim#company.com',
'Mobile': None,
'Office': '1234567'},
'Park': {'Email': 'park#company.com',
'Mobile': None,
'Office': '2345678'}}

Related

Only update values if they are not null in Koltin

So i try to only update values if they are not null in the response body of my request. This is how it looks at the moment, and if i dont send all the values with it, they just get nulled in the database. Im using Kotlin with JpaRepositories.
#PutMapping(value = ["/patient"], produces = ["application/json"])
fun updateClient(#RequestBody client: Client): ResponseEntity<Client>{
val old = repository.findById(client.id).orElseThrow{ NotFoundException("no patient found for id "+ client.id) }
val new = old.copy(lastName= client.lastName, firstName = client.firstName,
birthDate = client.birthDate, insuranceNumber = client.insuranceNumber)
return ResponseEntity(repository.save(new), HttpStatus.OK)
}
This is how the model class looks like
#Entity
data class Client(
#Id
val id: String,
val lastName: String?,
val firstName: String?,
val birthDate: Date?,
val insuranceNumber: Int?
)
Is there a easier way then writing copy once for every value and checking if its not null before?
The only thing that comes to mind that might make the process easier without modifying the current model or having to create other helper model/functions would be to use the elvis operator.
val new = old.copy(
lastName = client.lastName ?: old.lastName,
firstName = client.firstName ?: old.firstName,
birthDate = client.birthDate ?: old.birthDate,
insuranceNumber = client.insuranceNumber ?: old.insuranceNumber
)
Other ways of doing this would be to create our own copy function that would ignore input nulls, or a custom constructor that does the same. But that would require more work, and it depends on the model if that makes sense or not, for the example model that would not make sense in my opinion, it would be overkill

How do I explicitly specify language of email I want to send?

I have a custom user model that have a preferred_language field. I want all the emails (activation and password reset) to be sent translated to the language that user specified in profile.
class CustomUser(AbstractBaseUser, PermissionsMixin):
...
LANGUAGE_CHOICES = (
(1, "English"),
(2, "Русский")
)
preferred_language = models.PositiveSmallIntegerField(choices=LANGUAGE_CHOICES, default=2,
verbose_name=_("Preferred language"))
I thought about setting custom email class but didn't saw in navive djoser's classes any points where I could explicitly set the language of outcome emails despite of ready-to-be-translated style of email templates:
class ActivationEmail(BaseEmailMessage):
template_name = 'email/activation.html'
def get_context_data(self):
context = super(ActivationEmail, self).get_context_data()
user = context.get('user')
context['uid'] = utils.encode_uid(user.pk)
context['token'] = default_token_generator.make_token(user)
context['url'] = settings.ACTIVATION_URL.format(**context)
return context
Reset password view (which's refference is settings.EMAIL.activation used in ActivationEmail class above):
class ResetPassword(ActionViewMixin, generics.GenericAPIView):
...
def send_password_reset_email(self, user):
context = {'user': user}
to = [get_user_email(user)]
settings.EMAIL.password_reset(self.request, context).send(to)
def send_activation_email(self, user):
context = {'user': user}
to = [get_user_email(user)]
settings.EMAIL.activation(self.request, context).send(to)
In your case I would use the override context manager that stores the current language on enter (in order to sent the email) and restores it on exit.
from django.utils import translation
def send_password_reset_email(self, user):
context = {'user': user}
to = [get_user_email(user)]
lang_code = user.lang_code # retrieve user's language code here
with translation.override(lang_code):
settings.EMAIL.password_reset(self.request, context).send(to)
def send_activation_email(self, user):
context = {'user': user}
to = [get_user_email(user)]
lang_code = user.lang_code # retrieve user's language code here
with translation.override(lang_code):
settings.EMAIL.activation(self.request, context).send(to)

'QuerySet' object has no attribute 'subs'

Can someone pls explain how can I filter users posts if user is subscriber or not?
'QuerySet' object has no attribute 'subs'
I use custom user
class Every(AbstractBaseUser):
user = models.OneToOneField(settings.AUTH_USER_MODEL, unique=True)
name = models.CharField(max_length=30, blank=True)
Here is post model:
class Post(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
text = models.TextField(max_length=1200)
A subscriber model:
class Sub(models.Model):
user = models.OneToOneField(User, related_name='user')
subs = models.ManyToManyField(User, blank=True, related_name='subs')
A view that I'm trying to use:
def tape(request, every_id):
context = {}
context.update(csrf(request))
post_form = PostForm
pform = post_form
sub = Sub.objects.filter(subs=every_id)# here I get users that intersting for my user
tape = Post.objects.filter(user=sub.subs).order_by("-timestamp")
username = request.user
context = {"username": username, "pform": pform, "tape": tape, "sub": sub,}
return render(request, 'tape.html', context)
actually it would be better to use a class view. But here is an answer with an usual view. We need to get subscription's and subscribers's ids before we start filter posts
here is even a bit more :-)
def get_user_id_list(user):
"""Returns a list of subscribers's ids"""
try:
sub = user.user
Sub.DoesNotExist:
return []
return sub.subs.all().values_list('user_id', flat=True)
def get_user_id_list_2(user):
"""Returns a list of subscription's ids"""
return user.subs.values_list('user_id', flat=True)
def tape(request):
pform = PostForm
user_id_list = get_user_id_list_2(request.user)
logger.info('user_id_list = {}'.format(user_id_list))
tape = Post.objects.filter(user_id__in=user_id_list).order_by("-timestamp")
username = request.user
context = {
"username": username,
"pform": pform,
"tape": tape,
"sub": sub,
}
return render(request, 'tape.html', context)

grails Objects query when hasMany relationship is NULL

Not able to get the list of Objects when a hasMany attribute is null.
Class User {
...
List<EMail> emails
static hasMany = [emails: EMail,... ]
static mappedBy = [emails: 'customer',...]
...
}
Where Email is another Class with some String Attributes
Now i am trying to make a simple query as:
Method 1:
def users = User.findAllByEmailsIsEmpty()
This is giving Error as:
Queries of type IsEmpty are not supported by this implementation
Method 2:
def users = User.findAllByEmailsIsNull()
This is giving all the users even those have Email object associated with it.
Then I thought of trying Criteria Query (https://grails.github.io/grails-doc/latest/ref/Domain%20Classes/createCriteria.html )
Method 3:
def userCriteria = User.createCriteria()
def users = userCriteria.list(){
sizeEq('emails', 0)
}
This gives No result ( users.size() is 0 )
Method 4:
def userCriteria = User.createCriteria()
def users = userCriteria.list(){
isNull('emails')
}
This again gives all the Users even those who don't have emails.
Method 5:
def userCriteria = User.createCriteria()
def users = userCriteria.list(){
isEmpty('emails')
}
This gives the Error :
Queries of type IsEmpty are not supported by this implementation
Method 6:
def userCriteria = User.createCriteria()
def users = userCriteria.list(){
eq('emails', null)
}
This again lists down all the users.
PS: Grails is configured with Database as MongoDB.
I would use the grep method. Something like this:
nullEmailUsers = User.list().grep {
!it.emails
}
User.findAll { emails.id != null } do the job!

Lift Framework - problems with passing url param to Snippet class

I am trying to do a simple case of /author/ and get the Lift to build a Person object based on the id passed in.
Currently i have an Author snippet
class Author(item: Person) {
def render = {
val s = item match { case Full(item) => "Name"; case _ => "not found" }
" *" #> s;
}
}
object Author{
val menu = Menu.param[Person]("Author", "Author", authorId => findPersonById(authorId), person => getIdForPerson(person)) / "author"
def findPersonById(id:String) : Box[Person] = {
//if(id == "bob"){
val p = new Person()
p.name="Bobby"
p.age = 32
println("findPersonById() id = " +id)
Full(p)
//}else{
//return Empty
//}
}
def getIdForPerson(person:Person) : String = {
return "1234"
}
}
What i am attempting to do is get the code to build a boxed person object and pass it in to the Author class's constructor. In the render method i want determine if the box is full or not and proceed as appropriate.
If i change
class Author(item: Person) {
to
class Author(item: Box[Person]) {
It no longer works but if i leave it as is it is no longer valid as Full(item) is incorrect. If i remove the val s line it works (and replace the s with item.name). So how do i do this. Thanks
The Box returned from findPersonById(id:String) : Box[Person] is evaluated and if the Box is Full, the unboxed value is passed into your function. If the Box is Empty or Failure the application will present a 404 or appropriate error page instead.
You can try double boxing your return if you want to handle this error checking yourself (so that the result of this method is always a Full Box).
def findPersonById(id:String) : Box[Box[Person]] = {
if(id == "bob"){
val p = new Person()
p.name="Bobby"
p.age = 32
println("findPersonById() id = " +id)
Full(Full(p))
}else{
return Full(Empty)
}
}
and then this should work:
class Author(item: Box[Person])