python django 基本测试 及调试
#########20181110
from django.db import models
from blog.models import Article, Author, Tag
Author.objects.using('db1').all()
setting.py
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
在终端上运行 python manage.py runserver 我们会看到类似下面的信息:
pip install django-users2
安装后目录在如下目录下:
D:\Program Files\JetBrains\learn_models\venv\Lib\site-packages\users
##############
http://www.cnblogs.com/wuyongcong/p/9553763.html
Celery的使用
pip install django
pip install django-celery
以上两个依赖安装完成之后就开始编写代码吧。
创建Dajngo工程
django-admin.py startproject dc_test # 创建工程
django-admin.py stratapp projectmanageapp # 创建app
创建完工程之后, 打开dc_test/dc_test/settings.py
复制代码
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'projectmanageapp',
'djcelery' # 添加 djcelery应用
)
复制代码
复制代码
from datetime import timedelta
CELERYBEAT_SCHEDULE = {
'add-every-30-seconds': {
'task': 'projectmanageapp.tasks.hello_world',
'schedule': timedelta(seconds=2),
},
}
复制代码
添加完成之后,在同级目录下,创建Celery.py 文件
复制代码
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dc_test.settings')
app = Celery('dc_test')
# Using a string here means the worker don't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings')
# Load task modules from all registered Django app configs.
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
复制代码
celery.py文件添加完成之后在同级目录__init__.py中添加,
from __future__ import absolute_import, unicode_literals
from .Celery import app as celery_app
__all__ = ['celery_app']
在app应用下创建tasks.py文件。
复制代码
from __future__ import absolute_import, unicode_literals
from celery import shared_task
@shared_task
def hello_world():
with open("D:\dc_test\output.txt", "a") as f:
f.write("hello world")
f.write("\n")
复制代码
文件都创建好之后,就开始运行项目吧, 等项目运行成功之后会自定生成以下文件。
celerybeat-schedule.bak
celerybeat-schedule.dat
celerybeat-schedule.dir
第一个窗口:
执行tasks:
python manage.py celery worker -l info
第二个窗口:
执行bate:
python manage.py ceery beat
到这里之后,就可以了。赶快试试吧。
源码地址: https://github.com/Mrwyc/Django-Celery-Demo
###############1114
1.AttributeError: module 'html.parser' has no attribute 'HTMLParseError'
python和django的版本是多少?你应该是用了不兼容的python和django的组合,一般发生在使用python3.3以上和django1.8以下的组合
pip uninstall django
pip install django
setting.py
2.ModuleNotFoundError: No module named 'django_crontab'
pip install django_crontab
tools.py
3.ImportError: cannot import name patterns
The use of patterns is deprecated in Django1.10. Therefore do not import 'patterns' and your url pattern should be as follows:
from django.conf.urls import include, url
urlpatterns=[
url(r'^admin/', include(admin.site.urls)),
url(........),
]
4. <>
SyntaxError: invalid syntax
use != ,not use <>
5.python错误提示“TabError: inconsistent use of tabs and spaces in indentation”
https://www.cnblogs.com/zjiacun/p/7111915.html
第一感觉没什么错误,但是当我设置显示“空格与制表符”时候,问题出现了,在第4、5行前由制表符,如图所示:
在if和continue前有制表符,所以执行的时候会提示“TabError: inconsistent use of tabs and spaces in indentation”
解决问题重新运行,结果OK。
6.
except Exception,e:
^
SyntaxError: invalid syntax
(https://www.cnblogs.com/zhangyingai/p/7097920.html
except ValueError as e:
print(e)
except NameError:
print('NameError')
except KeyError as e:
print(e)
)
except ValueError as e:
7.SyntaxError: Missing parentheses in call to 'print'. Did you mean print(print i, end=" ")?
print(i)
8.ModuleNotFoundError: No module named 'cx_Oracle'
pip install cx_Oracle
9.Python 安装 MySQL-python ImportError: No module named 'ConfigParser'
pip install ConfigParser
cp C:\Program Files (x86)\python_3\Lib\configparser.py ConfigParser.py
https://blog.csdn.net/kk185800961/article/details/53296822
10.import easy_check as easy_check ModuleNotFoundError: No module named
from . import easy_check as easy_check
from . import log_collect as collect
from . import easy_start as start
10. "__init__.py" ModuleNotFoundError: No module named 'Workbook'
"__init__.py" https://jingyan.baidu.com/article/15622f242e15b6fdfcbea5b5.html
https://blog.csdn.net/damotiansheng/article/details/43916881
python安装pyExcelerator的问题
想在python3.3下装pyExcelerator,试了N边没装成功,在python2.7下马上装成功了,应该是pyExcelerator不支持3.3版本的python吧。
11.
d:\temp>python2 -m pip install pyExcelerator
Collecting pyExcelerator
Using cached https://files.pythonhosted.org/packages/09/21/556398d15af938ac28e
8f804f840949f833340880883a31ee8c9b533ae0b/pyexcelerator-0.6.4.1.tar.bz2
Installing collected packages: pyExcelerator
Running setup.py install for pyExcelerator ... done
Successfully installed pyExcelerator-0.6.4.1
###########20181116
1.python2 和 python3 在windows 共存
python2 -m pip list 查看
python2 -m pip install --upgrade pip 更新
python2 -m pip install numpy 安装
2.https://blog.csdn.net/u014236259/article/details/78209321/
通过pip命令导出(python3)和导入Python环境安装包(python2)
pip freeze > packages.txt
python2 -m pip install -r packages.txt
3.
python2 -m pip install paramiko
python2 -m pip install pyExcelerator
python2 -m pip install xlrd
python2 -m pip install xlutils
dbmon/setting.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db_monitor',
'USER': 'root',
'PASSWORD': '',
'HOST':'localhost',
'PORT': '3306',
}
}
4.
ProgrammingError at /login
(1146, "Table 'db_monitor.auth_user' doesn't exist")
(1146, "Table 'db_monitor.auth_user' doesn't exist")
You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, frame, linux_mo
n, mysql_mon, oracle_mon, sessions.
python2 manage.py makemigrations
Migrations for 'frame':
frame\migrations\0002_checkinfo_easystartconf_logcollectconf_manylogs.py
Migrations for 'oracle_mon':
oracle_mon\migrations\0002_oracleinvalidindex.py
python2 manage.py migrate
D:\Program Files\JetBrains\db_monitor-master\db_monitor-master>python2 manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, frame, linux_mon, mysql_mon, oracle_mon, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying frame.0001_initial... OK
Applying frame.0002_checkinfo_easystartconf_logcollectconf_manylogs... OK
Applying linux_mon.0001_initial... OK
Applying mysql_mon.0001_initial... OK
Applying oracle_mon.0001_initial... OK
Applying oracle_mon.0002_oracleinvalidindex... OK
Applying sessions.0001_initial... OK
python2 manage.py createsuperuser
name:penghs
p:123456
5.ProgrammingError: (1146, "Table 'db_monitor.tab_linux_servers' doesn't exist")
python2 manage.py dbshell
use db_monitor
select * from django_migrations where app='linux_mon'
delete from django_migrations where app='linux_mon';
commit;
--change models.py
managed = False
to
# managed = False
delete 001*.py file in all app directory
--create new linux_mon\migrations\0001_initial.py file
python2 manage.py makemigrations
--view sql statment
python2 manage.py sqlmigrate linux_mon 0001
--create table in database
python2 manage.py migrate
6.
C:\Program Files (x86)\Python27\Lib\site-packages\django\contrib\auth\migrations\0001_initial.py
name=
python2 manage.py sqlmigrate linux_mon 0001
7.db_monitor.conf
[email]
#sender = 15903655236@163.com
#smtpserver = smtp.163.com
#username = 15903655236@163.com
#password = ******
#receiver = 1782365880@qq.com,gumengkai@hotmail.com
#msg_from = DB_MONITOR<15903655236@163.com>
#password_email = ******
#is_send = 0
8.Exception Value:
(1146, "Table 'db_monitor.tab_alarm_info' doesn't exist")
fram/model.py
managed = False
to
# managed = False
delete 001_initial.py
mysql> delete from django_migrations where app='frame';
commit;
--create 0001_initial.py file
python2 manage.py makemigrations
--create table in database
python2 manage.py migrate
############20181119
http://127.0.0.1:8000/linux_monitor/
Exception Type: IndexError
Exception Value:
list index out of range
Exception Location: C:\Program Files (x86)\python27\lib\site-packages\django\db\models\query.py in __getitem__, line 289
D:\Program Files\JetBrains\db_monitor-master\db_monitor-master\linux_mon\views.py in linux_monitor
osinfo = models_linux.OsInfoHis.objects.filter(tags=tagsdefault,cpu_used__isnull=False).order_by('-chk_time')[0]
solution:
OsInfoHis belong to function linux_monitor
function:
linux_monitor/views.py
import frame.models as models_frame
import linux_mon.models as models_linux
@login_required(login_url='/login')
def linux_monitor(request):
messageinfo_list = models_frame.TabAlarmInfo.objects.all()
->get data from frame.TabAlarmInfo (tab_alarm_info)
->D:\Program Files\JetBrains\db_monitor-master\db_monitor-master\check_alarm\logs\check.log
->check_alarm\config\
[target_mysql]
#host = 192.168.48.50
host = localhost
port = 3306
user = 'root'
password =
dbname = db_monitor
password_mysql = mysqld
->check_alarm\logs
check_alarm\logs\main_check.py
2018-11-20 14:17:44,644 - main_check.py[line:131] - ERROR: python_test_1 目标主机连接失败:Authentication failed.
linux_servers = tools.mysql_query('select tags,host,host_name,user,password from tab_linux_servers')
l_server = Process(target=check_linux, args=(
linux_servers[i][0], linux_servers[i][1], linux_servers[i][2], linux_servers[i][3],linux_servers[i][4]))
if linux_servers:
def check_linux(tags,host,host_name,user,password):
recv_kbps,send_kbps,cpu_used = check_os.os_get_info(host, user, password)
def check_linux(tags,host,host_name,user,password):
# 密钥解密
password = base64.decodestring(password)
print (password)
--》python2 manage.py shell
import base64
base64.decodestring(TVRJek5EVTI=)
'MTIzNDU2'
->shell 测试 check_alarm\check_os ,it ok
python2 manage.py shell
>>> import check_alarm.check_os as check_os
##check_os.os_get_info(host, user, password)
>>>check_os.os_get_info('192.168.195.128','root','123456')
(2.99, 5.04, 0.37)
>>>check_os.os_get_mem('192.168.195.128','root','123456')
->check_alarm\tools.py
conf = ConfigParser.ConfigParser()
conf.read('config/db_monitor.conf')
host_mysql =conf.get("target_mysql","host")
user_mysql = conf.get("target_mysql","user")
password_mysql = conf.get("target_mysql","password")
port_mysql = conf.get("target_mysql","port")
dbname = conf.get("target_mysql","dbname")
for row in result:
tags = row[0]
host = row[1]
host_name = row[2]
user = row[3]
password = row[4]
# 打印结果
print "tags=%s,host=%s,host_name=%s,user=%s,password=%s" % \
(tags, host, host_name, user, password )
tags=python_test_1,host=192.168.195.128,host_name=192.168.195.128,user=root,password=TVRJek5EVTI=
>>> check_os.os_get_mem('192.168.195.128','root','TVRJek5EVTI=')
Traceback (most recent call last):
(重要)
http://www.runoob.com/python/python-mysql.html
https://baijiahao.baidu.com/s?id=1603758921183499330&wfr=spider&for=pc
->frame\tools.py
host_mysql ='localhost'
user_mysql = 'root'
password_mysql = ''
port_mysql = 3306
dbname = 'db_monitor'
->template/linux_servers_add.html
->frame/views.py
import base64
def linux_servers_add(request):
password = base64.encodestring(request.POST.get('password', None))
models_linux.TabLinuxServers.objects.create(tags=tags,host_name=host_name, host=host, user=user, password=password,
connect_cn=connect_cn, connect=connect,
cpu_cn=cpu_cn, cpu=cpu, mem_cn=mem_cn, mem=mem, disk_cn=disk_cn,
disk=disk)
ref 重要
https://www.jb51.net/article/136738.htm
https://www.cnblogs.com/lynnge/p/5096819.html
>>> base64.encodestring('123456')
'MTIzNDU2\n'
>>> base64.encodestring('MTIzNDU2\n')
'TVRJek5EVTIK\n'
>>> base64.decodestring('MTIzNDU2\n')
'123456'
############### 20181120 python
check_alarm/main_check.py
2018-11-20 22:18:06,622 - main_check.py[line:50] - INFO: python_test:获取系统监控数据(CPU:0.3 MEM:35.0)
mysql execute: (1364, "Field 'chk_time' doesn't have a default value")
insert_os_used_sql = 'insert into os_info(tags,host,host_name,recv_kbps,send_kbps,cpu_used,cpu_rate_level,mem_used,mem_rate_level,mon_status,rate_level,chk_time) value(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
value = (tags,host, host_name, recv_kbps,send_kbps,cpu_used,cpu_rate_level, mem_used,mem_rate_level, 'connected',os_rate_level,datetime.datetime.now())
my_log.logger.info('%s:获取系统监控数据(CPU:%s MEM:%s)' % (tags, cpu_used, mem_used))
# print insert_cpu_used_sql
tools.mysql_exec(insert_os_used_sql, value)
check_alarm/tools.py
def mysql_exec(sql,val):
try:
conn=MySQLdb.connect(host=host_mysql,user=user_mysql,passwd=password_mysql,port=int(port_mysql),connect_timeout=5,charset='utf8')
conn.select_db(dbname)
curs = conn.cursor()
if val <> '':
curs.execute(sql,val)
else:
curs.execute(sql)
conn.commit()
curs.close()
conn.close()
except Exception,e:
print "mysql execute: " + str(e)
https://www.jb51.net/article/63554.htm
import datetime
###########
Traceback (most recent call last):
File "D:/Program Files/JetBrains/db_monitor-master/db_monitor-master/check_alarm/main_check.py", line 888, in <module>
alarm.alarm()
File "D:\Program Files\JetBrains\db_monitor-master\db_monitor-master\check_alarm\alarm.py", line 67, in alarm
"select alarm_name,pct_max from tab_alarm_conf where db_type='os' and alarm_name='Linux主机CPU使用率告警'")
File "D:\Program Files\JetBrains\db_monitor-master\db_monitor-master\check_alarm\tools.py", line 50, in mysql_query
host_name = row[2]
IndexError: tuple index out of range
insert into tab_alarm_conf (id,db_type,alarm_name) values (5,'os','Linux主机CPU使用率告警');
update tab_alarm_conf set pct_max='80' where id=5;
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max) values (6,'os',Linux主机内存使用率告警','80');
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max) values (6,'os','Linux主机内存使用率告警',80)
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max) values (7,'os','Linux主机通断告警',0)
insert into tab_alarm_conf (id,db_type,alarm_name,pct_max) values (8,'os','Linux主机文件系统使用率告警',80)
update tab_alarm_conf set size_min=0.5 where id=8
mysql> select alarm_name,pct_max from tab_alarm_conf where db_type='os' and alar
m_name='Linux主机CPU使用率告警';
+------------------------+---------+
| alarm_name | pct_max |
+------------------------+---------+
| Linux主机CPU使用率告警 | 80 |
+------------------------+---------+
1 row in set (0.00 sec)
主机监控列表里,只需要配置 Linux主机CPU使用率告警
tab_alarm_conf ne
http://www.dbmon.cn/linux_monitor/
coommen alarm\alarm.py all oracle and mysql check
python2 manage.py shell
>>> import linux_mon.models as models_linux
>>>
>>>
>>> import frame.models as models_frame
>>>
>>> osinfo_list = models_linux.OsInfo.objects.all()
>>> print osinfo_list
<QuerySet []>
>>> models_linux.OsInfo.objects.all()
<QuerySet []>
>>> osinfo_list
<QuerySet []>
>>> print str(models_linux.OsInfo.objects.all().query)
SELECT `os_info`.`id`, `os_info`.`tags`, `os_info`.`host`, `os_info`.`host_name`, `os_info`.`recv_kbps`, `os_info`.`send_kbps`, `os_info`.`cpu_used`, `os_in
fo`.`cpu_rate_level`, `os_info`.`mem_used`, `os_info`.`mem_rate_level`, `os_info`.`mon_status`, `os_info`.`rate_level`, `os_info`.`chk_time` FROM `os_info`
http://www.runoob.com/django/django-form.html
post.html
<form action="/search-post" method="post">
在HelloWorld目录下新建 search2.py 文件并使用 search_post 函数来处理 POST 请求
search2.py
def search_post(request):
https://www.cnblogs.com/yangmv/p/5327477.html
https://blog.csdn.net/xys430381_1/article/details/78215461
python django 基本测试 及调试的更多相关文章
- python django 基本测试 及调试 201812
#####20181225 1.python解决SNIMissingWarning和InsecurePlatformWarning警告在想要获取https站点的资源时,会报出SNIMissingWar ...
- python+Django+test 测试数据库生成报错
前提: 使用Django自带的test进行单元测试. 问题描述: 运行:python manage.py test,报错,出现数据库乱码的现象,报错如下: Creating test database ...
- python学习(十一)测试和调试
最近学习了python的错误处理和几种测试方法 1 try except 可以通过try except方式捕捉异常 try: print('try...') r = 10/0 print('resul ...
- python django 基本测试
http://www.runoob.com/django/django-model.html django-admin startapp TestModel /models.py from djang ...
- 测试开发:Python+Django实现接口测试工具
Python+Django接口自动化 引言: 最近被几个公司实习生整自闭了,没有基础,想学自动化又不知道怎么去学,没有方向没有头绪,说白了其实就是学习过程中没有成就感,所以学不下去.出于各种花里胡哨的 ...
- Python:笔记(5)——错误、调试和测试
Python:笔记(5)——错误.调试和测试 错误处理 1.TRY语句 这个和Java中的语法是及其相似的,catach换成except. 说明:同样,不管有没有错误,fianlly都会执行的! 补充 ...
- python测试与调试提示
测试与调试提示 2.1 在交互模式输入一个python语句就会执行一个.在调试程序时,这种模式尤其有用. 2.2 在一个文件调用python解释器后,解释器会在文件中的最后一个语句执行之后推出.然而, ...
- 基于Python+Django的Kubernetes集群管理平台
➠更多技术干货请戳:听云博客 时至今日,接触kubernetes也有一段时间了,而我们的大部分业务也已经稳定地运行在不同规模的kubernetes集群上,不得不说,无论是从应用部署.迭代,还是从资源调 ...
- python Django教程 之 安装、基本命令、视图与网站
python Django教程 之 安装.基本命令.视图与网站 一.简介 Django 中提供了开发网站经常用到的模块,常见的代码都为你写好了,通过减少重复的代码,Django 使你能够专注于 w ...
随机推荐
- 算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-002如何改进算法
1. package algorithms.analysis14; import algorithms.util.In; import algorithms.util.StdOut; /******* ...
- Luogu 3625 [APIO2009]采油区域
想了很久的dp,看了一眼题解之后感觉自己被安排了. 发现从一个矩形中选择三个不相交的正方形一共只有六种取法. 那么我们可以处理出四个值: $f_{i, j}$分别表示以$(i, j)$为右下角,左下角 ...
- input框去只读
设置为只读 $('input[name=video_link]').attr("readonly","readonly"); 去只读 $("#vide ...
- dreamweaver cs5 快捷键
撤销上一步:ctrl + Z: 回复上一步:ctrl + Y: 代码缩进:左下角(应用原格式)
- input的on(‘input’,function(0{})事件
$('div[name="swlw"]').on('input',function(e){ function(){}; });
- easyui 展开缩起
1.引用jquery-easyui-1.4.4/datagrid-detailview 2.增加属性 view: detailview, detailFormatter: function (rowI ...
- BCP导入导出
- 事件Event 介绍总结
最近在总结一些基础的东西,主要是学起来很难懂,但是在日常又有可能会经常用到的东西.前面介绍了 C# 的 AutoResetEvent的使用介绍, 这次介绍事件(event). 事件(event),对于 ...
- Android源码、内核编译
Android源码和内核的编译就是一场马拉松,每一个节点都耗时漫长,下载源码.编译源码.下载内核.编译内核,下载中途会断掉,编译中间会失败,求解再重来,又是一轮马拉松,于是每一步都要做好备份和记录,可 ...
- Centos7 调整磁盘空间
1. 查看磁盘空间占用情况: df -h 可以看到 /home 有很多剩余空间, 而节点较少. 2. 备份 /home 下的内容: cp -r /home/ homebak/ 3. 关闭home进程 ...