内容字号:默认大号超大号

段落设置:段首缩进取消段首缩进

字体设置:切换到微软雅黑切换到宋体

最简单的Django项目(单文件)

2018-02-13 14:48 出处:清屏网 人气: 评论(0

前面的Django官方教程中学习到了使用 django - admin startproject mysite 生成项目的方法。为了对Django有更加深入的理解,今天来一起研究下如何手动生成一个Django项目,为了使项目看起来简单,手动生成的时候要把所有代码整合进一个文件中。

新建空白文件

空白文件命名为:project_name.py。

加入入口文件namage.py中的代码

import os
import sys
 
if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

以上代码是使用指令生成的,为了放进单文件,我们做如下优化:

  • 去除了是否安装Django环境的异常处理
  • 去除引入mysite.settings

将mysite.settings的内容直接加入单文件中

需要注意的事,mysite.settings包含的设置项非常的多,由于只是做学习,可以先将一些暂时用不到的设置全部删除。

"""
Django settings for mysite project.
 
Generated by 'django-admin startproject' using Django 2.0.1.
 
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
 
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
 
import os
 
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 
 
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
 
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'a()izd2o4^lj^6%w%9g7(^(1r4^o6(glwb8ks7)s8c8p6$p+$n'
 
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
 
ALLOWED_HOSTS = []
 
 
# Application definition
 
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 = 'mysite.urls'
 
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'mysite.wsgi.application'
 
 
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
 
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}
 
 
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
 
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',
    },
]
 
 
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
 
LANGUAGE_CODE = 'en-us'
 
TIME_ZONE = 'UTC'
 
USE_I18N = True
 
USE_L10N = True
 
USE_TZ = True
 
 
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
 
STATIC_URL = '/static/'

我们需要做的修改:

  • 载入from django.conf import settings
  • 使用settings.configuree()方法进行配置项设置
  • 去除暂时不用的配置项目(后期用到时再添加)
  • 将ROOT_URLCONF设置为当前文件,并将URL规则拷入到当前文件
  • 去除WSGI_APPLICATION配置项目,并将wsgi的内容引入进来
import sys
from django.conf import settings
 
settings.configure(
    DEBUG = True,
    ROOT_URLCONF = __name__,
)
 
from django.contrib import admin
from django.urls import path
 
urlpatterns = [
    path('admin/', admin.site.urls),
]
 
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
 
if __name__ == "__main__":
    from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)

修改url路由规则,并建立视图

  • 去除admin模块(这里用不到)
  • 新建index视图(需要注意视图要放在url路由规则上方,否则会报错)
  • 建立url规则与index视图的联系
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import sys
from django.conf import settings
 
settings.configure(
    DEBUG = True,
    ROOT_URLCONF = __name__,
)
 
from django.urls import path
from django.http import HttpResponse
 
def index(request):
    return HttpResponse("Hello World!")
 
urlpatterns = [
    path('index', index),
]
 
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
 
if __name__ == "__main__":
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

至此,一个最简单的Django项目生成了,运行 python project_name . py runserver 可看到执行效果。

把单文件作为模版来使用

上面完成的单文件,可以作为生成Django的模版使用,只需要在原先的指令后面加上–template=project_name即可。比如:

django-admin startproject mysite --template=project_name

注意,执行上面的生成指令要在project_name所在目录才行。

分享给小伙伴们:
本文标签: Django

相关文章

发表评论愿您的每句评论,都能给大家的生活添色彩,带来共鸣,带来思索,带来快乐。

CopyRight © 2015-2016 QingPingShan.com , All Rights Reserved.

清屏网 版权所有 豫ICP备15026204号