Python reads ini files operates on mysql and sends mail instances

  • 2020-04-02 14:30:24
  • OfStack

I have nothing to do, 2014 was too grandiose, the blog did not write a few, ah ~~~ use this to record the passing of 2014

Python does all kinds of things with all kinds of databases, but I like my style, which involves other operations, but the focus is on the database. Oh ~ ~

Python Mysql operation

First, I'm used to writing configuration information to a configuration file so I can change it without the source code, and then write generic functions to call

Create a new configuration file and name it conf.ini. You can write all kinds of configuration information, but you can specify the node (the file format is strict) :


[app_info]
DATABASE=test
USER=app
PASSWORD=123456
HOST=172.17.1.1
PORT=3306 [mail]
host=smtp.163.com
mail_from=zhoujie0111@126.com
password=654321
send_to=zhoujie0111@139.com;zhoujie0111@163.com

The same directory under the new file db. Py, the code is as follows, do not explain:


# -*-coding:utf-8 -*- import MySQLdb   # These two bags must be packed first
import ConfigParser cf=ConfigParser.ConfigParser()
cf.read("conf.ini") DATABASE=cf.get("app_info","DATABASE")
USER=cf.get("app_info","USER")
PASSWORD=cf.get("app_info","PASSWORD")
HOST=cf.get("app_info","HOST")
PORT=cf.get("app_info","PORT") def mysql(sql):
    try:
        conn=MySQLdb.connect(host=HOST,user=USER,passwd=PASSWORD,db=DATABASE,port=PORT)
        cur = conn.cursor()
        cur.execute(sql)
        rows = cur.fetchall()
        conn.commit()  # This is necessary for adding, deleting, or failing to commit the transaction
        cur.close()
        conn.close()
        return rows
    except MySQLdb.Error,e:
        print "Mysql Error %d: %s" % (e.args[0], e.args[1])

Above is the method that encapsulates the operation database, need to provide an SQL statement only, CRUD can operate. Next, YY some data to test the specific usage of add, delete, change and check (easy, I am really idle), and then the above code:


def operation():
    # The query
    select = mysql('select * from test')     # insert
    '''
    There's a plug in here 2 Points need to be noted:
    1. Insert certain columns as specified below, insert all may not specify columns, but must be followed by inserted values in order
    2. Note the following type I have anticline points on both sides of the column because type I have a table in my database called this, or you can call it a keyword, and if you don't put it in reverse, it will fail
    3. It's hard to say, hehe. Number placeholders %d, String to use %s , and the string placeholder must be enclosed in double quotes
    '''
    insert = mysql('insert into test (name,number,`type`) values("%s",%d,"%s")'%('jzhou',100,'VIP'))     # update
    mysql('update test set number=%d where name="%s"'%(99,'jzhou'))     # delete
    delete = mysql('delete from test where number = %d and `type`="%s"'%(100,'jzhou'))     return select # I returned this for the following email, and added a new email function

I just want to make this simple operation a little more complicated, add a function to send mail, is also the above code:


mailto_list=[]
send_info=cf.get("mail","send_to")
send_array=send_info.split(";")
for i in range(len(send_array)):
    mailto_list.append(send_array[i]) mail_host=cf.get("mail","host")
mail_from=cf.get("mail","mail_from")
mail_password=cf.get("mail","password") def send_mail(to_list,sub,content):
    me=mail_from
    msg=MIMEText(content,_subtype='html',_charset='utf-8')
    msg['Subject']=sub
    msg['From']=me
    msg['To']=";".join(to_list)
    try:
        s=smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_from,mail_password)
        s.sendmail(me,to_list,msg.as_string())
        s.close()
        return True
    except Exception,e:
        print str(e)
        return False

I also wrote the configuration of sending email in conf.ini. Call the sending email in the main function to end this thing:


if __name__ == '__main__':
    sub = u' Don't ask me why write this blog, idle, is capricious! '
    content = operation()
    if send_mail(mailto_list,sub,content):
        print 'send success'
    else:
        print 'send failed'

In fact, I also want to mention that python operates postgresql, which is very similar to mysql, and the download package psycopg2, except that all the SQL statements executed in postgresql are enclosed in double quotes.


# -*-coding:utf-8 -*-
import psycopg2
import ConfigParser cf=ConfigParser.ConfigParser()
cf.read("conf.ini") DATABASE=cf.get("cmdb_info","DATABASE")
USER=cf.get("cmdb_info","USER")
PASSWORD=cf.get("cmdb_info","PASSWORD")
HOST=cf.get("cmdb_info","HOST")
PORT=cf.get("cmdb_info","PORT") def psql(sql):
    try :
        conn = psycopg2.connect(database=DATABASE, user=USER, password=PASSWORD, host=HOST, port=PORT)
        cur = conn.cursor()
        cur.execute(sql)
        rows = cur.fetchall()
        conn.commit()
        cur.close()
        conn.close()
        return rows
    except Exception,e:
        print e def psql_oper():
    sql="select "name","type" from "test" where "name" = 'jzhou'"
    rows=psql(sql)
    print rows

I concluded that this blog is simple, but contains three important knowledge points, ^_^

1. Python reads ini file (to import ConfigParser)
2. Python operates mysql
3. Python sends mail

4, published are through the practice of testing, even if it is very simple, this is an attitude!


Related articles: