数据库自动化运维3-Restful API Postgres DB helpper

Posted renfengjun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据库自动化运维3-Restful API Postgres DB helpper相关的知识,希望对你有一定的参考价值。

今天来添加对postgres的支持

Codes:

jwttoken.py 加入如下代码
from pgtest import util as pgutil
from pgtest import mypg

app.config['PGPWD'] = 'oracle123'
app.config['PGUSR'] = 'postgres'
app.config['PGHOST'] = '192.168.132.218'
@app.route('/pgdblist')
def pgdblist():
    usr = app.config['PGUSR']
    passwd = app.config['PGPWD']
    try:
        new_pg = mypg.myPg(usr=usr, passwd=passwd)
    except Exception as e :
        app.logger.warning(str(e).strip())
        return quick(404,' execute failed')
    rows = pgutil.list_db(new_pg)
    str = ''
    for row in rows :
        str +=row[0]+ ' '
    return quick(200, str)

pgtest/util.py
#!/usr/bin/python
import psycopg2
from mypg import *
import os


def get_connection():
    return 1
#0 = not exists
#1 = exists
#mount or
def list_db(mypg):
    sql = "SELECT datname from pg_catalog.pg_database"
    rows = mypg.execute(sql)
    return rows

pgtest/mypg.py
#!/usr/bin/python
import psycopg2
import sys

class myPg():

    def __init__(self, usr, passwd, db='postgres', myhost="192.168.132.218", myport="5432"):
        self.conn = psycopg2.connect(database=db, user=usr, password=passwd, host=myhost, port=myport)
        print "complete"

    def getConn(self):
        return self.conn

    def execute(self, sql, binds=[], updateble= False):
        cur = self.conn.cursor()

        cur.execute(sql, binds)

        if sql[0:6] == 'SELECT' :
            result = cur.fetchall()
        else :
            result = True

        if updateble :
            self.conn.commit()
        cur.close()
        return result
    def __del__(self):
        try:
            if self.conn:
                #print 'connection destory'
                self.conn.close()
        except Exception as e :
            print 'Connection Failed'
            pass

类似于Oracle的db helper,后续只需要在util.py以及启动程序种加入相关的数据库功能即可。

不要忘记在redis种加入相关的roles

Redis: 
127.0.0.1:6379> SADD roles:gb-adi-api "PGDBLIST"
(integer) 1

[root@adirfj flaskspace]# token=$(curl -s -X POST -H "Content-Type: application/json" http://127.0.0.1:5000/aut -d "$APICREDS" |jq -r '.token')


[root@adirfj flaskspace]# curl -s -X GET -H "Content-Type: application/json" -H "Authentication: $token" http://127.0.0.1:5000/pgdblist

  "message": "postgres template1 template0 dbrfj "

后续将对于相关的技术进行进一步的讲解。

Enjoy!

以上是关于数据库自动化运维3-Restful API Postgres DB helpper的主要内容,如果未能解决你的问题,请参考以下文章

数据库自动化运维1-Restful API一个小DEMO

数据库自动化运维1-Restful API一个小DEMO

数据库自动化运维2-Restful API JWT and Redis authorization

数据库自动化运维2-Restful API JWT and Redis authorization

Elastic-Job-Lite 源码分析 —— 运维平台

算法,运维