zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python django 基本测试 及调试 201812

2023-09-11 14:18:40 时间

########1124
mysql 编辑器:wamper server
http://127.0.0.1/phpmyadmin/db_sql.php?db=db_monitor&token=4a6e01d703917ba43b7e5e0d0cc1ffd7


insert into tab_alarm_conf (id,db_type,alarm_name,pct_max,size_min,time_max,num_max) values (9,'oracle','Oracle数据库通断告警',0,0,1,0);
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max,size_min,time_max,num_max) values (10,'oracle','Oracle数据库表空间使用率告警',80,0,0,0);
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max,size_min,time_max,num_max) values (11,'oracle','Oracle数据库adg延迟告警',0,0,300,0);
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max,size_min,time_max,num_max) values (12,'oracle','Oracle数据库临时表空间告警',90,0.1,0,0);
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max,size_min,time_max,num_max) values (13,'oracle','Oracle数据库undo表空间告警',90,0.1,0,0);
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max,size_min,time_max,num_max) values (14,'oracle','Oracle数据库连接数告警',90,20,0,0);
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max,size_min,time_max,num_max) values (15,'oracle','Oracle数据库后台日志告警',0,0,0,0);
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max,size_min,time_max,num_max) values (16,'oracle','Oracle数据库综合性能告警',0,0,0,100);
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max,size_min,time_max,num_max) values (17,'oracle','Oracle数据库pga使用率告警',90,0,0,0);
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max,size_min,time_max,num_max) values (18,'oracle','Oracle数据库归档使用率告警',90,0,0,0);
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max,size_min,time_max,num_max) values (19,'oracle','Oracle数据库锁异常告警',0,0,100,0);
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max,size_min,time_max,num_max) values (20,'oracle','Oracle数据库密码过期告警',0,10,0,0);
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max,size_min,time_max,num_max) values (21,'oracle','Oracle失效索引告警',0,0,0,0);


models_oracle.OracleDb.objects.filter(tags=tagsdefault).get(tags=tagsdefault, )

####
http://127.0.0.1:8000/oracle_monitor/

File "D:\Program Files\JetBrains\db_monitor-master\db_monitor-master\oracle_mon\views.py", line 56, in oracle_monitor
oracleinfo = models_oracle.OracleDbHis.objects.filter(tags=tagsdefault,percent_process__isnull=False).order_by('-chk_time')[0]
File "C:\Program Files (x86)\python27\lib\site-packages\django\db\models\query.py", line 289, in __getitem__
return list(qs)[0]


-> url(r'^oracle_monitor/', oracle_mon.oracle_monitor),
-> oracle_mon/views/oracle_monitor

->python2 manage.py shell
oracle_monitor

print str(models_oracle.TabOracleServers.objects.all().order_by('tags').query)

try:
oracleinfo = models_oracle.OracleDb.objects.get(tags=tagsdefault)
except models_oracle.OracleDb.DoesNotExist:
oracleinfo = models_oracle.OracleDbHis.objects.filter(tags=tagsdefault,percent_process__isnull=False).order_by('-chk_time')[0]

->OracleDb no data (oracle_db)


-> check_alarm/main_check.py

2018-11-24 23:02:25,322 - main_check.py[line:531] - INFO: ora11g_test:初始化oracle_db表
mysql execute: (1136, "Column count doesn't match value count at row 1")
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
2018-11-24 23:35:35,313 - main_check.py[line:540] - INFO: ora11g_test :开始更新数据库评分信息

 

mysql> insert into oracle_db_his select * from oracle_db ;
ERROR 1136 (21S01): Column count doesn't match value count at row 1


oracle_db_his add three column

log_mode = models.CharField(max_length=255, blank=True, null=True)
archive_used = models.CharField(max_length=255, blank=True, null=True)
archive_rate_level = models.CharField(max_length=255, blank=True, null=True)

 

 

 

2018-11-26 09:23:29,035 - main_check.py[line:195] - INFO: ora11g_test:获取Oracle数据库表空间使用率(表空间名:SYSAUX 使用率:94.24)
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
2018-11-26 09:23:29,059 - main_check.py[line:195] - INFO: ora11g_test:获取Oracle数据库表空间使用率(表空间名:EXAMPLE 使用率:89.75)
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
2018-11-26 09:23:29,084 - main_check.py[line:530] - ERROR: ora11g_test 数据库连接失败:'tuple' object does not support item assignment
2018-11-26 09:23:29,085 - main_check.py[line:531] - INFO: ora11g_test:初始化oracle_db表
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")

 

 

find the insert sql,insert add column and value
insert into
chk_time ->%s -> datetime.datetime.now()

 


2018-11-26 10:22:21,743 - main_check.py[line:530] - ERROR: ora11g_test 数据库连接失败:'tuple' object does not support item assignment
这个报错是正常的,因为之前FOR 循环,有些字段为空的,通过检查,发现是之前检查表空间的语句返回值为空,所以导致这个报错。修改检查表空间的语句,方可进行


另外expection 也可以由以下
from
# error_msg = "%s 数据库连接失败:%s %s" % (tags, unicode(str(e), errors='ignore'))
to
error_msg = "%s 目标主机连接失败:%s " % (tags, str(e))

 


my_log.logger.info('%s:debug' % tags)


改成
except:
info=sys.exc_info()
print info[0],":",info[1]

(重要)
https://www.cnblogs.com/Simon-xm/p/4073028.html
https://www.cnblogs.com/technologylife/p/5628585.html

#######

CREATE TEST_ORACLE.PY ,手工测试


print (tbs)
print (line)
提示如下报错:
('USERS', 1, 0, None, None, None, None, None)


修改check_oracle.py


为如下即可:
SELECT DF.TABLESPACE_NAME,
COUNT(*) DATAFILE_COUNT,
ROUND(SUM(DF.BYTES) / 1048576 , 8) SIZE_MB,
ROUND(SUM(FREE.BYTES) / 1048576 , 8) FREE_MB,
ROUND(SUM(DF.BYTES) / 1048576 -
SUM(FREE.BYTES) / 1048576 ,
8) USED_MB,
ROUND(MAX(FREE.MAXBYTES) / 1048576 , 8) MAXFREE,
100 - ROUND(100.0 * SUM(FREE.BYTES) / SUM(DF.BYTES), 8) PCT_USED,
ROUND(100.0 * SUM(FREE.BYTES) / SUM(DF.BYTES), 8) PCT_FREE
FROM DBA_DATA_FILES DF,
(SELECT TABLESPACE_NAME,
FILE_ID,
SUM(BYTES) BYTES,
MAX(BYTES) MAXBYTES
FROM DBA_FREE_SPACE
WHERE BYTES > 1024
GROUP BY TABLESPACE_NAME, FILE_ID) FREE
WHERE DF.TABLESPACE_NAME = FREE.TABLESPACE_NAME(+) AND DF.TABLESPACE_NAME NOT LIKE 'UNDO%'
AND DF.FILE_ID = FREE.FILE_ID(+)
GROUP BY DF.TABLESPACE_NAME
ORDER BY 8

 

#############


