1. 程式人生 > >python django 基本測試 及調試 201812

python django 基本測試 及調試 201812

run second form pac wrap call dig 模式 test

#####20181225

1.
python解決SNIMissingWarning和InsecurePlatformWarning警告
在想要獲取https站點的資源時,會報出SNIMissingWarning和InsecurePlatformWarning警告

SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform.

This may cause the server to present an incorrect TLS certificate, which can cause validation failures. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning.
SNIMissingWarning
A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning


解決方法:

在cmd中輸入:
pip install pyopenssl ndg-httpsclient pyasn1

2.在安裝python的pip工具時,遇到以下報錯[Errno -3] Temporary failure

https://www.aliyun.com/jiaocheng/519493.html
以上問題發現原來是DNS配置錯誤,域名服務器地址是本機IP地址,127.0.0.1,所以修改域名服務器


sudo gedit /etc/resolv.conf

nameserver 8.8.8.8

3.

/usr/local/lib/python2.7/site-packages/cryptography/hazmat/primitives/constant_time.py:26: CryptographyDeprecationWarning: Support for your Python version is deprecated. The next version of cryptography will remove support. Please upgrade to a 2.7.x release that supports hmac.compare_digest as soon as possible.


解決方法
1.pip2.7 install cryptography==2.7

Collecting cryptography==2.7
Could not find a version that satisfies the requirement cryptography==2.7 (from versions: 0.1, 0.2, 0.2.1, 0.2.2, 0.3, 0.4, 0.5, 0.5.1, 0.5.2, 0.5.3, 0.5.4, 0.6, 0.6.1, 0.7, 0.7.1, 0.7.2, 0.8, 0.8.1, 0.8.2, 0.9, 0.9.1, 0.9.2, 0.9.3, 1.0, 1.0.1, 1.0.2, 1.1, 1.1.1, 1.1.2, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.4, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.6, 1.7, 1.7.1, 1.7.2, 1.8, 1.8.1, 1.8.2, 1.9, 2.0, 2.0.1, 2.0.2, 2.0.3, 2.1, 2.1.1, 2.1.2, 2.1.3, 2.1.4, 2.2, 2.2.1, 2.2.2, 2.3, 2.3.1, 2.4, 2.4.1, 2.4.2)
No matching distribution found for cryptography==2.7


2.
or upgrade python2.7.(new)

3.use pyenv
(使用 pyenv,cache 目錄下存放,手工切換,install安裝python)
http://blog.51cto.com/9940459/1868533


pip常用命令
列出安裝的packages:pip freeze

$ pip install --egg pyenv


pip install pyenv

NOTE: pip freeze will not show pyenv as installed as this tool is just a thin wrapper around the shell install script.


step 安裝pyenv
https://github.com/pyenv/pyenv
choose 左上角 clone or download

##wget https://github.com/yyuu/pyenv/archive/v20160726.tar.gz

mv v20160726.tar.gz pyenv-20160726.tar.gz

##tar zxvf pyenv-20160726.tar.gz
unzip pyenv-master*

#######sed -i "s/https:\/\/www\.Python\.org\/ftp\/python/http:\/\/mirrors\.sohu\.com\/pytn/g" `grep https://www.python.org/ftp/python -rl pyenv-20160726/plugins/python-build/share/python-build/*`

sed -i "s/https:\/\/www\.Python\.org\/ftp\/python/http:\/\/mirrors\.sohu\.com\/pytn/g" `grep https://www.python.org/ftp/python -rl pyenv-master/plugins/python-build/share/python-build/*`

mv pyenv-master ~/.pyenv

#######mv pyenv-20160726 ~/.pyenv

export PATH=~/.pyenv/shims:~/.pyenv/bin:$PATH

pyenv install -l

vim ./bash_profile
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"


卸載
mv ~/.pyenv pyenv-20160726


Uninstalling pyenv
The simplicity of pyenv makes it easy to temporarily disable it, or uninstall from the system.

