Quellcode durchsuchen

初始仓库。

Gfei vor 4 Jahren
Commit
9d6f83aa41

+ 63 - 0
.gitignore

@@ -0,0 +1,63 @@
+# ---> Python
+# 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/
+*.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
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+
+# Pycharm
+**/.idea
+

+ 29 - 0
TkMoldingServer/Dockerfile

@@ -0,0 +1,29 @@
+FROM python:3.6
+RUN mkdir -p /usr/src/app
+WORKDIR /usr/src/app
+# COPY pip.conf /root/.pip/pip.conf
+COPY requirements.txt /usr/src/app/
+RUN pip install -r /usr/src/app/requirements.txt
+RUN rm -rf /usr/src/app
+RUN apt-get update && \
+    apt-get install -y --no-install-recommends \
+    cron tzdata locales && \
+    rm -rf /var/lib/apt/lists/* && \
+    apt-get clean
+COPY . /usr/src/app
+
+#CMD ["python", "./manage.py", "runserver", "0.0.0.0:8080"]
+# 解决中文乱码问题
+#RUN locale-gen en_US.UTF-8
+# 时区为上海
+ENV TZ Asia/Shanghai
+ENV LANG en_US.UTF-8
+ENV LANGUAGE en_US:en
+ENV LC_ALL en_US.UTF-8
+
+EXPOSE 8080
+# 添加启动脚本
+ADD entry.sh .
+RUN chmod 755 entry.sh
+RUN sed -i "s/\r//" entry.sh
+ENTRYPOINT [ "./entry.sh"]

+ 0 - 0
TkMoldingServer/TkMoldingServer/__init__.py


+ 190 - 0
TkMoldingServer/TkMoldingServer/settings.py

@@ -0,0 +1,190 @@
+"""
+Django settings for TkMoldingServer project.
+
+Generated by 'django-admin startproject' using Django 2.2.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/2.2/topics/settings/
+
+For the full list of settings and their values, see
+https://docs.djangoproject.com/en/2.2/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.2/howto/deployment/checklist/
+
+# SECURITY WARNING: keep the secret key used in production secret!
+SECRET_KEY = '(_g3+3n*140t!k&g1drctb19=%8_hq-r$18pub-d-vtyl=89t)'
+
+# SECURITY WARNING: don't run with debug turned on in production!
+DEBUG = False
+
+ALLOWED_HOSTS = ['*']
+
+
+# Application definition
+
+INSTALLED_APPS = [
+    'django_crontab',
+    'tkschedule.apps.ScheduleConfig',
+    '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 = 'TkMoldingServer.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 = 'TkMoldingServer.wsgi.application'
+
+
+# Database
+# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
+
+DATABASES = {
+    'default': {
+        'ENGINE': 'django.db.backends.mysql',
+        'NAME': 'moldingdatabase',
+        'USER': 'hsmolding',
+        'PASSWORD': '87543492',
+        'HOST': '120.24.182.114',
+        'PORT': '3306',
+    },
+}
+
+
+# Password validation
+# https://docs.djangoproject.com/en/2.2/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.2/topics/i18n/
+
+LANGUAGE_CODE = 'zh-hans'
+
+TIME_ZONE = 'Asia/Shanghai'
+
+USE_I18N = True
+
+USE_L10N = True
+
+USE_TZ = True
+
+
+# Static files (CSS, JavaScript, Images)
+# https://docs.djangoproject.com/en/2.2/howto/static-files/
+
+STATIC_URL = '/static/'
+
+# 日志文件存放路径
+BASE_LOG_DIR = os.path.join(BASE_DIR, "logs")
+# Logging配置
+LOGGING = {
+    'version': 1.0,  # 保留字
+    'disable_existing_loggers': False,  # 是否禁用Django框架开发的时候已经存在的Logger实例
+    'formatters': {  # 格式化器
+        'standard': {  # 标准的格式
+            'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'
+                      '[%(levelname)s][%(message)s]'
+        },
+        'simple': {  # 简单的格式
+            'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
+        }
+    },
+    'filters': {  # 过滤器
+        'require_debug_true': {
+            '()': 'django.utils.log.RequireDebugTrue',
+        },
+    },
+    'handlers': {  # 处理器
+        'console': {  # 定义一个在终端输出的处理器
+            'level': 'DEBUG',  # 日志级别
+            'filters': ['require_debug_true'],  # 只有在Django debug为True时才在屏幕打印日志
+            'class': 'logging.StreamHandler',  # 日志流
+            'formatter': 'simple'  # 用简单格式打印日志
+        },
+        'info': {  # 定义一个名为SF的日志处理器(名字自己定义即可)
+            'level': 'INFO',  # 日志级别
+            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,根据文件大小自动切
+            'filename': os.path.join(BASE_LOG_DIR, "serverinfo.log"),  # 日志文件
+            'maxBytes': 1024 * 1024 * 20,  # 日志大小 50M
+            'backupCount': 3,  # 备份数为3  xx.log --> xx.log.1 --> xx.log.2 --> xx.log.3
+            'formatter': 'standard',  # 用标准格式打印日志
+            'encoding': 'utf-8',
+        },
+        'warning': {
+            'level': 'WARNING',
+            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自动切
+            'filename': os.path.join(BASE_LOG_DIR, "serverwarning.log"),  # 日志文件
+            'maxBytes': 1024 * 1024 * 20,  # 日志大小 50M
+            'backupCount': 3,
+            'formatter': 'standard',
+            'encoding': 'utf-8',
+        },
+    },
+    'loggers': {
+        'django': {  # 日志实例对象默认配置
+            'handlers': ['warning'],  # 使用哪几种处理器,上线之后可以把'console'移除
+            'level': 'DEBUG',  # 实例的级别
+            'propagate': True,  # 是否向上传递日志流
+        },
+        'tkschedule.views': {  # logger对象实例还单独处理
+            'handlers': ['info'],
+            'level': 'INFO',
+        }
+    },
+}
+
+CRONJOBS = [
+('50 8 * * *', 'tkschedule.tasks.testEmail'),
+]
+

+ 22 - 0
TkMoldingServer/TkMoldingServer/urls.py

@@ -0,0 +1,22 @@
+"""TkMoldingServer URL Configuration
+
+The `urlpatterns` list routes URLs to views. For more information please see:
+    https://docs.djangoproject.com/en/2.2/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, include
+
+urlpatterns = [
+    path('tkschedule/', include('tkschedule.urls')),
+    path('admin/', admin.site.urls),
+]

+ 16 - 0
TkMoldingServer/TkMoldingServer/wsgi.py

@@ -0,0 +1,16 @@
+"""
+WSGI config for TkMoldingServer 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.2/howto/deployment/wsgi/
+"""
+
+import os
+
+from django.core.wsgi import get_wsgi_application
+
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TkMoldingServer.settings')
+
+application = get_wsgi_application()

+ 13 - 0
TkMoldingServer/entry.sh

@@ -0,0 +1,13 @@
+#!/bin/bash
+set -x
+
+# 保存环境变量,开启crontab服务
+env >> /etc/default/locale
+# 启动任务计划
+/usr/sbin/cron
+
+# 最后一行增加任务计划
+python manage.py crontab add
+# 启动django项目
+
+python manage.py runserver 0.0.0.0:8080

+ 21 - 0
TkMoldingServer/manage.py

@@ -0,0 +1,21 @@
+#!/usr/bin/env python
+"""Django's command-line utility for administrative tasks."""
+import os
+import sys
+
+
+def main():
+    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TkMoldingServer.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)
+
+
+if __name__ == '__main__':
+    main()

+ 64 - 0
TkMoldingServer/requirements.txt

@@ -0,0 +1,64 @@
+alabaster==0.7.12
+amqp==2.5.2
+Babel==2.8.0
+billiard==3.6.2.0
+celery==4.4.0
+certifi==2019.9.11
+chardet==3.0.4
+colorama==0.4.3
+coreapi==2.3.3
+coreschema==0.0.4
+Django==2.2
+django-celery-results==1.2.0
+django-crontab==0.7.1
+django-filter==2.2.0
+django-redis==4.11.0
+django-redis-cache==2.1.0
+djangorestframework==3.10.3
+dnspython==1.16.0
+docutils==0.16
+drf-yasg==1.17.0
+eventlet==0.25.1
+greenlet==0.4.15
+idna==2.8
+imagesize==1.2.0
+importlib-metadata==1.5.0
+inflection==0.3.1
+itypes==1.1.0
+Jinja2==2.11.1
+joblib==0.14.1
+kombu==4.6.7
+MarkupSafe==1.1.1
+monotonic==1.5
+mysqlclient==1.4.6
+numpy==1.18.2
+packaging==20.1
+pandas==1.0.3
+Pygments==2.5.2
+PyMySQL==0.9.3
+pyparsing==2.4.6
+python-dateutil==2.8.1
+pytz==2019.3
+redis==3.4.1
+requests==2.22.0
+ruamel.yaml==0.16.9
+ruamel.yaml.clib==0.2.0
+schedule==0.6.0
+scikit-learn==0.22.2.post1
+scipy==1.4.1
+six==1.14.0
+sklearn==0.0
+snowballstemmer==2.0.0
+Sphinx==2.4.1
+sphinxcontrib-applehelp==1.0.1
+sphinxcontrib-devhelp==1.0.1
+sphinxcontrib-htmlhelp==1.0.2
+sphinxcontrib-jsmath==1.0.1
+sphinxcontrib-qthelp==1.0.2
+sphinxcontrib-serializinghtml==1.1.3
+sqlparse==0.3.0
+uritemplate==3.0.1
+urllib3==1.25.8
+vine==1.3.0
+wincertstore==0.2
+zipp==2.2.0

+ 0 - 0
TkMoldingServer/tkschedule/__init__.py


+ 3 - 0
TkMoldingServer/tkschedule/admin.py

@@ -0,0 +1,3 @@
+from django.contrib import admin
+
+# Register your models here.

+ 5 - 0
TkMoldingServer/tkschedule/apps.py

@@ -0,0 +1,5 @@
+from django.apps import AppConfig
+
+
+class ScheduleConfig(AppConfig):
+    name = 'tkschedule'

+ 160 - 0
TkMoldingServer/tkschedule/emails.py

@@ -0,0 +1,160 @@
+import mimetypes
+import os
+import smtplib
+import time
+from email import encoders
+from email.header import Header
+from email.mime.base import MIMEBase
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+from email.utils import parseaddr, formataddr
+from os.path import getsize
+
+
+class EmailManager(object):
+
+    _instance = None
+
+    def __new__(cls, **kwargs):
+        if not cls._instance:
+            cls._instance = super().__new__(cls)
+        return cls._instance
+
+    def __init__(self, **kwargs):
+        '''
+        constructor
+        :param kwargs:Variable paramete
+        '''
+        self.kwargs = kwargs
+        self.smtp_server = 'smtp.qq.com'
+        self.MAX_FILE_SIZE = 10 * 1024 * 1024
+
+        # initialize the configuration file
+        self.__init_cfg()
+
+    def __get_cfg(self, key, throw=True):
+        '''
+        get the configuration file based on the key
+        :param key:
+        :param throw:
+        :return:
+        '''
+        cfg = self.kwargs.get(key)
+        if throw == True and (cfg is None or cfg == ''):
+            raise Exception("The configuration can't be empty", 'utf-8')
+        return cfg
+
+    def __init_cfg(self):
+        self.msg_from = self.__get_cfg('msg_from')
+        self.password = self.__get_cfg('password')
+        self.msg_to = ';'.join(self.__get_cfg('msg_to'))
+        self.msg_subject = self.__get_cfg('msg_subject')
+        self.msg_content = self.__get_cfg('msg_content')
+        self.msg_date = self.__get_cfg('msg_date')
+        # attachment
+        self.attach_file = self.__get_cfg('attach_file', throw=False)
+
+    def login_server(self):
+        '''
+        login server
+        :return:
+        '''
+        server = smtplib.SMTP_SSL(self.smtp_server, 465)
+        server.set_debuglevel(1)
+        server.login(self.msg_from, self.password)
+        return server
+
+    def get_main_msg(self):
+        '''
+        suject content
+        :return:msg
+        '''
+        msg = MIMEMultipart()
+        # message content
+        msg.attach(MIMEText(self.msg_content, 'plain', 'utf-8'))
+
+        msg['From'] = self._format_addr('From <%s>' % self.msg_from)
+        msg['To'] = self._format_addr('To <%s>' % self.msg_to)
+        msg['Subject'] = Header(self.msg_subject, 'utf-8')
+        msg['Date'] = self.msg_date
+
+        # attachment content
+        attach_file = self.get_attach_file()
+        if attach_file is not None:
+            msg.attach(attach_file)
+        return msg
+
+    def get_attach_file(self):
+        '''
+        generate mail attachment content
+        :return:
+        '''
+        if self.attach_file is not None and self.attach_file != '':
+            try:
+                if getsize(self.attach_file) > self.MAX_FILE_SIZE:
+                    raise Exception('The attachment is too large and the upload failed!!')
+                with open(self.attach_file, 'rb') as file:
+                    ctype, encoding = mimetypes.guess_type(self.attach_file)
+                    if ctype is None or encoding is not None:
+                        ctype = 'application/octet-stream'
+                    maintype, subtype = ctype.split('/', 1)
+                    mime = MIMEBase(maintype, subtype)
+                    mime.set_payload(file.read())
+                    # set header
+                    mime.add_header('Content-Disposition', 'attachment',
+                                    filename=os.path.basename(self.attach_file))
+                    mime.add_header('Content-ID', '<0>')
+                    mime.add_header('X-Attachment-Id', '0')
+                    # set the attachment encoding rules
+                    encoders.encode_base64(mime)
+                    return mime
+            except Exception as e:
+                print('%s......' % e)
+                return None
+        else:
+            return None
+
+    def _format_addr(self, s):
+        name, addr = parseaddr(s)
+        return formataddr((Header(name, 'utf-8').encode(), addr))
+
+    def set_msg_content(self, content):
+        self.msg_content = content
+
+    def set_msg_to(self, tolist):
+        self.msg_to = tolist
+
+    def send(self):
+        try:
+            # initialize the configuration file
+            # self.__init_cfg()
+            # log on to the SMTP server and verify authorization
+            server = self.login_server()
+            # mail content
+            msg = self.get_main_msg()
+            # send mail
+            server.sendmail(self.msg_from, self.msg_to, msg.as_string())
+            server.quit()
+            print("Send succeed!!")
+        except smtplib.SMTPException:
+            print("Error:Can't send this email!!")
+
+
+if __name__ == "__main__":
+    mail_cfgs = {
+        # 'msg_from': 'trialmold@tkmold.com',
+                # 'password': '123456',
+                'msg_from': '704778540@qq.com',
+                'password': 'ctabssqsvnhsbcbf',
+                # 'msg_to': ['trialmold@tkmold.com'],
+                'msg_to': ['1621582331@qq.com'],
+                'msg_subject': 'Auto Send Email Test',
+                'msg_content': 'Hi, boy! Just do it!',
+                'attach_file': r'',
+                'msg_date': time.ctime()
+                }
+
+    manager = EmailManager(**mail_cfgs)
+    print(manager)
+    manager.set_msg_content("my Content.")
+    manager.send()

+ 0 - 0
TkMoldingServer/tkschedule/migrations/__init__.py


+ 106 - 0
TkMoldingServer/tkschedule/models.py

@@ -0,0 +1,106 @@
+# This is an auto-generated Django model module.
+# You'll have to do the following manually to clean this up:
+#   * Rearrange models' order
+#   * Make sure each model has one field with primary_key=True
+#   * Make sure each ForeignKey has `on_delete` set to the desired behavior.
+#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
+# Feel free to rename the models, but don't rename db_table values or field names.
+from django.db import models
+
+
+class ReservIndex(models.Model):
+    id_reservindex = models.AutoField(primary_key=True)
+    r_tag = models.CharField(max_length=45)
+    r_mold_no = models.CharField(max_length=45)
+    r_mold_type = models.CharField(max_length=45)
+    r_outsource = models.IntegerField()
+    r_mac_type = models.CharField(max_length=45)
+    r_inject_cycle = models.CharField(max_length=45)
+    r_trial_no = models.CharField(max_length=45)
+    r_customer_mac = models.CharField(max_length=45)
+    r_depart = models.CharField(max_length=45)
+    r_trial_time = models.CharField(max_length=45)
+    r_duration = models.CharField(max_length=45)
+    r_orderdate = models.DateField()
+    r_mold_readydate = models.DateTimeField()
+    r_trialdate = models.DateField()
+    r_reservdate = models.DateTimeField()
+    r_remark = models.CharField(max_length=45)
+    is_deleted = models.IntegerField()
+
+    class Meta:
+        managed = False
+        db_table = 'reserv_index'
+
+# This is an auto-generated Django model module.
+# You'll have to do the following manually to clean this up:
+#   * Rearrange models' order
+#   * Make sure each model has one field with primary_key=True
+#   * Make sure each ForeignKey has `on_delete` set to the desired behavior.
+#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
+# Feel free to rename the models, but don't rename db_table values or field names.
+from django.db import models
+
+
+class ReservAim(models.Model):
+    id_reservaim = models.AutoField(primary_key=True)
+    reserv = models.ForeignKey('ReservIndex', models.DO_NOTHING)
+    r_is_customer = models.IntegerField()
+    r_is_t1 = models.IntegerField()
+    r_is_inject = models.IntegerField()
+    r_is_self = models.IntegerField()
+    r_is_crun = models.IntegerField()
+    r_is_change = models.IntegerField()
+    r_action = models.IntegerField()
+    r_burrs = models.IntegerField()
+    r_appearance = models.IntegerField()
+    r_airtrap = models.IntegerField()
+    r_shrink = models.IntegerField()
+    r_pick = models.IntegerField()
+    r_customerchange = models.IntegerField()
+    r_stickymold = models.IntegerField()
+    r_deformation = models.IntegerField()
+    r_remark = models.CharField(max_length=45)
+
+    class Meta:
+        managed = False
+        db_table = 'reserv_aim'
+
+# This is an auto-generated Django model module.
+# You'll have to do the following manually to clean this up:
+#   * Rearrange models' order
+#   * Make sure each model has one field with primary_key=True
+#   * Make sure each ForeignKey has `on_delete` set to the desired behavior.
+#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
+# Feel free to rename the models, but don't rename db_table values or field names.
+from django.db import models
+
+
+class ReservExtra(models.Model):
+    id_reservextra = models.AutoField(primary_key=True)
+    reserv = models.ForeignKey('ReservIndex', models.DO_NOTHING)
+    r_make_engineer = models.CharField(max_length=45)
+    r_mk_email = models.CharField(max_length=45)
+    r_pro_engineer = models.CharField(max_length=45)
+    r_technician = models.CharField(max_length=45)
+    r_tc_email = models.CharField(max_length=45)
+    r_schemer = models.CharField(max_length=45)
+    r_sc_email = models.CharField(max_length=45)
+    r_status = models.IntegerField()
+    r_is_customer = models.IntegerField()
+    r_customer = models.CharField(max_length=45)
+    r_mold_readydate = models.DateTimeField()
+    r_busi_person = models.CharField(max_length=45)
+    r_busi_phone = models.CharField(max_length=45)
+    r_wkshop_person = models.CharField(max_length=45)
+    r_wkshop_phone = models.CharField(max_length=45)
+    r_tk_manager = models.CharField(max_length=45)
+    r_tk_manager_phone = models.CharField(max_length=45)
+    r_tk_test_manager = models.CharField(max_length=45)
+    r_tk_test_manager_phone = models.CharField(max_length=45)
+    r_tk_purchase = models.CharField(max_length=45)
+    r_tk_purchase_phone = models.CharField(max_length=45)
+
+    class Meta:
+        managed = False
+        db_table = 'reserv_extra'

+ 47 - 0
TkMoldingServer/tkschedule/tasks.py

@@ -0,0 +1,47 @@
+import datetime
+import time
+
+from tkschedule.emails import EmailManager
+from .models import ReservIndex
+
+MAIL_CONf = {
+    # 'msg_from': 'trialmold@tkmold.com',
+    # 'password': '123456',
+    'msg_from': '704778540@qq.com',
+    'password': 'ctabssqsvnhsbcbf',
+    # 'msg_to': ['trialmold@tkmold.com'],
+    'msg_to': ['1621582331@qq.com'],
+    'msg_subject': '试模约机确认提醒(请勿回复本邮件)!',
+    'msg_content': 'No Content!',
+    'attach_file': r'',
+    'msg_date': time.ctime()
+}
+
+
+def testEmail():
+    email_manager = EmailManager(**MAIL_CONf)
+
+    dt_s = datetime.datetime.now().date()  # 2018-7-15
+    dt_e = (dt_s - datetime.timedelta(20))  # 2018-7-08
+    objs = ReservIndex.objects.filter(r_trialdate__range=[dt_e, dt_e]).values('r_tag', 'r_trialdate',
+                                                                              'r_mold_no', 'r_trial_no',
+                                                                              'reservextra__r_make_engineer',
+                                                                              'reservextra__r_mk_email')
+    count = objs.count()
+    if count != 0:
+        for item in objs:
+            mk_email = item['reservextra__r_mk_email']
+            if mk_email == 'N/A':
+                print("无邮件地址!")
+                continue
+            print("有邮件地址")
+            mold_no = item['r_mold_no']
+            trial_no = item['r_trial_no']
+            trial_date = item['r_trialdate']
+            msg_content = f"您预约的{mold_no}-{trial_no}试模将于{trial_date}进行,请前往试模系统进行确认!(若无预约请勿略此邮件。)"
+            print(msg_content)
+            email_manager.set_msg_content(msg_content)
+            email_manager.set_msg_to([mk_email])
+            email_manager.send()
+            # continue
+

+ 0 - 0
TkMoldingServer/tkschedule/tests.py


+ 7 - 0
TkMoldingServer/tkschedule/urls.py

@@ -0,0 +1,7 @@
+from django.urls import path
+
+from . import views
+
+urlpatterns = [
+    path('', views.index, name='index'),
+]

+ 61 - 0
TkMoldingServer/tkschedule/views.py

@@ -0,0 +1,61 @@
+import datetime
+import time
+
+from django.http import HttpResponse
+
+from tkschedule.emails import EmailManager
+from .models import ReservIndex
+
+# Create your views here.
+import logging
+
+logger = logging.getLogger("tkschedule.views")
+MAIL_CONf = {
+    # 'msg_from': 'trialmold@tkmold.com',
+    # 'password': '123456',
+    'msg_from': '704778540@qq.com',
+    'password': 'ctabssqsvnhsbcbf',
+    # 'msg_to': ['trialmold@tkmold.com'],
+    'msg_to': ['1621582331@qq.com'],
+    'msg_subject': '试模约机确认提醒(请勿回复本邮件)!',
+    'msg_content': 'No Content!',
+    'attach_file': r'',
+    'msg_date': time.ctime()
+}
+
+def getData():
+
+
+    email_manager = EmailManager(**MAIL_CONf)
+
+    dt_s = datetime.datetime.now().date()  # 2018-7-15
+    dt_e = (dt_s - datetime.timedelta(20))  # 2018-7-08
+    objs = ReservIndex.objects.filter(r_trialdate__range=[dt_e, dt_e]).values('r_tag','r_trialdate',
+                                                                              'r_mold_no','r_trial_no',
+                                                                              'reservextra__r_make_engineer',
+                                                                              'reservextra__r_mk_email')
+    count = objs.count()
+    if count != 0 :
+        for item in objs:
+            mk_email  = item['reservextra__r_mk_email']
+            if mk_email == 'N/A':
+                print("无邮件地址!")
+                continue
+            print("有邮件地址")
+            mold_no = item['r_mold_no']
+            trial_no = item['r_trial_no']
+            trial_date = item['r_trialdate']
+            msg_content = f"您预约的{mold_no}-{trial_no}试模将于{trial_date}进行,请前往试模系统进行确认!(若无预约请勿略此邮件。)"
+            print(msg_content)
+            email_manager.set_msg_content(msg_content)
+            email_manager.set_msg_to([mk_email])
+            email_manager.send()
+            # continue
+
+def index(request):
+    # getData()
+    # logger.info("ss")
+
+    return HttpResponse("Hello, world. You're at the polls index.")
+
+