Python writing only the last element in dict to database

47 views Asked by At

I am getting the mx-record of the domains in the database. And then I write to the rows in the relevant column. However, the last value in mx-record written to database. What is the reason, how can I fix it?

My code:

domains = Domain.query.all()

for mx in domains:
    if mx:
        try:
            result = dns.resolver.resolve(mx.domain, 'MX')
            for mx_record in result:
                mx.mx_record = mx_record.to_text()
        except Exception as e:
            print(e)

        finally:
            db.session.commit()

the database output I want: My database table have to be like this.

domain mx_record
cat.com 10 mail5.cat.com.,10 mail6.cat.com.,10 mail1.cat.com.,10 mail4.cat.com.,10 mail2.cat.com.,10 mail3.cat.com.
stackoverflow.com 10 alt4.aspmx.l.google.com.,5 alt1.aspmx.l.google.com.,10 alt3.aspmx.l.google.com.,5 alt2.aspmx.l.google.com.,1 aspmx.l.google.com.
1

There are 1 answers

4
furas On

You run for-loop which assign all mx_record.to_text() to the same mx - and this removes previous values and you get only last one.

You should first create one string with all values and later assign single string. Something like this:

result = dns.resolver.resolve(mx.domain, 'MX')

values = []
for mx_record in result:
    values.append(mx_record.to_text())

# values = [mx_record.to_text() for mx_record in result]  # shorter

one_string = ','.join(values)

mx.mx_record = one_string