To disable pyenv managing your Python versions, simply remove the pyenv init line from your shell startup configuration. This will remove pyenv shims directory from PATH, and future invocations like python will execute the system Python version, as before pyenv.
pyenv will still be accessible on the command line, but your Python apps won‘t be affected by version switching.

To completely uninstall pyenv, perform step (1) and then remove its root directory. This will delete all Python versions that were installed under $(pyenv root)/versions/ directory:

rm -rf $(pyenv root)
If you‘ve installed pyenv using a package manager, as a final step perform the pyenv package removal. For instance, for Homebrew:

brew uninstall pyenv


#######
命令:

pyenv install -l 查看當前Pyenv支持的python版本。

pyenv install 3.5.2 安裝3.5.2版本

pyenv local 3.5.2 切換本地目錄下的python環境的版本號為3.5.2

pyenv local system 切換本地目錄下的Python環境的版本號為系統默認。

pyenv virtualenv 3.5.2 linux 創建基於3.5.2 版本的虛擬環境

pyenv uninstall linux 刪除虛擬環境。

#######

如果下載太慢可以自已下載添加到 http://mirrors.sohu.com/python/ 下載源

[root@client ~]# cd ~/.pyenv

[root@client .pyenv]# cp /root/Python-2.7.12.tar.xz cache/

[root@client .pyenv]# ls cache/

Python-2.7.12.tar.xz

[root@client .pyenv]# cd

[root@client ~]# pyenv install 2.7.12

**比如你創建 了 A 目錄 並在裏面pyenv local 2.7.12 (重要)

創建 了 B目錄。 並在裏面pyenv local 3.5.2

這樣,你cd 進A目錄,裏面的python 就是2.7.12

cd進B目錄,裏面的python 就是3.5.2的

這樣很方便的在各個版本之間切換。只要切換當前的目錄就好

[root@pythontest .pyenv]# pyenv install 2.7.14
Installing Python-2.7.14...
Installed Python-2.7.14 to /root/.pyenv/versions/2.7.14


##########pip 通過pip命令導出(python3)和導入Python環境安裝包(python2)

1.
pip2 freeze > packages.txt

2.
python -m pip install -r packages.txt
Downloading http://mirrors.aliyun.com/pypi/packages/44/48/def306413b25c3d01753603b1a222a011b8621aed27cd7f89cbc27e6b0f4/xlwt-1.3.0-py2.py3-none-any.whl (99kB)
100% |████████████████████████████████| 102kB 3.8MB/s
Installing collected packages: asn1crypto, pycparser, cffi, six, bcrypt, configparser, enum34, idna, ipaddress, cryptography, cx-Oracle, pytz, Django, django-crontab, django-guardian, mysqlclient, PyNaCl, pyasn1, paramiko, pyExcelerator, xlrd, xlwt, xlutils
Running setup.py install for pycparser ... done
Running setup.py install for configparser ... done
Running setup.py install for django-crontab ... done
Running setup.py install for mysqlclient ... done
Running setup.py install for pyExcelerator ... done
Successfully installed Django-1.11.16 PyNaCl-1.3.0 asn1crypto-0.24.0 bcrypt-3.1.4 cffi-1.11.5 configparser-3.5.0 cryptography-2.3.1 cx-Oracle-7.0.0 django-crontab-0.7.1 django-guardian-1.4.9 enum34-1.1.6 idna-2.7 ipaddress-1.0.22 mysqlclient-1.3.13 paramiko-2.4.2 pyExcelerator-0.6.4.1 pyasn1-0.4.4 pycparser-2.19 pytz-2018.7 six-1.11.0 xlrd-1.1.0 xlutils-2.0.0 xlwt-1.3.0
You are using pip version 9.0.1, however version 18.1 is available.
You should consider upgrading via the ‘pip install --upgrade pip‘ command.
[root@pythontest ~]#

3.
python -m pip download -r packages.txt