2018-11-27 11:10:13,576 - test_oracle.py[line:151] - INFO: ora11g_test:获取Oracle数据库监控数据(数据库名:ORA11G 数据库角色:PRIMARY 数据库状态:READ WRITE 连接数使用率:18 )
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
2018-11-27 11:10:13,576 - test_oracle.py[line:154] - INFO: ora11g_test:开始获取Oracle数据库用户密码过期信息
2018-11-27 11:10:13,576 - test_oracle.py[line:156] - INFO: ora11g_test:初始化oracle_expired_pwd表
mysql execute: (1146, "Table 'db_monitor.oracle_expired_pwd' doesn't exist")
2018-11-27 11:10:13,645 - test_oracle.py[line:166] - INFO: ora11g_test:开始获取Oracle数据库等待事件信息
2018-11-27 11:10:13,645 - test_oracle.py[line:168] - INFO: ora11g_test:初始化oracle_db_event表
mysql execute: (1146, "Table 'db_monitor.oracle_db_event_his' doesn't exist")
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
2018-11-27 11:10:14,019 - test_oracle.py[line:180] - INFO: ora11g_test:开始获取Oracle数据库锁等待信息
2018-11-27 11:10:14,020 - test_oracle.py[line:182] - INFO: ora11g_test:初始化oracle_Lock表
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
2018-11-27 11:10:14,305 - test_oracle.py[line:193] - INFO: ora11g_test:开始获取Oracle数据库无效索引信息
2018-11-27 11:10:14,305 - test_oracle.py[line:195] - INFO: ora11g_test:初始化oracle_invalid_index表
2018-11-27 11:10:16,670 - test_oracle.py[line:206] - INFO: ora11g_test:开始获取Oracle数据库临时表空间监控信息
2018-11-27 11:10:16,671 - test_oracle.py[line:208] - INFO: ora11g_test:初始化oracle_tmp_tbs表
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
2018-11-27 11:10:16,766 - test_oracle.py[line:221] - INFO: ora11g_test:获取Oracle数据库临时表空间使用率(temp表空间名:TEMP 使用率:0)
2018-11-27 11:10:16,766 - test_oracle.py[line:224] - INFO: ora11g_test:开始获取Oracle数据库undo表空间监控信息
2018-11-27 11:10:16,766 - test_oracle.py[line:225] - INFO: ora11g_test:初始化oracle_undo_tbs表
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
2018-11-27 11:10:17,003 - test_oracle.py[line:237] - INFO: ora11g_test:获取Oracle数据库undo表空间使用率(undo表空间名:UNDOTBS1 使用率:8.68)
2018-11-27 11:10:17,003 - test_oracle.py[line:240] - INFO: ora11g_test :开始更新Oracle数据库评分信息
2018-11-27 11:10:17,042 - test_oracle.py[line:248] - WARNING: ora11g_test:内存使用率未采集到数据
2018-11-27 11:10:17,063 - test_oracle.py[line:264] - WARNING: ora11g_test:CPU使用率未采集到数据
2018-11-27 11:10:17,084 - test_oracle.py[line:279] - WARNING: ora11g_test:连接数未采集到数据
2018-11-27 11:10:17,095 - test_oracle.py[line:294] - WARNING: ora11g_test:归档未采集到数据
<class '_mysql_exceptions.ProgrammingError'> : (1146, "Table 'db_monitor.oracle_db_event_his' doesn't exist")
<type 'tuple'>
(<class '_mysql_exceptions.ProgrammingError'>, ProgrammingError(1146, "Table 'db_monitor.oracle_db_event_his' doesn't exist"), <traceback object at 0x0351E300>)
2018-11-27 11:10:17,114 - test_oracle.py[line:423] - ERROR: a[1]
2018-11-27 11:10:17,114 - test_oracle.py[line:424] - INFO: ora11g_test:初始化oracle_db表
2018-11-27 11:10:17,145 - test_oracle.py[line:431] - INFO: ora11g_test:debug
2018-11-27 11:10:17,157 - test_oracle.py[line:434] - INFO: ora11g_test :开始更新数据库评分信息
mysql execute: (1364, "Field 'conn_decute' doesn't have a default value")
2018-11-27 11:10:17,196 - test_oracle.py[line:439] - INFO: ora11g_test扣分明细,总评分:0,扣分原因:connected error
2018-11-27 11:10:17,196 - test_oracle.py[line:29] - INFO: ora11g_test等待2秒待linux主机信息采集完毕
2018-11-27 11:10:27,618 - test_oracle.py[line:54] - INFO: ora11g_test:开始获取Oracle数据库表空间监控信息
2018-11-27 11:10:27,618 - test_oracle.py[line:56] - INFO: ora11g_test:初始化oracle_tbs表

 


oracle_undo_tbs/oracle_db
find the insert sql,insert add column and value
insert into
chk_time ->%s -> datetime.datetime.now()

oracle_tmp_tbs

 

mysql execute: (1146, "Table 'db_monitor.oracle_db_event_his' doesn't exist")

