用django建立測試用https伺服器(自我測試用)
用django建立測試用https伺服器(自我測試用)
由於之前已用djano建立過基本http server,這裡僅採補充說明改https server的方式,
參考:https://blog.csdn.net/yfj300/article/details/80597873
1. 安裝django額外套件
我是在virtualenv環境中安裝Django 1.8.19版本, 所以這裡也是在virtural安裝額外套件用參考資料會遭遇下面錯誤
File "env2.7.12/local/lib/python2.7/site-packages/django_extensions/management/commands/runserver_plus.py", line 223, in handle
self.inner_run(options)
File "local/lib/python2.7/site-packages/django_extensions/management/commands/runserver_plus.py", line 266, in inner_run
self.check_migrations()
AttributeError: 'Command' object has no attribute 'check_migrations'
django-extensions官方說新版已不支援1.8版Django
https://github.com/django-extensions/django-extensions/issues/1414
我搜尋到歷史可支援django的1.8版本之一並測試成功
pip install "django-extensions<1.2.5"
pip install django-werkzeug-debugger-runserver
pip install pyOpenSSL
上述指令最後安裝的模組版本:
django-extensions-1.2.4 six-1.14.0
Werkzeug-0.16.1 django-werkzeug-debugger-runserver-0.3.1
cffi-1.13.2 cryptography-2.8 enum34-1.1.6 ipaddress-1.0.23 pyOpenSSL-19.1.0 pycparser-2.19
2. 增加django模組
找出setting.py在INSTALLED_APPS列表加入'werkzeug_debugger_runserver','django_extensions',然後在最外層加入一個變數SECURE_SSL_REDIRECT = True
3. 幫自己產生SSL證書
使用上面參考資料中的指令會有錯誤訊息unable to load Private Key
140514287793816:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:701:Expecting: ANY PRIVATE KEY
所以參考另一篇產生SSL自我簽章的方法,可使用下面config檔案和指令
cat >ssl.conf<<EOF
[req]
prompt = no
default_md = sha256
default_bits = 2048
distinguished_name = dn
x509_extensions = v3_req
[dn]
C = TW
ST = Taiwan
L = Taipei
O = Example Inc.
OU = Example Dept.
emailAddress = admin@example.com
CN = localhost
[v3_req]
subjectAltName = @alt_names
[alt_names]
DNS.1 = *.localhost
DNS.2 = localhost
DNS.3 = 10.131.2.183
EOF
openssl req -newkey rsa:4096 \
-x509 \
-sha256 \
-days 3650 \
-nodes \
-out server.crt \
-keyout server.key \
-config ssl.conf
4. 啟動你的https伺服器
從原本python manage.py runserver 0.0.0.0:8080 --insecure
換成
python manage.py runserver_plus 0.0.0.0:8080 --insecure --cert server.crt
即可使用
測試方法wget
wget https://localhost:8080 -O - --no-check-certificate
如果沒有加入--no-check-certificate就會被檔連線
測試方法chrome
想要在chrome中測試此https server, 請先到chrome://flags/#allow-insecure-localhost中啟用存取不安全的localhost伺服器
參考資料: https://superuser.com/questions/772762
留言