使用Django和heroku搭建一个简易网站

最近由于毕设的需要,想要做一个通过输入各种参数,预测冷热负荷的机器学习系统。可以在网页上直接输入房屋参数,预测出房屋所需冷热负荷和能耗水平。

关于机器学习那块相信网上已经有不少教程,这里就不再赘述,本文主要总结一下Django和heroku搭配来建立网站。

Django

https://docs.djangoproject.com/zh-hans/2.1/contents/
这个tutorial真的内容很全有木有,不管是新手入门还是遇到的一些问题,大部分都能在官方的doc里面得到解答。这也是我这一次学到的东西吧。

这个是根据tutorial建立起来的网站的文件目录。

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py
    polls/
        __init__.py
        admin.py
        migrations/
            __init__.py
            0001_initial.py
        models.py
        static/
            polls/
                images/
                    background.gif
                style.css
        templates/
            polls/
                detail.html
                index.html
                results.html
        tests.py
        urls.py
        views.py
    templates/
        admin/
            base_site.html

最顶层是mysite使我们的project,然后在这个project下面添加了一个app叫做polls。

在project下面又有一个文件夹叫mysite,里面放了一些setting,urls的重要文件。
url是指明Uniform Resource Locator的文件,即各种资源的索引位置。
wsgi.py是方便之后部署的文件。

在polls文件夹中,migration文件夹主要是负责数据库的连接。
models文件里定义了一些类,是我们数据库中会记录的东西。
views是我们给访问者呈现什么数据,它和templates是搭配的。
templates文件夹里,还有一个polls文件夹(虽然我自己后来建的时候放在polls文件夹中的html文件总是找不到就不再加这个polls子文件夹了,但是合理的情况是放在polls中的),存放着html格式的文件,和views搭配负责页面如何呈现。

需要学习一点html的知识
http://www.runoob.com/html/html-basic.html
其中在我自己的project里面最重要的是表单,即用户输入数据然后表单通过request接收,views.py处理,return回去。
这是我views.py文件的内容:

# -*- coding: utf-8 -*-
from django.shortcuts import render, render_to_response
from django.views.decorators import csrf
import tensorflow as tf
import numpy as np


def add_layer(inputs, insize, outsize, n, activation_function=None):
    layer_name = 'layer%s' % n
    with tf.name_scope(layer_name):
        Weights = tf.Variable(tf.random_normal([insize, outsize]), name='w')
        tf.summary.histogram(layer_name + 'Weights', Weights)
        bias = tf.Variable(tf.zeros([1, outsize]))
        tf.summary.histogram(layer_name + 'bias', bias)
        wx_b = tf.add(tf.matmul(inputs, Weights), bias)

        if activation_function is None:
            output = wx_b
        else:
            output = activation_function(wx_b, )
        return output

def input(request):
    return render_to_response('get.html')

def calculate(request):
    # xdata = [0.98, 514.50, 294.00, 110.25, 7.00, 2, 0.10, 1]
    request.encoding = 'utf-8'
    context = {}
    xdata = []
    if request.GET:
        for num in range(1, 9):
            xdata.append(float(request.GET['X%i' % num]))

    xdata = np.array(xdata).reshape([1, 8])
    xdata = 1.0 / (1 + np.exp(xdata))
    # print('xdata: ', xdata)
    # context['heatload'] = xdata[0]
    # context['coolload'] = xdata[2]
    
    tf.reset_default_graph()
    xs = tf.placeholder(tf.float32, xdata.shape, name='xinput')

    l1 = add_layer(xs, xdata.shape[1], 10, 1, activation_function=tf.nn.relu)  # 10 is layer units
    l2 = add_layer(l1, 10, 10, 2, activation_function=tf.nn.relu)  # 10 is layer units
    prediction = add_layer(l2, 10, 2, 3, activation_function=None)  # predicted output

    saver = tf.train.Saver()

    with tf.Session() as sess:
        # you cannot initialize here
        saver.restore(sess, './my_net/save_net.ckpt')
        rlt = sess.run(prediction, feed_dict={xs: xdata})
        # print('result: ', rlt)
        context['heatload'] = rlt[0, 0]
        context['coolload'] = rlt[0, 1]
        print('context', context)
    return render(request, "result.html", context)

