positional arguments python crash course? - python

def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
Output:
{'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}
I dont understand why the key and value first_name and last_name was placed at the last? aren't they supposed to be placed before location and field? because of positional arguments??
please help.

In case you'd want the positional arguments passed in to the function to come before the **kwargs passed in, you could use the dict(..., **kwargs) approach to build a new dict object:
def build_profile(first, last, **addl_info):
"""Build a dictionary containing everything we know about a user."""
user_info = {'first_name': first, 'last_name': last, **addl_info}
return user_info
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
Out:
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}

Related

Additional key: values not being added to Python Dictionary

Summary problem: Building an API endpoint and trying to push new key:values to the existing API. Not knowing if I am correctly adding key value pairs or not. Familiar with Ruby but first time Python user!
Context:
I currently have a method that will format given information into a Python Dictionary to be used as a JSON for my API. I have one method that pushes information to this method but another that is not functioning. Can anybody spot why?
Things I've tried:
Feature test using command line environment
Getting visibility - Printing
Environment:
MacOS 11.1, python 3.9.1, VSCode
Code:
METHOD THAT IS FORMATTING
class Database(object):
def __init__(self):
self.data = {}
def insert_entity(self, kind, entity):
kind_dict = self.data.get(kind, {})
entity_id = entity.get('id', str(uuid4()))
if not isinstance(entity_id, str):
raise Exception('Entity `id` must be a string')
entity['id'] = entity_id
kind_dict[entity_id] = entity
self.data[kind] = kind_dict
return entity
def get_entity(self, kind, entity_id):
entities = self.data.get(kind, {})
return entities.get(entity_id, None)
def get_all_entities(self, kind):
return list(self.data.get(kind, {}).values())
METHOD THAT IS WORKING:
def initialise_user_data():
first_names = ['Ron', 'Paul', 'Simon', 'David', 'Phil', 'Ada', 'Julia']
last_names = [
'Legend', 'Mac', 'Stuartson', 'Sili', 'Word', 'Nine',
'Smith'
]
for index in range(len(first_names)):
first_name = first_names[index]
last_name = last_names[index]
email = str(random.randint(0, 9999)) + "#email.com"
user_data = {
'firstName': first_name,
'lastName': last_name,
'email': email
}
database.insert_entity('User', user_data)
METHOD THAT IS NOT WORKING:
def initialise_event_data():
users = database.get_all_entities('User')
for user in users:
for _ in range(random.randint(0, 10)):
database.insert_entity(
'Event', {
'userId': user['id'],
'points': 100,
'eventName': 'levels_completed'
})
ALL METHODS ARE INVOKED AS SUCH:
database = InMemoryDatabase()
initialise_data()
def initialise_data():
initialise_user_data()
initialise_event_data()
initialise_follow_data()

How to clear text field using alike switch case in python

# this function clears text from fields.
def clear_text(self, field):
switcher = {
'company': self.company_name_textbox_id,
'email': self.email_textbox_id,
'website': self.website_textbox_id,
'phone': self.phone_textbox_id,
}
switcher.get(self.driver.find_element_by_id(field).clear(), "Invalid field provided")
def test03_existing_company_validation(self):
company = CompanyPage(self.driver)
company.clear_text('company')
clear_text is not working. Am I doing it right? How to fix it?
Seems like your logic is going in the wrong order. You should probably be passing field to your switcher dictionary and then passing the value from that to find_element_by_id.
self.driver.find_element_by_id(switcher[field]).clear()

How to add fields in MongoDb document which already exist?

I'm trying to get some POST requests using Postman to MongoDb and everything works well.
Following is the code:
def add_npo():
add_new_npo = mongo.db.npos
name = request.json['name']
description = request.json['description']
category = request.json['category']
status = request.json["status"]
npo_id = add_new_npo.insert({'name': name, 'description':
description, 'category': category,'status': status})
new_npo = add_new_npo.find_one({'_id': npo_id })
output = {'name': new_npo["name"], 'description':
new_npo["description"], 'category': new_npo["category"], 'status':
new_npo["status"]}
return jsonify({'result' : output})
But how can I add new fields on the document without assigning them in advance?
You can add new fields on the document by update operation.
For example,
db.col.update({your filter}, {"$set": {"newField": newFieldValue}})

How to manually create a form and then validate it in Flask wtform?

How can I populate my form manually and then validate it?
class TestForm(Form):
name = StringField('name', validators=[InputRequired()])
age = IntegerField('age', validators=[InputRequired()])
I try to build the form with arbitrary data and validate:
data = {'name': 'bob', 'age': 33}
tform = TestForm(name=data['name'], age=data['age'])
if tform.validate():
print 'success!'
else:
print tform.errors
The result prints out errors:
{'age': [u'This field is required.']}
Which is odd because it didn't complain about name, even though I supplied both of them to the my TestForm. What am I doing wrong?
try doing this instead
data = {'name': 'bob', 'age': 33}
tform = TestForm()
tform.name.data = data['name']
tform.age.data = data['age']
if tform.validate():
print 'success!'
else:
print tform.errors

How to test a Django form with a ModelChoiceField using test client and post method

How do I use Django test client.post to test a form that has a ModelChoiceField? How should the data dictionary passed to the post method be written? The way I am doing does not select any value at all.
I have a form with the following field:
country = forms.ModelChoiceField(
label="PaĆ­s",
queryset=Country.objects.all().order_by('name'),
required=True,
widget=forms.Select(attrs={
'onchange': "Dajaxice.party.update_country(Dajax.process, {'option':this.value})"
},
)
I also have the following test case:
def test_party_profile_sucessfully_saved(self):
self.client.login(username='Party1', password='BadMotherF')
response = self.client.post(reverse('party'), data={'slx_legal_type': '1', 'city': 'Belo Horizonte', 'country': '32',
'mobile': '+55-31-55555555', 'name': 'Roberto Vasconcelos Novaes',
'phone': '+55-31-55555555', 'slx_cnpj': '', 'slx_cpf': '056846515',
'slx_ie': '', 'slx_im': '', 'slx_rg': 'MG9084545', 'street':
'Rua Palmira, 656 - 502', 'streetbis': 'Serra', 'subdivision': '520',
'zip': '30220110'},
follow=True)
self.assertContains(response, 'Succesfully Saved!')
This form works all right. But when I test it using the aforementioned test case, the choice passed as data for the Model Choice Field (Country) does not get chosen. I have tried to pass the value (32) and the name of the country ('Brasil') or whatever.
I guess you need to pass the ID of the country or the model instance.
If you have a country 'Brazil' with id 32 you can pass in
{....
'country' : 32
....}
or
you can first get the country by using
country = Country.objects.get(id=32)
{....
'country': country
....}
I myself encountered such a problem when solving the problem. When specifying specific attributes, for example, <ModelName>.objects.get(<attr>='<...>').<something> when running django test, no post submit is formed and <ModelName>.objects.count() remains unchanged. In a practical way, I noticed that ChoiceField in the POST works only if you specify the id of the required <ModelName>.objects. But I passed the id as '32'. Therefore, it seems to me that the problem is a little different, not that the wrong value for 'country' is passed.
P.S. I apologize in advance that with a separate answer, there is not enough reputation for commenting

Categories