4.
pip install /root/package/six-1.11.0-py2.py3-none-any.whl

or
執行方法:
1.使用setuptools工具安裝xlrd模塊
1) 安裝setuptools工具
gunzip setuptools-2.0.tar.gz
tar -xvf setuptools-2.0.tar
python setup.py build
python setup.py install

2)安裝xlrd模塊
gunzip xlrd-1.1.0.tar.gz
tar -xvf xlrd-1.1.0.tar
python setup.py install

######################3

drwxr-xr-x. 4 root root 4096 12月 25 16:42 mysql_mon
[root@pythontest db_monitor-master]# python manage.py runserver
Performing system checks...

Unhandled exception in thread started by <function wrapper at 0x7fe0a234ab90>
Traceback (most recent call last):
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper
fn(*args, **kwargs)
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run
self.check(display_num_errors=True)
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/core/checks/model_checks.py", line 30, in check_all_models
errors.extend(model.check(**kwargs))
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/models/base.py", line 1284, in check
errors.extend(cls._check_fields(**kwargs))
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/models/base.py", line 1359, in _check_fields
errors.extend(field.check(**kwargs))
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 913, in check
errors = super(AutoField, self).check(**kwargs)
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 219, in check
errors.extend(self._check_backend_specific_checks(**kwargs))
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 322, in _check_backend_specific_checks
return connections[db].validation.check_field(self, **kwargs)
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/backends/mysql/validation.py", line 49, in check_field
field_type = field.db_type(self.connection)
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 644, in db_type
return connection.data_types[self.get_internal_type()] % data
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 174, in data_types
if self.features.supports_microsecond_precision:
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/backends/mysql/features.py", line 53, in supports_microsecond_precision
return self.connection.mysql_version >= (5, 6, 4) and Database.version_info >= (1, 2, 5)
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 385, in mysql_version
with self.temporary_connection() as cursor:
File "/root/.pyenv/versions/2.7.14/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/backends/base/base.py", line 591, in temporary_connection
cursor = self.cursor()
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/backends/base/base.py", line 254, in cursor
return self._cursor()
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/backends/base/base.py", line 229, in _cursor
self.ensure_connection()
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection
self.connect()
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection
self.connect()
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/backends/base/base.py", line 189, in connect
self.connection = self.get_new_connection(conn_params)
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 274, in get_new_connection
conn = Database.connect(**conn_params)
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/MySQLdb/__init__.py", line 85, in Connect
return Connection(*args, **kwargs)
File "/root/.pyenv/versions/2.7.14/lib/python2.7/site-packages/MySQLdb/connections.py", line 204, in __init__
super(Connection, self).__init__(*args, **kwargs2)
django.db.utils.OperationalError: (2002, "Can‘t connect to local MySQL server through socket ‘/tmp/mysql.sock‘ (2)")

解決辦法:


https://blog.csdn.net/chenguolinblog/article/details/19421909

vi 根目錄:setting.py
於是改成了以下的代碼就ok了,實際上就是localhost的問題,只要替換為127.0.0.1即可

然後新開一個窗口,重要
重新運行python manage.py runserver

#######

[root@pythontest check_alarm]# python main_check.py
2018-12-25 21:51:05,157 - main_check.py[line:793] - INFO: 清除osinfo表無效監控數據
mysql execute: (2003, "Can‘t connect to MySQL server on ‘192.168.48.50‘ (110)")
mysql execute: (2003, "Can‘t connect to MySQL server on ‘192.168.48.50‘ (110)")

另外check_alarm/config/db_monitor.conf 也要mysql server 地址也要改


##########
Traceback (most recent call last):
File "main_check.py", line 881, in <module>
alarm.alarm()
File "/app/python/project/db_monitor-master/check_alarm/alarm.py", line 189, in alarm
group by tags, host, port, service_name) t where cnt_all > %d ‘‘‘ %(tags,100,num_max)
UnboundLocalError: local variable ‘tags‘ referenced before assignment


