作者 张志平

first

FROM python:3.6.3
# 设置工作目录
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# 添加依赖(利用Docker 的缓存)
ADD ./requirements.txt /usr/src/app/requirements.txt
# 安装依赖
RUN pip install -r requirements.txt
# 添加应用
ADD . /usr/src/app
# 运行服务
CMD python manage.py runserver 0.0.0.0:8000
... ...
不能预览此文件类型
不能预览此文件类型
不能预览此文件类型
不能预览此文件类型
不能预览此文件类型
from django.contrib import admin
# Register your models here.
... ...
from django.apps import AppConfig
class BlogConfig(AppConfig):
name = 'blog'
... ...
from django import forms as dforms
from django.forms import fields
class UserForm(dforms.Form):
username = fields.CharField()
email = fields.EmailField()
... ...
# Generated by Django 2.0 on 2018-05-29 10:14
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='UserInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('username', models.CharField(max_length=32)),
('email', models.EmailField(max_length=32)),
],
),
]
... ...
from django.db import models
class UserInfo(models.Model):
username = models.CharField(max_length=32)
email = models.EmailField(max_length=32)
def __str__(self):
return self.username
# Create your models here.
... ...
from django.test import TestCase
# Create your tests here.
... ...
from django.shortcuts import render
from django.shortcuts import redirect
from . import models
from .form import *
def users(request):
user_list = models.UserInfo.objects.all()
return render(request, 'users.html', {'user_list': user_list})
def add_user(request):
if request.method == 'GET':
obj = UserForm()
return render(request, 'add_user.html', {'obj': obj})
else:
obj = UserForm(request.POST)
if obj.is_valid():
models.UserInfo.objects.create(**obj.cleaned_data)
return redirect('/users/')
else:
return render(request, 'add_user.html', {'obj': obj})
def edit_user(request, nid):
if request.method == "GET":
data = models.UserInfo.objects.filter(id=nid).first()
obj = UserForm({'username': data.username, 'email': data.email})
return render(request, 'edit_user.html', {'obj': obj, 'nid': nid})
else:
obj = UserForm(request.POST)
if obj.is_valid():
models.UserInfo.objects.filter(id=nid).update(**obj.cleaned_data)
return redirect('/users/')
else:
return render(request, 'edit_user.html', {'obj': obj, 'nid': nid})
... ...
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mytest.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)
... ...
import pymysql
pymysql.install_as_MySQLdb()
... ...
不能预览此文件类型
不能预览此文件类型
"""
Django settings for mytest project.
Generated by 'django-admin startproject' using Django 2.0.
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 = '5ap(3kvz-e5@@pm(6l^s66#=+tba-(c0md(9u4+jth98hahid9'
# 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',
'blog',
]
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 = 'mytest.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 = 'mytest.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mytest',
'USER': 'root',
'PASSWORD': 'root@2013',
'HOST': os.environ.get('MYSQL_SERVICE_HOST'),
'PORT': 3306,
}
}
# 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/'
... ...
"""mytest URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.users, name='users'),
path('users/', views.users, name='users'),
path('add_user/', views.add_user),
path('edit_user/<int:nid>/', views.edit_user,name='edit_user'),
]
... ...
"""
WSGI config for mytest project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mytest.settings")
application = get_wsgi_application()
... ...
Django==2.0
PyMySQL==0.8.0
... ...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/add_user/" method="post" novalidate>
{% csrf_token %}
<p>{{ obj.username }}{{ obj.errors.username.0 }}</p>
<p>{{ obj.email }}{{ obj.errors.email.0 }}</p>
<input type="submit" value="提交" />
</form>
</body>
</html>
... ...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/edit_user/{{ nid }}/" method="post" novalidate>
{% csrf_token %}
<p>{{ obj.username }}{{ obj.errors.username.0 }}</p>
<p>{{ obj.email }}{{ obj.errors.email.0 }}</p>
<input type="submit" value="提交" />
</form>
</body>
</html>
... ...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
</head>
<body>
<a class="btn btn-primary" id="addBtn" href="/add_user/">添加</a>
<a class="btn btn-primary" id="cancel" href="/get_classes.html">跳转</a>
<ul>
{% for row in user_list %}
<li>{{ row.id }}-{{ row.username }}-{{ row.email }} <a class="btn btn-warning" href="/edit_user/{{ row.id }}/">编辑</a></li>
{% endfor %}
</ul>
</body>
</html>
... ...