get.html


<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Calculate the hear load and cool load</title>
</head>
<body>
    <form action = "/result/" method = "get">
        {%  csrf_token %}
        Relative Compactness (surface-area-to-volume ratio): <input type="number" step = "any" name="X1" value = 0.764167> <br />
        Surface Area: <input type="number" name="X2" step = "any" value = 671.708333> <br />
        Wall Area: <input type="number" name="X3" step = "any" value = 318.50000> <br />
        Roof Area: <input type="number" name="X4" step = "any" value = 176.604167> <br />
        Overall Height: <input type="number" name="X5" step = "any" value = 5.25> <br />
        Orientation: <input type="number" name="X6" step = "any" value = 3.5> <br />
        Glazing Area: <input type="number" name="X7" step = "any" value = 0.234375> <br />
        Glazing Area Distribution: <input type="text" name="X8" step = "any" value = 2.812500> <br />
        <input type="submit" value="Submit">
    </form>
<p></p>

</body>
</html>

返回结果的页面get.html。里面还用到一些html判断语句来判断能耗等级。


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>result</title>
</head>
<body>
heat load: <p> {{ heatload }} BTU </p> <br />
cool load: <p> {{ coolload }} BTU </p> <br />

{% if heatload < 11.67 and coolload < 14.52 %}
    the efficiency classification: very low heating and cooling requirement
{% elif 15.92 > heatload and heatload >= 11.67 and 18.65 > coolload and coolload >= 14.52  %}
    the efficiency classification: low heating and cooling requirement
{% elif 26.27 > heatload and heatload >= 15.92 and 28.27 > coolload and coolload >= 18.65  %}
    the efficiency classification: medium heating and cooling requirement
{% elif 32.32 > heatload and heatload >= 26.27 and 34.03 > coolload and coolload >= 28.27  %}
    the efficiency classification: high heating and cooling requirement
{% else %}
    the efficiency classification: very high heating and cooling requirement
{% endif %}
</body>
</html>

然后下面这个是mysite/urls,是指明了url和views或者下面app的url关联关系

from django.contrib import admin
from django.urls import path, include
from energy.views import calculate

urlpatterns = [
    path('', include('energy.urls')),
    path('result/', calculate),
    path('admin/', admin.site.urls),
]

Heroku

同理,heroku这边还是得参照官方的tutorial一步一步来,包括遇到问题在官方的doc里面很多时候都能找到答案。我一开始是在Stack Overflow上看到一些解决办法,但通常这不是最优的方法。不如official的doc

https://devcenter.heroku.com/articles/getting-started-with-python
这个tutorial主要用一个小的app来示例如何部署,我们需要先开一个heroku的账号。使用heroku login登录一下

然后根据这篇文章
https://devcenter.heroku.com/articles/django-app-configuration
需要先在自己的project文件夹中,放置一个requirements.txt和Procfile。里面分别记录了app需要的python module和启动app的命令。

注意是需要两个django_heroku和gunicorn的帮忙,doc中写得很清楚了

接下来

heroku create # 建立一个云端的dyno
git push heroku master # 上传云端
heroku ps:scale web=1 # 启动  
heroku open # 自动打开网页

注意每一次对app或者project有改动都要重新push,方法同GIT (参考了这篇http://daikeren.github.io/django_tutorial/deploy_to_cloud/README.html)但其实这篇没有多大帮助,基本都是靠官方的doc解决的

git init
git add .

或者

git add -u
git commit -m  "first commit"

在部署的时候遇到一个关于static file的问题,官方doc也有解答
https://devcenter.heroku.com/articles/django-assets

更多问题
https://devcenter.heroku.com/categories/working-with-django

猜你喜欢

转载自blog.csdn.net/qq_42648305/article/details/83758895