Skip to content

Commit 6a3e295

Browse files
committed
First commit.
0 parents  commit 6a3e295

15 files changed

+358
-0
lines changed

.gitignore

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
*.pyc
2+
*.pyo
3+
*.log
4+
*.sqlite3
5+
/static/*
6+
/db.sqlite3
7+
*/__pycache__/*
8+
*/migrations/*

TM/__init__.py

Whitespace-only changes.

TM/admin.py

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from django.contrib import admin
2+
3+
# Register your models here.

TM/apps.py

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
from django.apps import AppConfig
2+
3+
4+
class TmConfig(AppConfig):
5+
name = 'TM'

TM/models.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from django.db import models
2+
3+
4+
# * ArticleSwint
5+
class Temperature(models.Model):
6+
"""Model for Articles."""
7+
8+
time = models.DateTimeField(verbose_name=u"时间", auto_now_add=True)
9+
value = models.TextField(verbose_name=u"温度")
10+
11+
class Meta():
12+
ordering = [
13+
'time',
14+
]
15+
16+
def __unicode__(self):
17+
return self.title
18+
19+
__str__ = __unicode__
20+
21+
22+
# Create your models here.

TM/static/TM/plot.png

46.5 KB
Loading

TM/templates/TM/index.html

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<!DOCTYPE html>
2+
<html lang="zh-cn">
3+
<head>
4+
<meta charset="utf-8" />
5+
<title>{{website_title}}</title>
6+
</head>
7+
<body>
8+
{#% if temperature_list %#}
9+
{#% with post_list=temperature_list %#}
10+
{#% for post in post_list %#}
11+
{#{post.time|time:"H:i" }#}
12+
{#{post.value}#}
13+
<!-- <br/> -->
14+
{#% endfor %#}
15+
{#% endwith %#}
16+
{#% endif %#}
17+
{% load static %}
18+
<img src={% static "TM/plot.png"%}></img>
19+
</body>
20+
</html>

TM/tests.py

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from django.test import TestCase
2+
3+
# Create your tests here.

TM/urls.py

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from django.conf.urls import url
2+
from TM.views import index
3+
# from swint.models import Article, Category
4+
5+
urlpatterns = [
6+
url(r'^$', index, name='index-view'),
7+
]

TM/views.py

+102
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
# from django.shortcuts import render
2+
from django.shortcuts import render_to_response
3+
from django.http import HttpResponse
4+
# from django.views.generic import ListView
5+
from django.conf import settings
6+
from TM.models import Temperature
7+
# import logging
8+
from django.views.decorators.csrf import csrf_exempt
9+
import sqlite3
10+
# 查看tables:apt安装sqlite3,然后sqlite3 db.sqlite3,输入.tables。
11+
import matplotlib
12+
matplotlib.use('Agg')
13+
import matplotlib.pyplot as plt
14+
import os
15+
16+
# logger = logging.getLogger(__name__)
17+
18+
# Create your views here.
19+
20+
21+
@csrf_exempt
22+
def index(request):
23+
if request.method == 'POST':
24+
add = Temperature(value=request.POST.get("temperature_data", ""))
25+
add.save() # 不save无法保存到数据库
26+
return HttpResponse('login success!')
27+
else:
28+
# 从sqlite中获取数据。
29+
conn = sqlite3.connect('db.sqlite3')
30+
cur = conn.cursor()
31+
cur.execute("SELECT * FROM TM_Temperature")
32+
data = cur.fetchall()
33+
data_0 = [int(row[0]) for row in data][-10:]
34+
data_2 = [float(row[2]) for row in data][-10:]
35+
36+
plot_file = 'static/TM/plot.png'
37+
fig1, ax1 = plt.subplots(figsize=(8, 4), dpi=98)
38+
ax1.set_title(u'房间温度', fontproperties='KaiTi')
39+
ax1.set_xlabel(u'时间(小时)', fontproperties='KaiTi')
40+
ax1.set_ylabel(u'温度(\u2103)', fontproperties='KaiTi')
41+
ax1.plot(
42+
data_0,
43+
data_2,
44+
)
45+
fig1.savefig(plot_file)
46+
plt.close(fig1)
47+
48+
# temperature_list = Temperature.objects.all()
49+
return render_to_response('TM/index.html')
50+
51+
52+
# * Base_Mixin
53+
# class Base_Mixin(object):
54+
# """Basic mix class."""
55+
56+
# def get_context_data(self, *args, **kwargs):
57+
# context = super(Base_Mixin, self).get_context_data(**kwargs)
58+
# try:
59+
# # 网站标题等内容
60+
# context['website_title'] = settings.WEBSITE_TITLE
61+
# except Exception:
62+
# logger.error(u'[BaseMixin]加载基本信息出错')
63+
# return context
64+
65+
# * Index_View
66+
# class Index_View(Base_Mixin, ListView):
67+
# """view for index.html"""
68+
# model = Temperature
69+
# # 或者
70+
# # queryset = Temperature.objects.all()
71+
# template_name = 'TM/index.html'
72+
# context_object_name = 'temperature_list'
73+
74+
# # def get(self, request, *args, **kwargs):
75+
# # article_id = self.kwargs.get('id')
76+
77+
# # # 如果ip不存在就把文章的浏览次数+1。
78+
# # if ip not in visited_ips:
79+
# # try:
80+
# # article = self.queryset.get(id=article_id)
81+
# # except ArticleSwint.DoesNotExist:
82+
# # logger.error(u'[ArticleView]访问不存在的文章:[%s]' % article_id)
83+
# # raise Http404
84+
# # else:
85+
# # article.view_times += 1
86+
# # article.save()
87+
# # visited_ips.append(ip)
88+
89+
# # # 更新缓存
90+
# # cache.set(article_id, visited_ips, 15 * 60)
91+
92+
# # return super(Article_View, self).get(request, *args, **kwargs)
93+
94+
# @csrf_exempt
95+
# def post(self, request, *args, **kwargs):
96+
# add = Temperature(value=request.POST)
97+
# add.save() # 不save无法保存到数据库
98+
# # 或者
99+
# # Temperature.objects.create(value=request.POST)
100+
# kwargs['Temp'] = request.POST + 1
101+
102+
# return super(Index_View, self).post(request, *args, **kwargs)

TemperatureMonitor/__init__.py

Whitespace-only changes.

TemperatureMonitor/settings.py

+128
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
"""
2+
Django settings for TemperatureMonitor project.
3+
4+
Generated by 'django-admin startproject' using Django 1.11.2.
5+
6+
For more information on this file, see
7+
https://docs.djangoproject.com/en/1.11/topics/settings/
8+
9+
For the full list of settings and their values, see
10+
https://docs.djangoproject.com/en/1.11/ref/settings/
11+
"""
12+
13+
import os
14+
15+
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
16+
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17+
18+
# Quick-start development settings - unsuitable for production
19+
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
20+
21+
# SECURITY WARNING: keep the secret key used in production secret!
22+
SECRET_KEY = 'yp9*3fr006eoj&hq4&i^3@hm$_&!!s#s$3whu@is&$dsy*p*g@'
23+
24+
# SECURITY WARNING: don't run with debug turned on in production!
25+
DEBUG = False
26+
ALLOWED_HOSTS = [
27+
'127.0.0.1',
28+
'localhost ',
29+
'192.168.1.102',
30+
'192.168.1.6',
31+
'192.168.1.13',
32+
]
33+
34+
# Application definition
35+
36+
INSTALLED_APPS = [
37+
'django.contrib.admin',
38+
'django.contrib.auth',
39+
'django.contrib.contenttypes',
40+
'django.contrib.sessions',
41+
'django.contrib.messages',
42+
'django.contrib.staticfiles',
43+
'TM',
44+
'gunicorn',
45+
]
46+
47+
MIDDLEWARE = [
48+
'django.middleware.security.SecurityMiddleware',
49+
'django.contrib.sessions.middleware.SessionMiddleware',
50+
'django.middleware.common.CommonMiddleware',
51+
'django.middleware.csrf.CsrfViewMiddleware',
52+
'django.contrib.auth.middleware.AuthenticationMiddleware',
53+
'django.contrib.messages.middleware.MessageMiddleware',
54+
'django.middleware.clickjacking.XFrameOptionsMiddleware',
55+
]
56+
57+
ROOT_URLCONF = 'TemperatureMonitor.urls'
58+
59+
TEMPLATES = [
60+
{
61+
'BACKEND': 'django.template.backends.django.DjangoTemplates',
62+
'DIRS': [],
63+
'APP_DIRS': True,
64+
'OPTIONS': {
65+
'context_processors': [
66+
'django.template.context_processors.debug',
67+
'django.template.context_processors.request',
68+
'django.contrib.auth.context_processors.auth',
69+
'django.contrib.messages.context_processors.messages',
70+
],
71+
},
72+
},
73+
]
74+
75+
WSGI_APPLICATION = 'TemperatureMonitor.wsgi.application'
76+
77+
# Database
78+
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
79+
80+
DATABASES = {
81+
'default': {
82+
'ENGINE': 'django.db.backends.sqlite3',
83+
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
84+
}
85+
}
86+
87+
# Password validation
88+
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
89+
90+
AUTH_PASSWORD_VALIDATORS = [
91+
{
92+
'NAME':
93+
'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
94+
},
95+
{
96+
'NAME':
97+
'django.contrib.auth.password_validation.MinimumLengthValidator',
98+
},
99+
{
100+
'NAME':
101+
'django.contrib.auth.password_validation.CommonPasswordValidator',
102+
},
103+
{
104+
'NAME':
105+
'django.contrib.auth.password_validation.NumericPasswordValidator',
106+
},
107+
]
108+
109+
# Internationalization
110+
# https://docs.djangoproject.com/en/1.11/topics/i18n/
111+
112+
LANGUAGE_CODE = 'en-us'
113+
114+
TIME_ZONE = 'UTC'
115+
116+
USE_I18N = True
117+
118+
USE_L10N = True
119+
120+
USE_TZ = True
121+
122+
# Static files (CSS, JavaScript, Images)
123+
# https://docs.djangoproject.com/en/1.11/howto/static-files/
124+
125+
STATIC_URL = '/static/'
126+
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
127+
128+
WEBSITE_TITLE = u'Swint\'s blog'

TemperatureMonitor/urls.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
"""TemperatureMonitor URL Configuration
2+
3+
The `urlpatterns` list routes URLs to views. For more information please see:
4+
https://docs.djangoproject.com/en/1.11/topics/http/urls/
5+
Examples:
6+
Function views
7+
1. Add an import: from my_app import views
8+
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
9+
Class-based views
10+
1. Add an import: from other_app.views import Home
11+
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
12+
Including another URLconf
13+
1. Import the include() function: from django.conf.urls import url, include
14+
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
15+
"""
16+
from django.conf.urls import url, include
17+
from django.contrib import admin
18+
19+
urlpatterns = [
20+
url(r'^admin/', admin.site.urls),
21+
url(r'', include('TM.urls')),
22+
]

TemperatureMonitor/wsgi.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""
2+
WSGI config for TemperatureMonitor project.
3+
4+
It exposes the WSGI callable as a module-level variable named ``application``.
5+
6+
For more information on this file, see
7+
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
8+
"""
9+
10+
import os
11+
12+
from django.core.wsgi import get_wsgi_application
13+
14+
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "TemperatureMonitor.settings")
15+
16+
application = get_wsgi_application()

manage.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#!/usr/bin/env python
2+
import os
3+
import sys
4+
5+
if __name__ == "__main__":
6+
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
7+
"TemperatureMonitor.settings")
8+
try:
9+
from django.core.management import execute_from_command_line
10+
except ImportError:
11+
# The above import may fail for some other reason. Ensure that the
12+
# issue is really that Django is missing to avoid masking other
13+
# exceptions on Python 2.
14+
try:
15+
import django
16+
except ImportError:
17+
raise ImportError(
18+
"Couldn't import Django. Are you sure it's installed and "
19+
"available on your PYTHONPATH environment variable? Did you "
20+
"forget to activate a virtual environment?")
21+
raise
22+
execute_from_command_line(sys.argv)

0 commit comments

Comments
 (0)