今天来添加对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!