使用CodeStar开发Django(Python3.8、Django2.1.15)

创建一个新项目

我们将选择Python(Django)作为CodeStar的编程语言,并创建项目。我们将使用CodeCommit作为代码仓库。

image.png

当CodeStar的仪表盘显示出来并准备好之后,您可以通过应用程序的端点查看Django的页面。

image.png
image.png
image.png

编辑项目

只需要一个选项:
我们将使用Anaconda建立Python3.8的环境。

$ conda create -n py38 python=3.8
$ conda activate py38

从CodeCommit复制URL,使用git进行克隆。

$ git clone https://username:password@git-codecommit.ap-northeast-1.amazonaws.com/v1/repos/gachimoto-gtfs
$ cd gachimoto-gtfs

安装所需的库。

$ pip install -r requirements.txt

添加.gitignore文件。

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# dotenv
.env

# virtualenv
.venv
venv/
ENV/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/


.idea/
db.sqlite3
migrations/

编辑buildspec.yml的一部分。

commands:
  # Install dependencies needed for running tests
  - pip install -r requirements/common.txt
 - python manage.py makemigrations helloworld
 - python manage.py migrate
 - python manage.py collectstatic --noinput

安装外部库(例如:requests) 之后。

$ pip install requests

我也会编辑common.txt。

# dependencies common to all environments
Django==2.1.15
requests==2.22.0

创建第一个页面

你只需要提供一个选项,用中文将以下内容翻译成自然语言:helloworld/views.py。

# helloworld/views.py
from django.shortcuts import render
from django.views import generic
from django.views.generic import TemplateView
from django.views.generic import ListView

class Top(generic.TemplateView):
    template_name = 'top.html'

helloworld/urls.py的内容请进行释义。

# helloworld/urls.py
from django.urls import path
from django.conf.urls import url
from django.conf.urls.static import static
from helloworld import views

urlpatterns = [
    # url(r'^$', views.HomePageView.as_view()),
    path('', views.Top.as_view(), name='top'),
]

你好世界/测试.py

from django.test import TestCase, RequestFactory

你好世界/模板/顶部.html

{% extends "base.html" %}
{% block content %}
<p> gachimoto-gtfsへようこそ </p>
{% endblock %}

helloworld/templates/base.html可以以以下一种方式进行中文重述:

helloworld/templates/base.html的底层模板。

<!doctype html>
{% load staticfiles %}
<html lang="ja">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"
          integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
    <title>gachimoto gtfs api</title>
  </head>
  <body>
    <!-- ナビバー -->
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <a class="navbar-brand" href="{% url 'top' %}">G</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
        </ul>
      </div>
    </nav>

    <!-- メインコンテント -->
    <div class="container mt-3">
      {% block content %}{% endblock %}
    </div>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
            integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
            crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"
            integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ"
            crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"
            integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm"
            crossorigin="anonymous"></script>
  </body>
</html>

ec2django/urls.py 的中文释义:

""" ec2django URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('helloworld.urls')),
]

ec2django的设置文件settings.py

"""
Django settings for ec2django project.

Generated by 'django-admin startproject' using Django 2.1.14.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/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.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'CHANGE_ME' # 適当に変てね

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True # bool( os.environ.get('DJANGO_DEBUG', False) )

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'helloworld.apps.HelloworldConfig', # 'helloworld',
]

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 = 'ec2django.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 = 'ec2django.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/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.1/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.1/topics/i18n/

LANGUAGE_CODE = 'ja' # 'en-us'

TIME_ZONE = 'Asia/Tokyo' # 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = 'static'

项目部署

我会检查页面。

$ python manage.py migrate
$ python manage.py runserver
image.png

创建并提交feature分支。

$ git branch feature 
$ git checkout feature
$ git status 
$ git add .
$ git commit -m "最初のページ"
$ git push origin feature
image.png
image.png
image.png
image.png

我們將從”develop”分支合併到”master”分支。然後CodePipline會啟動並自動進行部署。

image.png
image.png
image.png

在EC2重新启动时,进行设置以启动Django。

辛苦了。现在可以轻松地创建Django应用程序了!

追加

静态文件的加载和生产环境配置(Debug=False)

收集静态文件。

$ python manage.py collectstatic --noinput
$ python manage.py runserver

设置.py

将DEBUG模式设为False。

DEBUG = False

urls.py -> 网址.py

添加静态文件夹设置。

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('helloworld.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

添加图像

将任意的图像添加到helloworld/static/helloworld/img/和static/helloworld/img/。如果添加了css等文件,请确保统一将它们放置在static文件夹下。在DEBUG=False时可能无法正确加载。

示例图片(base.html)

<a class="navbar-brand" href="{% url 'top' %}"><img src="{% static 'helloworld/img/G.svg' %}" width="11%" /></a>
广告
将在 10 秒后关闭
bannerAds