django搭建博客之初始化工程

django搭建博客之初始化工程,第1张

项目初始化

初始化django空项目可以基于命令行创建或者是pycharm创建,我这里就通过pycharm来创建了

打开pycharm,选择File->New Project,如下图:

点击create之后等待项目创建完毕。创建完毕之后此时我们的根目录结构如下图

E:\myblog
│  manage.py                         
│          
├─media
├─myblog
│  │  asgi.py
│  │  settings.py
│  │  urls.py
│  │  wsgi.py
│  │  __init__.py
├─templates

新建\myblog\db.sqlite3,\myblog\static,\myblog\media,\myblog\build\requirements\

文件或者文件夹解释
db.sqlite3本地开发数据库
static静态资源目
media媒体资源目录
build镜像构建目录
requirements不同环境的安装依赖目录

如果当前目录下如果已经有了这些文件或者文件夹,则不需要重复创建。

项目基本依赖

新建\myblog\myblog\base.txt

添加以下内容

django
celery[redis,django]
django-haystack
django-simple-captcha
jieba
pyparsing
pysolr
requests
Whoosh
django-celery-beat
django-celery-results
django-redis
psycopg2-binary
django-simpleui
django-meditor
项目开发依赖

新建\myblog\myblog\dev.txt

添加以下内容

-r base.txt
eventlet
django-debug-toolbar
项目生产依赖

新建\myblog\myblog\prod.txt

添加以下内容

-r base.txt
gunicorn

其中base.txt则是开发环境和生成环境公共的依赖,dev.txt则是开发环境下要安装的依赖,prod则是生成环境下要安装的依赖。

然后按照下图

执行以下命令

pip install -r build/requirements/dev.txt
项目开发配置

新建\myblog\myblog\dev_settings.py

添加以下内容

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, "db.sqlite3"),
    }
}

REDIS_CONF = {
    "host": "127.0.0.1",
    "port": "6379"
}
REDIS_URL = f'redis://{REDIS_CONF["host"]}:{REDIS_CONF["port"]}'

DEBUG = True

ALLOWED_HOSTS = []

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

# 开发地址
SITE_URL = 'http://127.0.0.1:8000'

# 开发环境下邮件发送到控制台
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
项目生产配置

新建\myblog\myblog\prod_settings.py

添加以下内容

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'HOST': os.getenv("POSTGRES_HOST", "app-postgres"),
        'PORT': os.getenv("POSTGRES_PORT", "5432"),
        'NAME': os.getenv("POSTGRES_DB"),
        'USER': os.getenv("POSTGRES_USER"),
        'PASSWORD': os.getenv("POSTGRES_PASSWORD")
    }
}

REDIS_CONF = {
    "host": os.getenv("REDIS_HOST", "app-redis"),
    "port": os.getenv("REDIS_PORT", "6379")
}
REDIS_URL = f'redis://{REDIS_CONF["host"]}:{REDIS_CONF["port"]}'

CACHES = {
    "default": {
        "VERSION": 1,
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": f"{REDIS_URL}/0",
    }
}

DEBUG = False

ALLOWED_HOSTS = ['*']

# 这里替换成你上线后的域名或者服务器公网IP
SITE_URL = 'https://oneisall.top'

# 生产环境下真实发送邮件
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
项目配置

编辑myblog\myblog\settings.py

添加以下内容

from pathlib import Path
import os

env = os.getenv("APP_ENV", "dev")

if env == "prod":
    from .prod_settings import *
elif env == "dev":
    from .dev_settings import *

BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'django-insecure-!5)rlq06fcxq*h9ry#o7)(e&@^nyv1xr%nqbt7lwr5z#k053'

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'myblog.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
WSGI_APPLICATION = 'myblog.wsgi.application'
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

此时我们的项目目录结构如下

E:\myblog
│  db.sqlite3
│  dir.txt
│  manage.py
│                          
├─build
│  └─requirements
│          base.txt
│          dev.txt
│          prod.txt
│          
├─media
├─myblog
│  │  asgi.py
│  │  dev_settings.py
│  │  prod_settings.py
│  │  settings.py
│  │  urls.py
│  │  wsgi.py
│  │  __init__.py
│          
├─static
├─templates

运行django项目,访问http://127.0.0.1:8000/,出现下图说明代码没有问题

配置django-debug-toolbar

编辑\myblog\urls.py文件

追加以下内容

if settings.DEBUG:
    import debug_toolbar

    urlpatterns = urlpatterns + [path('__debug__/', include(debug_toolbar.urls))]

编辑\myblog\myblog\settings.py末尾

追加以下内容

if env == "dev":
    INSTALLED_APPS.append('debug_toolbar')
    MIDDLEWARE.append('debug_toolbar.middleware.DebugToolbarMiddleware')
    INTERNAL_IPS = ['127.0.0.1']

再次访问如下图表示ok

邮件配置

新建\myblog\myblog\email_settings.py

添加以下内容

from django.conf import settings

EMAIL_HOST = "你的邮件服务器HOST"
EMAIL_PORT = 25 if settings.DEBUG else 465
EMAIL_HOST_TLS = True if settings.DEBUG else False
EMAIL_USE_SSL = False if settings.DEBUG else True
EMAIL_HOST_USER = "用户名"
EMAIL_HOST_PASSWORD = "密码"
EMAIL_FROM = "你的邮件地址"
DEFAULT_FROM_EMAIL = '用户收到邮件显示的邮箱'

编辑myblog\myblog\settings.py

追加以下内容

from myblog.email_settings import *
静态文件和媒体文件配置

编辑\myblog\urls.py文件

追加以下内容

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
else:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

编辑\myblog\myblog\settings.py

修改TEMPLATES,增加media上下文处理器,这样才可以在模板里面使用MEDIA_URL

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                # 把media全局注册进template模板中
                'django.template.context_processors.media',
            ],
        },
    },
]
celery配置

新增\myblog\myblog\celery.py

添加以下内容

from celery import Celery
import os
from django.utils import timezone

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myblog.settings')
app = Celery('myblog')
app.now = timezone.now
# 命名空间 namespace='CELERY'定义所有与celery相关的配置的键名要以'CELERY_'为前缀。
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

新增\myblog\myblog\celery_settings.py

内容如下

from django.conf import settings

CELERY_TIMEZONE = settings.TIME_ZONE
CELERY_ENABLE_UTC = True  # 不使用UTC时区
CELERY_BROKER_URL = f"{settings.REDIS_URL}/1"
CELERY_RESULT_BACKEND = 'django_celery_results.backends.database.DatabaseBackend'  # 存储任务结果
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['json']
DJANGO_CELERY_RESULTS_TASK_ID_MAX_LENGTH = 191
DJANGO_CELERY_RESULTS = {
    'ALLOW_EDITS': False
}

编辑\myblog\myblog\settings.py

追加以下内容

from myblog.celery_settings import *

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/716769.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存