解決方法:
copy windows main_check.py to linux .

###############
2018-12-25 22:18:40,537 - main_check.py[line:528] - ERROR: ora11g_test 數據庫連接失敗:DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so: cannot open shared object file: No such file or directory". See https://oracle.github.io/odpi/doc/installation.html#linux for help


解決方法
1.

find / -name libclntsh.so
/home/db/oracle/product/11.2.0/dbhome_1/lib/libclntsh.so


2.
export LD_LIBRARY_PATH=/home/db/oracle/product/11.2.0/dbhome_1/lib:$LD_LIBRARY_PATH
export ORACLE_HOME=/home/db/oracle/product/11.2.0/dbhome_1


###########

http://127.0.0.1:8000/admin

添加用戶和管理權限

###########1229

#######如何傳遞vies函數的變量到模板
https://code.ziqiangxuetang.com/django/django-template2.html


view function -> function.name.html view 中指定返回模板名字
在視圖中(views)我們傳遞了一個字符串名稱是 string 到模板 home.html,在模板中這樣使用它:

實例二,講解了基本的 for 循環 和 List內容的顯示

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 %}


2、model 中的queryset debug

https://code.ziqiangxuetang.com/django/django-queryset-advance.html

開始之前我們修改一個 settings.py 讓Django打印出在數據庫中執行的語句

settings.py 尾部加上

LOGGING = {
‘version‘: 1,
‘disable_existing_loggers‘: False,
‘handlers‘: {
‘console‘: {
‘class‘: ‘logging.StreamHandler‘,
},
},
‘loggers‘: {
‘django.db.backends‘: {
‘handlers‘: [‘console‘],
‘level‘: ‘DEBUG‘ if DEBUG else ‘INFO‘,
},
},
}

python manage.py shell

>>> from oracle_mon.models import TabOracleServers
>> TabOracleServers.objects.all().order_by(‘tags‘)
>> print str(TabOracleServers.objects.all().order_by(‘tags‘))

>>> for m in a:
... print (m.tags)
...

QuerySet 是可叠代的,比如:

es = Entry.objects.all()
for e in es:
print(e.headline)


############20181231

1.
Your models have changes that are not yet reflected in a migration, and so won‘t be applied.
Run ‘manage.py makemigrations‘ to make new migrations, and then re-run ‘manage.py migrate‘ to apply them.


python2 manage.py makemigrations
python2 manage.py migrate


check migration/db.log


2.
insert into check_list(check_tag,check_type,server_tag,begin_time,end_time) values(%s,%s,%s,%s,%s)"
value = (file_tag,‘Oracle數據庫‘,‘,‘.join(select_tags),begin_time,end_time)


mysql execute: (1364, "Field ‘id‘ doesn‘t have a default value")

solution:
https://blog.csdn.net/u012110719/article/details/41850587
AUTO_INCREMENT PRIMARY KEY,
ALTER TABLE `check_list` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT;

3.
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()


或者

https://www.cnblogs.com/os-python/p/6773499.html
想要解決問題就需要知道在mysql5.7中,啟用了嚴格模式:
在配置文件中 /etc/mysql/my.cnf 中找到:
sql-model=STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
修改為:sql-mode=NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
然後重啟mysql,在重新同步模型到數據庫

4.
URL ->view function -> function.name.html view 中指定返回模板名字


url(r‘^checklist_del/‘, frame.checklist_del),


add views.py
@login_required(login_url=‘/login‘)
def checklist_del(request):
check_tag = request.GET.get(‘check_tag‘)
print check_tag
models_frame.CheckList.objects.filter(check_tag=check_tag).delete()
return HttpResponseRedirect(‘/my_check/‘)

3.
pip download --only-binary=:all: --platform linux_x86_64 --python-version 27 --implementation cp -d D:\temp\zab pyenv

python django 基本測試 及調試 201812