目录
[一、安装 django-sslserver](#一、安装 django-sslserver)
[4.1 安装cryptography](#4.1 安装cryptography)
[4.2 生成证书代码](#4.2 生成证书代码)
[4.3 将生成的证书放到django项目根目录下](#4.3 将生成的证书放到django项目根目录下)
[5.1 本地测试启动](#5.1 本地测试启动)
[5.2 生产启动](#5.2 生产启动)
前言:django接口采取https访问,以及安全证书ssl
一、安装 django-sslserver
pip install django-sslserver
二、配置settings
SECURE_SSL_REDIRECT = False
INSTALLED_APPS = [
'sslserver'
]
三、启动项目测试
python manage.py runsslserver
四、使用ssl证书
4.1 安装cryptography
pip install cryptography
4.2 生成证书代码
# -*- coding: utf-8 -*-
# @Time : 2024/9/29 13:31
# @Author : super
# @File : httpsSsl.py
# @Software: PyCharm
# @Describe:生成ssl证书
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
from datetime import datetime, timedelta
def generate_rsa_private_key(bits=2048):
"""生成RSA私钥"""
return rsa.generate_private_key(
public_exponent=65537,
key_size=bits,
backend=default_backend()
)
def generate_self_signed_cert(private_key, subject, validity_days=365):
"""生成自签名证书"""
# 有效期
now = datetime.utcnow()
cert_not_valid_before = now
cert_not_valid_after = now + timedelta(days=validity_days)
# 创建证书签名请求(CSR)
subject_alternative_name = x509.SubjectAlternativeName([
# 你可以根据需要添加其他名称,比如IP地址
x509.DNSName(subject)
])
# 创建证书
cert = (
x509.CertificateBuilder()
.subject_name(x509.Name([
# 你可以根据需要添加更多的字段
x509.NameAttribute(NameOID.COMMON_NAME, subject),
]))
.issuer_name(x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, subject),
]))
.public_key(private_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(cert_not_valid_before)
.not_valid_after(cert_not_valid_after)
.add_extension(
x509.SubjectAlternativeName(subject_alternative_name),
critical=False,
)
.sign(private_key, hashes.SHA256(), default_backend())
)
# 返回PEM格式的证书和私钥
return (
cert.public_bytes(serialization.Encoding.PEM),
private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
)
if __name__ == '__main__':
# 使用函数
private_key = generate_rsa_private_key()
cert_pem, private_key_pem = generate_self_signed_cert(private_key, "localhost")
# 打印证书和私钥(通常你会将它们保存到文件中)
print("Certificate:")
print(cert_pem.decode())
print("Private Key:")
print(private_key_pem.decode())
# 导出证书和私钥到文件
with open('./certificate.pem', 'wb') as f:
f.write(cert_pem)
with open('./private_key.pem', 'wb') as f:
f.write(private_key_pem)
print("证书和私钥已保存到当前目录。")
4.3 将生成的证书放到django项目根目录下
略
五、使用证书启动项目
下面的路径自己调整一下
5.1 本地测试启动
python manage.py runsslserver --certificate certificate.pem --key private_key.pem
5.2 生产启动
python manage.py runsslserver --certificate /path/to/your/certificate.pem --key /path/to/your/private_key.pem 0.0.0.0:8000
六、生成docker镜像的dockerfile
FROM python:3.8.10
WORKDIR /app
COPY . /app
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone \
&& python -m pip install --upgrade pip -i https://pypi.tuna.tsinghua.edu.cn/simple \
&& pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
# 暴露端口
EXPOSE 8000
CMD ["python", "manage.py", "runsslserver", "0.0.0.0:8000", "--certificate", "certificate.pem", "--key", "private_key.pem"]
七、构建服务
到对应文件目录下
docker build -t my-django-app .
八、启动服务
docker run -d --name myappname --restart=always -p 8000:8000 my-django-app
# 指定宿主机(我使用的是这个)
docker run -d --name dora --restart=always -p 8000:8000 -v /opt/myapp/dora/djangoMarketBacken:/app my-django-app
九、修改settings
DEBUG = False
ALLOWED_HOSTS = ['*']