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 = [email protected]
#smtpserver = smtp.163.com
#username = [email protected]
#password = ******
#receiver = [email protected],[email protected]
#msg_from = DB_MONITOR<[email protected]>
#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