CREATE TABLE IF NOT EXISTS `oracle_db_event_his` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tags` varchar(255) NOT NULL,
`host` varchar(255) NOT NULL,
`port` varchar(255) NOT NULL,
`service_name` varchar(255) NOT NULL,
`event_no` varchar(255) NOT NULL,
`event_name` varchar(255) NOT NULL,
`event_cnt` varchar(255) NOT NULL,
`chk_time` datetime(6) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

 


#########20181127

gumengkai
sed -n '/gumengkai/p' *

grep gumengka oracle_monitor.html

sed -i '/gumengka/c\' oracle_monitor.html

sed -i '/gumengka/c\' `grep gumengkai -rl /tmp/dba`


oracle_monitor.html


####python 调试 check_alarm\mian_check.py

cd check_alarm
python2

import base64
import sys
import time
import datetime
from multiprocessing import Process;

import MySQLdb
import cx_Oracle

import check_mysql as check_msql
import check_oracle as check_ora
import check_os as check_os
import tools as tools
import alarm as alarm
import my_log as my_log

reload(sys)
sys.setdefaultencoding('utf-8')
# 配置文件
import ConfigParser
conf = ConfigParser.ConfigParser()
conf.read('config/db_monitor.conf')

# conn = cx_Oracle.connect(user, password, url)
conn = cx_Oracle.connect('dbmgr','1234DBA','192.168.195.128:1521/ora11g')


tbs = check_ora.check_tbs(conn)

 

2018-11-26 14:50:24,134 - main_check.py[line:881] - INFO: ora11g_test 开始采集oracle数据库信息
2018-11-26 14:50:24,135 - main_check.py[line:882] - INFO: 192.168.195.128 1
2018-11-26 14:50:24,135 - main_check.py[line:883] - INFO: 1521 2
2018-11-26 14:50:24,135 - main_check.py[line:884] - INFO: ora11g 3
2018-11-26 14:50:24,137 - main_check.py[line:885] - INFO: dbmgr 4
2018-11-26 14:50:24,137 - main_check.py[line:886] - INFO: Y3JiYW5rMTIzNERCQQ==
5
2018-11-26 14:50:24,137 - main_check.py[line:887] - INFO: oracle 6
2018-11-26 14:50:24,171 - main_check.py[line:888] - INFO: b3JhY2xl 7

 

check_oracle('ora11g_test','192.168.195.128','1521','ora11g','dbmgr','1234DBA','oracle','oracle')

 


运行check_alarm/alarm.py

 

raise errorvalue
_mysql_exceptions.ProgrammingError: (1146, "Table 'db_monitor.oracle_expired_pwd' doesn't exist")

check_alarm\alarm.py

#### # 密码过期告警

 

####
# event_sql = ''' select tags, host, port, service_name, cnt_all from (select tags, host, port, service_name, sum(event_cnt) cnt_all
# from oracle_db_event_his where tags = '%s' and timestampdiff(minute, chk_time, current_timestamp()) < %s
# group by tags, host, port, service_name) t where cnt_all > %d ''' %(tags,100,num_max)
# event_stat = tools.mysql_query(event_sql)

 

from . import tools as tools

###############1128

D:\Program Files\JetBrains\db_monitor-master\db_monitor-master\frame\easy_check.py in ora_check, line 36

D:\Program Files\JetBrains\db_monitor-master\db_monitor-master\frame\views.py in my_check (函数)

## views.py 是后端的中间件,所以无法单独调试,前端(网页)交互提交的数据 可以通过 python2 manage.py runserver 的输出看看结果
print (select_tags)
print (begin_time)
print (check_file_name)
print (file_tag)
easy_check.ora_check(select_tags,begin_time,end_time,check_file_name,file_tag)
current_conn = int(current_conn_sql[0][0])

[u'orcl_adg']
2018-11-27 15:48:18
oracheck_20181128154818.xls
20181128154818

 

current_conn_sql = tools.mysql_query("select percent_process from oracle_db where tags= '%s'" % tags)

 

chrom查看源代码:
<button type="submmit" class="btn btn-info btn-flat" name="go_check">开始巡检Go!</button>

<label>选择巡检设备</label>
<select id="select_tags" class="form-control select2" multiple="multiple" data-placeholder=选择一个或多个
name="select_tags">
<option>orcl</option>
<option>orcl_adg</option>
<option>orcl_aliyun</option>
</select>

方法;ajax
https://blog.csdn.net/sun_never_set/article/details/80959431
https://blog.csdn.net/RikkaTakanashi/article/details/82730237
https://blog.csdn.net/slamx/article/details/51095066
https://blog.csdn.net/z278718149/article/details/50034283?utm_source=blogxgwz0
https://www.cnblogs.com/jxrichar/p/3901426.html


在tools文件夹中新建一个 forms.py 文件
from django import forms

class AddForm(forms.Form):
a = forms.IntegerField()
b = forms.IntegerField()

 

我们的视图函数 views.py 中


# coding:utf-8
from django.shortcuts import render
from django.http import HttpResponse

# 引入我们创建的表单类
from .forms import AddForm

def index(request):
if request.method == 'POST':# 当提交表单时

form = AddForm(request.POST) # form 包含提交的数据

if form.is_valid():# 如果提交的数据合法
a = form.cleaned_data['a']
b = form.cleaned_data['b']
return HttpResponse(str(int(a) + int(b)))

else:# 当正常访问时
form = AddForm()
return render(request, 'index.html', {'form': form})


对应的模板文件 index.html

1
2
3
4
5
<form method='post'>
{% csrf_token %}
{{ form }}
<input type="submit" value="提交">
</form>

urls.py
from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
# 注意下面这一行
url(r'^$', 'tools.views.index', name='home'),
url(r'^admin/', include(admin.site.urls)),
)

 

#######JQuery 20181203
https://code.ziqiangxuetang.com/jquery/jquery-selectors.html
https://code.ziqiangxuetang.com/jquery/jquery-ajax-get-post.html
https://code.ziqiangxuetang.com/jquery/jquery-examples.html


档就绪事件
您也许已经注意到在我们的实例中的所有 jQuery 函数位于一个 document ready 函数中:

$(document).ready(function(){

// jQuery methods go here...

});
这是为了防止文档在完全加载(就绪)之前运行 jQuery 代码。

如果在文档没有完全加载之前就运行函数,操作可能失败。下面是两个具体的例子:

试图隐藏一个不存在的元素
获得未完全加载的图像的大小
提示:简洁写法(与以上写法效果相同):

$(function(){

// jQuery methods go here...

});


HTTP 请求:GET vs. POST
两种在客户端和服务器端进行请求-响应的常用方法是:GET 和 POST。

GET - 从指定的资源请求数据
POST - 向指定的资源提交要处理的数据
GET 基本上用于从服务器获得(取回)数据。注释:GET 方法可能返回缓存数据。

POST 也可用于从服务器获取数据。不过,POST 方法不会缓存数据,并且常用于连同请求一起发送数据。

如需学习更多有关 GET 和 POST 以及两方法差异的知识,请阅读我们的 HTTP 方法 - GET 对比 POST。

 

######### 20181204
var arr=[{name:'dd'},{name:'bb'}]
for (var i=0; i< arr.length; i++) {
console.log(arr[i]);
}
先的简单介绍一下chrome的控制台,打开chrome浏览器,按f12就可以轻松的打开控制台,调试JQUERY (重要)
【转】console.log 用法
https://www.cnblogs.com/wohenxion/p/4478457.html

https://www.cnblogs.com/psklf/archive/2016/05/30/5542612.html
(重要)

chrom 进入控制台
F12


UTF-8
<head>
<title>欢迎光临</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>


########20181205
https://code.ziqiangxuetang.com/jquery/jquery-ref-ajax.html (方法)
jQuery.get()
http://api.jquery.com/jquery.get (重要)
http://api.jquery.com/jquery.each/ (重要)

jQuery.get()
Description: Load data from the server using a HTTP GET request.

http://www.w3school.com.cn/jquery/ajax_get.asp
使用 AJAX 的 GET 请求来改变 div 元素的文本:

$("button").click(function(){
$.get("demo_ajax_load.txt", function(result){
$("div").html(result);
});
});

https://blog.csdn.net/aoerqileng/article/details/79131736
return HttpResponse
这种方式ajax在接收到后一直执行error部分代码,其实返回的数据是没有问题的。
后来换了
return HttpResponse(json.dumps({“serverList”:serverList}), content_type=”application/json”)
这种形式就没有问题了
在返回json对象,动态在原页面加载显示的时候,还是使用httpresponse吧。你直接返回数据给html,不同过ajax请求这种的可以用render


return render
这里是这样:后台传递一些数据给html,直接渲染在网页上,不会有什么复杂的数据处理(如果前台要处理数据,那么就传数据给JS处理)

views.py 的函数和 urls 函数匹配
views的函数定义的网页与template的网页 匹配
views的变量传递到template 网页
template 网页的jquery 的值通过 views 的函数处理

$(selector).html()
输出到HTML

json可以在网页中输出
import json


技能提升:getJSON中的写的对应网址,用 urls.py 中的 name 来获取是一个更好的方法!
标签:{% url 'name' %}

【已解决】Object of type 'range' is not JSON serializable

所以问题应该就出现在Python的版本上,我用的是Python3.6.2
所以Python3.X和2.X的range()用法是不一样的
def ajax_list(request):
a = list(range(100))
return JsonResponse(a, safe=False)

 

setting.py
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'common_static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

 


$('#result').html('') //清空前面的结果


https://www.cnblogs.com/yanxiatingyu/p/9254659.html (重要)
python 3.6.5 map() max() lambda匿名函数

 

https://blog.csdn.net/weixin_42305814/article/details/81180224 (重要)
https://blog.csdn.net/zoulonglong/article/details/80666073
https://www.cnblogs.com/psklf/archive/2016/05/30/5542612.html

 

###############1206

迁移一个项目的SQLLIT数据库到另一台服务器的数据库
1.
默认配置下,Django 的模板系统会自动找到app下面的templates文件夹中的模板文件。
Django 模板查找机制: Django 查找模板的过程是在每个 app 的 templates 文件夹中找(而不只是当前 app 中的代码只在当前的 app 的 templates 文件夹中找)。各个 app 的 templates 形成一个文件夹列表,Django 遍历这个列表,一个个文件夹进行查找,当在某一个文件夹找到的时候就停止,所有的都遍历完了还找不到指定的模板的时候就是 Template Not Found (过程类似于Python找包)。这样设计有利当然也有弊,有利是的地方是一个app可以用另一个app的模板文件,弊是有可能会找错了。所以我们使用的时候在 templates 中建立一个 app 同名的文件夹,这样就好了。


Django 找不到模版报错" django.template.exceptions.TemplateDoesNotExist: index.html"
(https://www.cnblogs.com/alan-babyblog/p/5828026.html)

解决办法:在setting.py的TEMPLATES‘DIRS'[]加入模版路径
'BACKEND': 'django.template.backends.django.DjangoTemplates',

2.
https://blog.csdn.net/foryouslgme/article/details/52034149
1、下载sqlite3【http://www.sqlite.org/sqlite-shell-win32-x86-3071401.zip】

2、将sqlite3.exe文件放入(C:\Windwos\System32)中

3、C:\Users\Administrator\PycharmProjects\untitled3>python manage.py dbshell
4. ADD sqlite3.exe on the directory that de manage.py

http://www.runoob.com/sqlite/sqlite-select.html
sqlite> SELECT tbl_name FROM sqlite_master WHERE type = 'table';
sqlite> SELECT sql FROM sqlite_master WHERE type = 'table' AND tbl_name = 'exam2014_biodrug';
sqlite>
CREATE TABLE district_info(
ID INT NOT NULL,
P_ID TEXT NOT NULL,
NAME VARCHAR(50)
)


INSERT INTO district_info (ID,P_ID,NAME)
VALUES (11, 0,'湖南');


INSERT INTO district_info (ID,P_ID,NAME)
VALUES (12, 0,'广东');


INSERT INTO district_info (ID,P_ID,NAME)
VALUES (13, 0,'北京');

INSERT INTO district_info (ID,P_ID,NAME)
VALUES (14, 0,'天津');


INSERT INTO district_info (ID,P_ID,NAME)
VALUES (15, 0,'河北');

 

INSERT INTO district_info (ID,P_ID,NAME)
VALUES (16, 0,'山西');
3.
python manage.py dbshell


python manage.py makemigrations
python manage.py migrate

 


4
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});
这样之后,就可以像原来一样的使用 jQuery.ajax() 和 jQuery.post()了

 

5.
views.py

def home(request):
TutorialList = ["HTML", "CSS", "jQuery", "Python", "Django"]
return render(request, 'home.html', {'TutorialList': TutorialList})

在视图中我们传递了一个List到模板 home.html,在模板中这样使用它:

home.html

教程列表:
{% for i in TutorialList %}
{{ i }}
{% endfor %}


6.
print str(BioDrug.objects.filter(inputer__isnull=True).query)
SyntaxError: invalid syntax
print (BioDrug.objects.filter(inputer__isnull=True).query)

SELECT "exam2014_biodrug"."id", "exam2014_biodrug"."name", "exam2014_biodrug"."inputer_id", "exam2014_biodrug"."create_time", "exam2014_biodrug"."update_time" FROM "exam2014_biodrug" WHERE "exam2014_biodrug"."inputer_id" IS NULL

 


########1210

AUSTRIA ="中"

https://www.cnblogs.com/lightwind/p/4499193.html (重要,python3中SQLLIT编码与解码之Unicode与bytes)
https://www.cnblogs.com/lightwind/p/4499193.html
https://docs.python.org/3/library/sqlite3.html?highlight=conn%20text_factory%20str
https://docs.python.org/3/library/sqlite3.html?highlight=conn%20text_factory%20str
https://blog.csdn.net/chb4715/article/details/79104299 ( python3中编码与解码之Unicode与bytes)

https://blog.csdn.net/yezonggang/article/details/50978114 (python中lambda的用法)

https://blog.csdn.net/xkxjy/article/details/8179479 (解决方法)
http://www.runoob.com/python/python-func-str.html (重要,Python str() 函数)
https://www.cnblogs.com/sesshoumaru/p/6070713.html (Python str() 函数))

http://www.runoob.com/python3/python3-string-encode.html (Python3 encode()方法)


sqlite3.OperationalError: Could not decode to UTF-8 column 'logtype' with text

直接在浏览器调试函数 http://127.0.0.1:8000/ajax_province (重要)

with connection.cursor() as c:
c.execute("select id,name from district_info where p_id=0")
provinces = c.fetchall()

 

调整为

con = sqlite3.connect('./db.sqlite3')
# con.text_factory = bytes
con.text_factory = lambda x: str(x, 'gbk', 'ignore')
cur = con.cursor()
# with connection.cursor() as c:
c=cur.execute("select id,name from district_info where p_id=0")
provinces = c.fetchall()
return JsonResponse(provinces, safe=False)


########
CTRL+Q (查看python 中的变量)


https://blog.csdn.net/mr_l_0927/article/details/79401095
错误信息如下:

RuntimeError at /picload
You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. 
Django can't redirect to the slash URL while maintaining POST data. Change your form to point 
to 127.0.0.1:8000/picload/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.

表单字段action以'/'结尾,(action="/picsave/),尝试修改settings文件,设置了APPEND_SLASH = False属性,

bug仍存在。最后将应用的urls中对应的路径末去掉'/',(r'^picsave/$',去掉表达式中的'/'),bug修复。
PS:仔细了解APP中urls路径配置详细规则
---------------------


修改下拉框为可选项(直接从数据库获得信息)。

urls:
url(r'^ajax_db$', frame.ajax_db),

views:
from django.db import connection
from django.http import JsonResponse
import json
def ajax_db(request):
with connection.cursor() as c:
c.execute("select tags,host,port,service_name from tab_oracle_servers")
db = c.fetchall()
return JsonResponse(db, safe=False)


my_check.html
1.
$.ajax({
type: "post",
url: "/ajax_province",
dataType: "json",
success: function (data) {
console.info(data);
for (var i = 0; i < data.length; i++) {
console.info(data[i][1]);
var pOption = "<option value='"+data[i][0]+"'>"+data[i][1]+"</option>";
$("#select_tags").append(pOption);
}
}
});



2.
<select id="select_tags" class="form-control select2" multiple="multiple" data-placeholder={{ select_tags }}
name="select_tags">
<option>orcl</option>
<option>orcl_adg</option>
<option>orcl_aliyun</option>

修改为

<select id="select_tags" class="form-control select2" multiple="multiple" data-placeholder={{ select_tags }}
name="select_tags">
<option value="">请选择</option>


##############
https://www.cnblogs.com/sheng-247/p/7529289.html
https://lichuanbao.iteye.com/blog/1855057
https://www.cnblogs.com/panblack/p/access_oracle_with_python.html


frame\views

 



easy_check.ora_check(select_tags,begin_time,end_time,check_file_name,file_tag)
替换成
check_alarm.main_check.check_oracle(tags,host,port,service_name,user,password,user_os,password_os)

 

################20181211
跨APP的 py 的引用

from from [应用名].models import * ,

python2 manage.py shell

from check_alarm.tools import *
from check_alarm.tools import mysql_query
File "C:\Program Files (x86)\python27\lib\ConfigParser.py", line 607, in get
raise NoSectionError(section)
NoSectionError: No section: 'target_mysql'


solution:
from frame import tools


oracle_servers = tools.mysql_query('select tags,host,port,service_name,user,password from tab_oracle_servers where tags=select_tags')

 

"select * from just_id_and_name where name = '{0}'".format(data)
query ="select tags,host,port,service_name,user,password from tab_oracle_servers where tags='{0}'".format(select_tags)"
print query

insert_sql = "insert into os_info_his select * from os_info where tags = '%s'" % tags
tools.mysql_exec(insert_sql, '')

for line in event_info:
insert_event_info_sql = "insert into oracle_db_event(tags,host,port,service_name,event_no,event_name,event_cnt,chk_time) values(%s,%s,%s,%s,%s,%s,%s,%s)"
value = (tags, host, port, service_name, line[0], line[1], line[2],datetime.datetime.now())
tools.mysql_exec(insert_event_info_sql, value)

https://docs.python.org/2/faq/programming.html#how-can-i-have-modules-that-mutually-import-each-other
https://stackoverflow.com/questions/28737121/operationalerror-1054-unknown-column-in-where-clause
https://segmentfault.com/q/1010000000397716
https://www.cnblogs.com/jaw-crusher/p/3594541.html

[u'ora11g_test']
<type 'list'>

select_sql = "select tags,host,port,service_name,user,password,user_os,password_os from tab_oracle_servers where tags = '%s'" % select_tags
oracle_servers=tools.mysql_exec(select_sql, '')

oracle_servers = tools.mysql_query(
'select tags,host,port,service_name,user,password,user_os,password_os from tab_oracle_servers where tags = '%s'' % select_tags)


oracle_servers = tools.mysql_query(
'select tags,host,port,service_name,user,password,user_os,password_os from tab_oracle_servers')
if oracle_servers:
for i in xrange(len(oracle_servers)):
o_server = Process(target=check_oracle, args=(
oracle_servers[i][0], oracle_servers[i][1], oracle_servers[i][2], oracle_servers[i][3],
oracle_servers[i][4], oracle_servers[i][5], oracle_servers[i][6],oracle_servers[i][7]))
o_server.start()
my_log.logger.info('%s 开始采集oracle数据库信息' %oracle_servers[i][0])
my_log.logger.info('%s 1' % oracle_servers[i][1])
my_log.logger.info('%s 2' % oracle_servers[i][2])
my_log.logger.info('%s 3' % oracle_servers[i][3])
my_log.logger.info('%s 4' % oracle_servers[i][4])
my_log.logger.info('%s 5' % oracle_servers[i][5])
my_log.logger.info('%s 6' % oracle_servers[i][6])
my_log.logger.info('%s 7' % oracle_servers[i][7])
p_pool.append(o_server)

https://blog.csdn.net/xm_csdn/article/details/52248521
在Python中,出现:'unicode' object is not callable 的错误一般是把字符串当做函数使用了。
s='你好'
print(s)#输出结果:你好
print(type(s))#输出结果:<class 'str'>
s=s.encode('UTF-8')

AttributeError: 'list' object has no attribute 'write_pdf'
https://blog.csdn.net/petermsh/article/details/78515712


views.py
for o_row in select_tags:
select_tags = o_row.encode('UTF-8')
print str(select_tags)
select_sql = "select tags,host,port,service_name,user,password,user_os,password_os from tab_oracle_servers where tags = '%s'" % select_tags
oracle_db = tools.mysql_query(select_sql)
print (oracle_db)


check_oracle.py


check_alarm\tools.py

 

############1212

https://jingyan.baidu.com/article/636f38bb80e824d6b9461040.html
PyCharm常用快捷键和设置


https://blog.csdn.net/qq_31391261/article/details/80274727

python操作excel中遇到的错误
xlrd.biffh.XLRDError: No sheet named <'sheet2'>
原因:自动添加的sheet页的名字首字母是大写的S,book.sheet_by_name()方法区分大小写

 


https://blog.csdn.net/chengxuyuanyonghu/article/details/54951399
python中使用xlrd、xlwt操作excel表格详解
file |setting |sql dialects | preference | SQL Dialect


time.sleep(2)
password = base64.decodestring(password)
password_os = base64.decodestring(password_os)
url = host + ':' + port + '/' + service_name
conn = cx_Oracle.connect(user, password, url)


ctrl+alt+shift+U


##############1213

https://blog.csdn.net/IMBA123456789/article/details/42046165
+00000 00:15:00.0,+00062 00:00:00.0


select comp_id from dba_registry where status='VALID'
select comp_id from dba_registry where status="VALID"

select nvl(status,0) mrp from v\\$managed_standby where process!=\\'"\\'ARCH\\'"\\' and process like \\'"\\'%MRP%\\'"\\';'

select nvl(status,0) mrp from v$managed_standby where process!='"'ARCH'"'

select comp_id from dba_registry where status='VALID';


######## DB 结果结果写入excel
python2 manage.py shell

>>> from check_alarm import check_oracle
>>> from check_alarm import check_oracle as check_ora
>>> import cx_Oracle
>>>conn = cx_Oracle.connect('dbmgr','1234DBA', '192.168.195.128:1521/ora11g')
>>> tbs = check_ora.check_tbs(conn)
>>> tbs
>>> import xlwt
f = xlwt.Workbook()
sheet1 = f.add_sheet(u'sheet1',cell_overwrite_ok=True)
sheet1.write(0,1,str(tbs))
f.save('demo1.xls')

##sheet1.write(0,1,tbs)

######## 结果写入excel

dbmgr
1234DBA
192.168.195.128:1521/ora11g


############
港澳通信证,领取地 珠海
出差珠海 领取地 通勤珠海
铭牌去掉,深圳,朋友圈没有
珠海24号呆一周

########### 从下至上编写代码
check_oracle.py

# 获取检查组件
def com(conn):
cur = conn.cursor()
com_sql = "select comp_id from dba_registry where status='VALID'"
cur.execute(com_sql)
return cur.fetchall()


main_check.py
def check_db_par(tags,host,port,service_name,user,password,user_os,password_os):
my_log.logger.info('%s巡检数据库主机' %tags)
time.sleep(2)
password = base64.decodestring(password)
password_os = base64.decodestring(password_os)
url = host + ':' + port + '/' + service_name
file_path = os.getcwd() + '\check_result' + '\\'
template = '11gchecklist.xls'
rb = xlrd.open_workbook(file_path+template, formatting_info=True)
wb = copy(rb)
for tags in tags_l:
try:
conn = cx_Oracle.connect(user, password, url)
sheet1.write(1,0,service_name)
com = check_ora.check_com(conn)
sheet1.write(2,8,com)
wb.save(file_path + 11gchecklist.xls)


########debug *.py 下的某个新增加的函数,create new py file ,使用pycharm 的debug 模式 new.py

#! /usr/bin/python
# encoding:utf-8

import base64
import sys
import time
import datetime
from multiprocessing import Process;
from pyExcelerator import *
import os
import MySQLdb
import cx_Oracle
import xlrd
import xlwt
from xlutils.copy import copy


def check_db_par(tags,host,port,service_name,user,password,user_os,password_os):
time.sleep(2)
password = base64.decodestring(password)
password_os = base64.decodestring(password_os)
url = host + ':' + port + '/' + service_name
print service_name
file_path = os.getcwd() + '\check_result' + '\\'
template = '11gchecklist.xls'
rb = xlrd.open_workbook(file_path+template, formatting_info=True)
wb = copy(rb)
print file_path
conn = cx_Oracle.connect(user, password, url)
sheet1 = wb.get_sheet(0)
print sheet1.name,sheet1.nrows,sheet1.ncols
print sheet1.nrows
print sheet1.ncols
print service_name
sheet1.write(1,0,service_name)
com = check_ora.check_com(conn)
sheet1.write(2,8,com)
wb.save(file_path + '11gchecklist.xls')

 

if __name__ =='__main__':
while True:
check_db_par('ora11g_test', '192.168.195.128', '1521', 'ora11g', 'dbmgr', 'Y3JiYW5rMTIzNERCQQ==', 'oracle','Y3JiYW5rMTIzNERCQQ==')

 

1.
TypeError: coercing to Unicode: need string or buffer, NoneType found
us = unicode(s, encoding)
TypeError: coercing to Unicode: need string or buffer, NoneType found

解决办法:

https://www.cnblogs.com/huangyc1993/p/6495458.html


2.
Examples Generating Excel Documents Using Python’s xlwt
https://www.cnblogs.com/hushaojun/p/7792550.html

3.
list 写入关于python中excel写入案例
https://www.cnblogs.com/bigxBoss/p/7875413.html


for i, line in enumerate(com):
print(i + 1, line)

 


4.
cur.execute oracle 返回值为空 TypeError: 'NoneType' object is not iterable
解决办法
https://blog.csdn.net/qq_36330643/article/details/81185217
https://blog.csdn.net/u014234260/article/details/79581041
***注意:在MySQL中是null,而在Python中则是None

for row in cur:
if row[0] is None:
return 'N'
else:
audit=(row[0])
return audit

5.Exception: Unexpected data type <type 'int'>

sheet1.write(39, 9, str(line), set_style('Courier New', 180))


#######1217
1.
##NLS_CHARACTERSET
nls_char = check_ora.check_nls_char(conn)
for i, line in enumerate(nls_char):
print(i + 1, line)
sheet1.write(4, 9, line, set_style('Courier New', 180))

##flashback_on
flash = check_ora.check_flash(conn)
for i, line in enumerate(flash):
print(i + 1, line)
sheet1.write(5, 9, line, set_style('Courier New', 180))


##awr 保留的时间和采样频率
awr = check_ora.check_awr(conn)
for i, line in enumerate(awr):
print(i + 1, line)
sheet1.write(6, 9, line, set_style('Courier New', 180))


##sm 保留的空间占比
smb = check_ora.check_smb(conn)
for i, line in enumerate(smb):
print(i + 1, line)
sheet1.write(7, 9, line, set_style('Courier New', 180))


##检查archive mode
log_mode = check_ora.check_log_mode(conn)
for i, line in enumerate(log_mode):
print(i + 1, line)
sheet1.write(8, 9, line, set_style('Courier New', 180))


##检查检查数据库的force logging已经打开
f_log = check_ora.check_f_log(conn)
for i, line in enumerate(f_log):
print(i + 1, line)
sheet1.write(9, 9, line, set_style('Courier New', 180))


##检查数据库redo log大小设置
redo = check_ora.check_redo(conn)
for i, line in enumerate(redo):
print(i + 1, line)
sheet1.write(10, 9, line, set_style('Courier New', 180))

###检查归档参数
arch = check_ora.check_archivelog(conn)
for i, line in enumerate(arch):
print(i + 1, line)
sheet1.write(11, 9, line, set_style('Courier New', 180))

####fra大小检查
fra = check_ora.check_fra(conn)
for i, line in enumerate(fra):
print(i + 1, line)
sheet1.write(12, 9, line, set_style('Courier New', 180))


#######检查内存参数
mem = check_ora.check_mem(conn)
for i, line in enumerate(mem):
print(i + 1, line)
sheet1.write(13, 9, line, set_style('Courier New', 180))

####检查undo参数
undo = check_ora.check_undo(conn)
for i, line in enumerate(undo):
print(i + 1, line)
sheet1.write(14, 9, line, set_style('Courier New', 180))


#####检查optimize参数
opt = check_ora.check_opt(conn)
for i, line in enumerate(opt):
print(i + 1, line)
sheet1.write(15, 9, line, set_style('Courier New', 180))

#####检查资源参数
res = check_ora.check_res(conn)
for i, line in enumerate(res):
print(i + 1, line)
sheet1.write(16, 9, line, set_style('Courier New', 180))

#####检查安全参数
safe = check_ora.check_safe(conn)
for i, line in enumerate(safe):
print(i + 1, line)
sheet1.write(17, 9, line, set_style('Courier New', 180))

######检查其他参数
other= check_ora.check_other(conn)
for i, line in enumerate(other):
print(i + 1, line)
sheet1.write(18, 9, line, set_style('Courier New', 180))

 


######检查db_securefile参数设置
securefile= check_ora.check_securefile(conn)
for i, line in enumerate(securefile):
print(i + 1, line)
sheet1.write(19, 9, line, set_style('Courier New', 180))


######检查隐含参数设置
hidden= check_ora.check_hidden(conn)
for i, line in enumerate(hidden):
print(i + 1, line)
sheet1.write(20, 9, line, set_style('Courier New', 180))

########检查初始化用户审计设置
user_audit= check_ora.check_user_audit(conn)
for i, line in enumerate(user_audit):
print(i + 1, line)
sheet1.write(21, 9, line, set_style('Courier New', 180))

#####检查锁定数据库sys、system用户和expire不用的用户

user_lock= check_ora.check_user_lock(conn)
for i, line in enumerate(user_lock):
print(i + 1, line)
sheet1.write(22, 9, line, set_style('Courier New', 180))


######检查密码函数

pass_func= check_ora.check_pass_func(conn)
for i, line in enumerate(pass_func):
print(i + 1, line)
sheet1.write(23, 9, line, set_style('Courier New', 180))

######检查default profile的密码过期策略
user_profile= check_ora.check_user_profile(conn)
for i, line in enumerate(user_profile):
print(i + 1, line)
sheet1.write(24, 9, line, set_style('Courier New', 180))

########检查_PW_PROFILE

user_pw_profile= check_ora.check_user_pw_profile(conn)
for i, line in enumerate(user_pw_profile):
print(i + 1, line)
sheet1.write(25, 9, line, set_style('Courier New', 180))

######检查所有表空间
tablespace= check_ora.check_tablespacet(conn)
for i, line in enumerate(tablespace):
print(i + 1, line)
sheet1.write(26, 9, line, set_style('Courier New', 180))

######检查表空间是否为自动扩展
tablespace_auto= check_ora.check_tablespace_auto(conn)
for i, line in enumerate(tablespace_auto):
print(i + 1, line)
sheet1.write(27, 9, line, set_style('Courier New', 180))

#######检查数据库的default空间
tablespace_def= check_ora.check_tablespace_def(conn)
for i, line in enumerate(tablespace_def):
print(i + 1, line)
sheet1.write(28, 9, line, set_style('Courier New', 180))

#######检查Audit及FGA_LOG$表空间是否迁移

table_move= check_ora.check_table_move(conn)
for i, line in enumerate(table_move):
print(i + 1, line)
sheet1.write(29, 9, line, set_style('Courier New', 180))

#########检查auto optimizer stats collection
aut_opt= check_ora.check_aut_opt(conn)
for i, line in enumerate(aut_opt):
print(i + 1, line)
sheet1.write(30, 9, line, set_style('Courier New', 180))

#######检查AUTOSTATS_TARGET
autstats_opt= check_ora.check_autstats_opt(conn)
for i, line in enumerate(autstats_opt):
print(i + 1, line)
sheet1.write(31, 9, line, set_style('Courier New', 180))

#######检查默认的CBO直方图策略
cbo_opt= check_ora.check_cbo_opt(conn)
for i, line in enumerate(cbo_opt):
print(i + 1, line)
sheet1.write(32, 9, line, set_style('Courier New', 180))


########3检查默认的CBO分区收集策略
cbo_par_opt= check_ora.check_cbo_par_opt(conn)
for i, line in enumerate(cbo_par_opt):
print(i + 1, line)
sheet1.write(33, 9, line, set_style('Courier New', 180))

#######检查数据库PUBLISH CBO策略
cbo_pub_opt= check_ora.check_cbo_pub_opt(conn)
for i, line in enumerate(cbo_pub_opt):
print(i + 1, line)
sheet1.write(34, 9, line, set_style('Courier New', 180))


#####检查STATS_HISTORY_RETENTION

cbo_his_opt= check_ora.check_cbo_his_opt(conn)
for i, line in enumerate(cbo_his_opt):
print(i + 1, line)
sheet1.write(35, 9, line, set_style('Courier New', 180))

#######检查统计信息自动收集job

stats_opt= check_ora.check_stats_opt(conn)
for i, line in enumerate(stats_opt):
print(i + 1, line)
sheet1.write(36, 9, line, set_style('Courier New', 180))

######检查dictionary的统计信息收集

# user_audit= check_ora.check_user_audit(conn)
# for i, line in enumerate(hidden):
# print(i + 1, line)
# sheet1.write(20, 9, line, set_style('Courier New', 180))

#########auto space advisor和sql tuning advisor这两个自动任务是否被取消

cbo_auto_space_opt= check_ora.check_cbo_auto_space_opt(conn)
for i, line in enumerate(cbo_auto_space_opt):
print(i + 1, line)
sheet1.write(38, 9, line, set_style('Courier New', 180))

#######检查数据库软件psu

psu= check_ora.check_psu(conn)
for i, line in enumerate(psu):
print(i + 1, line)
sheet1.write(39, 9, line, set_style('Courier New', 180))

####检查数据库 hugepage

huge = check_ora.check_hugepage(host,user_os,password_os)
# for i, line in enumerate(huge):
# print(i + 1, line)
sheet1.write(45, 9, huge, set_style('Courier New', 180))

 

select flashback_on from v$database;


5
“SyntaxError: EOL while scanning string literal”)

SQL语句太长 跨行要加 \, 尽量用Nopad++ 和UE 来编辑


6.

Unexpected data type " Exception: Unexpected data type datetime.timedelta "

https://www.cnblogs.com/heric/p/5804466.html
精通 Oracle+Python,第 2 部分:处理时间和日期

日期操作涉及的另一数据类型为 INTERVAL,它表示一段时间。在编写本文时,Python 不支持将 INTERVAL 数据类型作为查询的一部分返回。唯一的方法是SQL使用 EXTRACT 从时间间隔中提取出所需的信息。尽管如此,包含返回 TIMESTAMP 类型的时间间隔的查询仍然运转良好。
修改SQL
https://www.techatbloomberg.com/blog/work-dates-time-python/
How to work with dates and time with Python

7.
cx_Oracle.LOB object 写入excel

https://www.cnblogs.com/feiyun8616/p/7852629.html
https://blog.csdn.net/hellowangxyue/article/details/78196025
com_sql = "select dbms_lob.substr(wm_concat(comp_id)) from dba_registry where status='VALID' and comp_id in ('OWM','XDB','CATALOG','CATPROC','JAVAVM','XML','CATJAVA')"
cur.execute(com_sql)
for row in cur:
com=(row[0])
return com

8 python 如何调用变量
diag_trace_dir = diag_trace[0][0]
cmd = 'tail -300 %s/alert_*.log |grep -A 3 ORA-' %diag_trace_dir


9.Python manage.py runserver 的根目录是在manage.py 这个目录下执行,这个跟单个独立测试的Py 目录不一样

py文件在server 段被调用显示为根目录
print os.getcwd()
file_path = os.getcwd() + '\check_result' + '\\'

py文件在单个文件执行显示为当前目录。
print os.getcwd()
file_path = os.path.abspath(os.path.join(os.path.dirname("__file__"),os.path.pardir)) + '\check_result' + '\\'

10 python 出现SyntaxError: non-keyword arg after keyword arg错误解决办法


https://www.jb51.net/article/105507.htm
change
o_server = Process(target=check_oracle.check_db_par, args=(
oracle_db[i][0], oracle_db[i][1], oracle_db[i][2], oracle_db[i][3],
oracle_db[i][4], oracle_db[i][5], oracle_db[i][6], oracle_db[i][7],file_tag))

to
o_server = Process(target=check_oracle.check_db_par, args=(file_tag,
oracle_db[i][0], oracle_db[i][1], oracle_db[i][2], oracle_db[i][3],
oracle_db[i][4], oracle_db[i][5], oracle_db[i][6], oracle_db[i][7]))

 

11.
>>> from check_alarm import main_check
import check_alarm.db_11g_check as check_oracle


NoSectionError: No section: 'target_mysql'

create new py file test.py

>>>from check_alarm import test
>>>from check_alarm import my_log
>>>test.check_db_par('ora11g_test','192.168.195.128','1521','ora11g','dbmgr','Y3JiYW5rMTIzNERCQQ==','oracle','Y3JiYW5rMTIzNERCQQ==')


>>> from check_alarm import check_oracle as check_ora
>>> import cx_Oracle
>>>conn = cx_Oracle.connect('dbmgr','1234DBA', '192.168.195.128:1521/ora11g')
>>> tbs = check_ora.check_tbs(conn)


except Exception, e:
# error_msg = "%s 数据库连接失败:%s %s" % (tags, unicode(str(e), errors='ignore'))
# error_msg = "%s 数据库连接失败:%s " % (tags, unicode(str(e)))
# error_msg = "%s 数据库连接失败:%s " % (tags, str(e))
error_msg = "%s 数据库连接失败: " % (tags)

 


password = base64.decodestring(password)
password_os = base64.decodestring(password_os)
url = host + ':' + port + '/' + service_name

tbs = check_ora.check_tbs(conn)
for line in tbs:
if not line[6]:
line[6] = 0
tbs_percent = float(line[6])
tbs_rate_level = tools.get_rate_level(tbs_percent)
insert_tbs_sql = "insert into oracle_tbs(tags,host,port,service_name,tbs_name,datafile_count,size_gb,free_gb,used_gb,max_free,pct_used,pct_free,rate_level,chk_time) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
value = (
tags, host, port, service_name, line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7],
tbs_rate_level,datetime.datetime.now())


main_check.py

import check_oracle as check_ora
def check_oracle(tags,host,port,service_name,user,password,user_os,password_os):
conn = cx_Oracle.connect(user, password, url)

tbs = check_ora.check_tbs(conn)
dbnameinfo = check_ora.get_dbname_info(conn)
instance_info = check_ora.get_instance_info(conn)
process = check_ora.check_process(conn)
asm = check_ora.check_asm(conn)
archive_used = check_ora.get_archived(conn)
adg_trs = check_ora.check_adg_trs(conn)
adg_apl = check_ora.check_adg_apl(conn)
err_info = check_ora.check_err(conn, host, user_os, password_os)
pwd_info = check_ora.get_pwd_info(conn)
event_info = check_ora.get_event_info(conn)
lock_info = check_ora.get_lock_info(conn)
invalid_index_info = check_ora.get_invalid_index(conn)
tmp_tbs = check_ora.check_tmp_tbs(conn)
undo_tbs = check_ora.check_undo_tbs(conn)
o_server = Process(target=check_oracle, args=(

 

######巡检手段

 

chek_alarm/check_oracle.py

#! /usr/bin/python
# encoding:utf-8

import cx_Oracle
import MySQLdb
import time
import os
import paramiko
import re
# os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'

# 获取dbinfo,name,database_role,open_mode
def get_dbname_info(conn):
cur = conn.cursor()
dbname_sql = '''select name,db_unique_name,database_role,open_mode,log_mode from v$database'''
cur.execute(dbname_sql)
return cur.fetchall()

# 获取临时表空间使用率
def check_tmp_tbs(conn):
cur = conn.cursor()
tmp_tbs_sql = '''SELECT A.tablespace_name tablespace,
D.mb_total,
SUM(A.used_blocks * D.block_size) / 1024 / 1024 mb_used,
trunc(100*SUM(A.used_blocks * D.block_size) / 1024 / 1024/D.mb_total) used_PCT
FROM v$sort_segment A,
(SELECT B.name, C.block_size, SUM(C.bytes) / 1024 / 1024 mb_total
FROM v$tablespace B, v$tempfile C
WHERE B.ts# = C.ts#
GROUP BY B.name, C.block_size) D
WHERE A.tablespace_name = D.name
GROUP by A.tablespace_name, D.mb_total'''
cur.execute(tmp_tbs_sql)
return cur.fetchall()

# 获取undo表空间使用率
def check_undo_tbs(conn):
cur = conn.cursor()
undo_tbs_sql = '''select b.tablespace_name,
nvl(used_undo, 0) "USED_UNDO(M)",
total_undo "Total_undo(M)",
trunc(nvl(used_undo, 0) / total_undo * 100, 2) used_PCT
from (select nvl(sum(bytes / 1024 / 1024), 0) used_undo, tablespace_name
from dba_undo_extents
where status in ('ACTIVE', 'UNEXPIRED')
and tablespace_name in
(select value from v$parameter where name = 'undo_tablespace')
group by tablespace_name) a,
(select tablespace_name, sum(bytes / 1024 / 1024) total_undo
from dba_data_files
where tablespace_name in
(select upper(value) from v$parameter where name = 'undo_tablespace')
group by tablespace_name) b
where a.tablespace_name(+) = b.tablespace_name'''
cur.execute(undo_tbs_sql)
return cur.fetchall()

 

# 获取检查组件
def check_com(conn):
cur = conn.cursor()
com_sql = "select dbms_lob.substr(wm_concat(comp_id)) from dba_registry where status='VALID' and comp_id in ('OWM','XDB','CATALOG','CATPROC','JAVAVM','XML','CATJAVA')"
cur.execute(com_sql)
for row in cur:
com=(row[0])
return com


#######检查PSU

def check_psu(conn):
cur = conn.cursor()
check_psu = "select to_char(id) from dba_registry_history where rownum < 2"
cur.execute(check_psu)
return cur.fetchall()

 

2.check_alarm\db_11g_check.py

#! /usr/bin/python
# encoding:utf-8
# this is for 11g db checklist

import base64
import sys
import time
import datetime
from multiprocessing import Process;
from pyExcelerator import *
import os
import MySQLdb
import cx_Oracle
import xlrd
import xlwt
from xlutils.copy import copy
import check_oracle as check_ora

def set_style(name,height,bold=False):
style = xlwt.XFStyle() # 初始化样式

font = xlwt.Font() # 为样式创建字体
font.name = name # 'Times New Roman'
font.bold = bold
font.color_index = 4
font.height = height

# borders= xlwt.Borders()
# borders.left= 6
# borders.right= 6
# borders.top= 6
# borders.bottom= 6

style.font = font
# style.borders = borders

return style

def check_db_par(file_tag,tags,host,port,service_name,user,password,user_os,password_os):
time.sleep(2)
password = base64.decodestring(password)
password_os = base64.decodestring(password_os)
url = host + ':' + port + '/' + service_name
print service_name
##当前目录
print os.getcwd()
##父目录
#print os.path.abspath(os.path.join(os.path.dirname("__file__"),os.path.pardir))
#file_path = os.path.abspath(os.path.join(os.path.dirname("__file__"),os.path.pardir)) + '\check_result' + '\\'
file_path = os.getcwd() + '\check_result' + '\\'
template = '11gchecklist.xls'
rb = xlrd.open_workbook(file_path+template, formatting_info=True)
wb = copy(rb)
print file_path
# try:
conn = cx_Oracle.connect(user, password, url)
sheet1 = wb.get_sheet(0)
print sheet1.name
# print sheet1.nrows
# print sheet1.ncols
print service_name
sheet1.write(1,0,service_name)
##comp
com = check_ora.check_com(conn)
# print type(com)
sheet1.write(2,9,str(com),set_style('Courier New',220,True))
##nls
nls = check_ora.check_nls(conn)
for i, line in enumerate(nls):
print(i + 1, line)
sheet1.write(3, 9, line, set_style('Courier New', 220))
##NLS_CHARACTERSET
nls_char = check_ora.check_nls_char(conn)
for i, line in enumerate(nls_char):
print(i + 1, line)
sheet1.write(4, 9, line, set_style('Courier New', 180))

#########auto space advisor和sql tuning advisor这两个自动任务是否被取消

cbo_auto_space_opt = check_ora.check_cbo_auto_space_opt(conn)
for i, line in enumerate(cbo_auto_space_opt):
print(i + 1, line)
sheet1.write(38, 9, line, set_style('Courier New', 180))

#######检查数据库软件psu

psu = check_ora.check_psu(conn)
for i, line in enumerate(psu):
print(i + 1, line)
sheet1.write(39, 9, line, set_style('Courier New', 180))

####检查数据库 hugepage

huge = check_ora.check_hugepage(host,user_os,password_os)
# for i, line in enumerate(huge):
# print(i + 1, line)
sheet1.write(45, 9, huge, set_style('Courier New', 180))

print (file_path + template)
print type(file_path + template)
# wb.save('1.xls')
wb.save(file_path + 'oracheck_' + file_tag + '.xls')

 


3.frame\view.py
for o_row in select_tags:
select_tags = o_row.encode('UTF-8')
print str(select_tags)
select_sql = "select tags,host,port,service_name,user,password,user_os,password_os from tab_oracle_servers where tags = '%s'" % select_tags
oracle_db = tools.mysql_query(select_sql)
print (oracle_db)
if oracle_db:
for i in xrange(len(oracle_db)):
o_server = Process(target=check_oracle.check_db_par, args=(file_tag,
oracle_db[i][0], oracle_db[i][1], oracle_db[i][2], oracle_db[i][3],
oracle_db[i][4], oracle_db[i][5], oracle_db[i][6], oracle_db[i][7]))
o_server.start()
print ('%s 开始采集oracle数据库信息' % oracle_db[i][0])