本期内容:基于Django与Bootstrap的在线计算器
实验环境:
项目功能主要是实现一个在线计算器。在输入框中输入计算式,单击“计算”按钮可以在输出框中输出结果。前端采用了 Bootstrap进行制作,提供输入框和按钮让用户进行信息输入,然后将计算式通过 Ajax方式传输给后台进行计算。后台采用Django 进行开发,获取到前端发送的数据后利用Python的子进程模块subprocess来计算式子,并将计算结果返回给前端进行显示。
1.打开vscode命令行输入以下命令创建一个名为jsq的项目
django-admin startproject jsq
2.利用cd命令切换到manage.py文件所在目录,输入以下命令创建一个名为app的应用
cd jsq
python manage.py startapp app
3.输入以下命令启动项目
python manage.py runserver
4.在浏览器中输入“http://127.0.0.1:8000”检查web界面是否启动成功
出现如下界面说明web界面启动成功
1.在官网下载bootstrap源代码后解压
2.在app文件夹下创建一个static子文件夹
3.在解压的文件中找到dist文件夹,将该文件夹中的css,fonts,js三个子文件夹复制到static文件夹下面,并在static文件夹中新建一个名为img的子文件夹(用于存放图片)
4.进入jQuery官网,复制网页内容,保存为jquery.min.js文件放到static目录下的js子文件夹中。
1.在app文件夹下创建一个templates子文件夹,然后在templates文件夹下面创建一个index.html文件,编辑该文件,填入以下代码:
{% load static %}
DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta http-equiv = "X-UA-Compatible" content = "IE=edge">
<meta name = "viewport" content = "width=device-width,initial-scale=1">
<title>在线计算器title>
<link rel = "stylesheet" href = "{% static 'css/bootstrap.min.css' %}"/>
<link rel = "stylesheet" href = "{% static 'css/style.css'%}"/>
<script src = "{% static 'js/jquery.min.js' %}">script>
<script src = "{% static 'js/bootstrap.min.js' %}">script>
head>
<body>
<div class="container-fluid">
<div class = "row">
<div class = "col-xs-1 col-sm-4">div>
<div id = "computer" class="col-xs-10 col-sm-6">
<input type="text" id="txt_code" name="txt_code" value="" class="form-control input_show" placeholder="公式计算" disabled/>
<input type="text" id="txt_result" name="txt_result" value="" class="form-control input_show" placeholder="结果" disabled/>
<br />
<div>
<button type="button" class="btn btn-default btn_num" onclick="fun_7()">7button>
<button type="button" class="btn btn-default btn_num" onclick="fun_8()">8button>
<button type="button" class="btn btn-default btn_num" onclick="fun_9()">9button>
<button type="button" class="btn btn-default btn_num" onclick="fun_div()">÷button>
<br/>
<button type="button" class="btn btn-default btn_num" onclick="fun_4()">4button>
<button type="button" class="btn btn-default btn_num" onclick="fun_5()">5button>
<button type="button" class="btn btn-default btn_num" onclick="fun_6()">6button>
<button type="button" class="btn btn-default btn_num" onclick="fun_mul()">×button>
<br/>
<button type="button" class="btn btn-default btn_num" onclick="fun_1()">1button>
<button type="button" class="btn btn-default btn_num" onclick="fun_2()">2button>
<button type="button" class="btn btn-default btn_num" onclick="fun_3()">3button>
<button type="button" class="btn btn-default btn_num" onclick="fun_sub()">-button>
<br/>
<button type="button" class="btn btn-default btn_num" onclick="fun_0()">0button>
<button type="button" class="btn btn-default btn_num" onclick="fun_00()">00button>
<button type="button" class="btn btn-default btn_num" onclick="fun_dot()">.button>
<button type="button" class="btn btn-default btn_num" onclick="fun_add()">+button>
div>
<div>
<br/>
<button type = "button" class = "btn btn-success btn-lg btn_clear"
id = "lgbut_clear" onclick="fun_clear()">清空button>
<button type = "button" class = "btn btn-success btn-lg"
id = "lgbut_compute">计算button>
div>
div>
<div class="col-xs-1 col-sm-2">div>
div>
div>
<div class="extendContent">div>
<script>
var x = document.getElementById("txt_code");
var y = document.getElementById("txt_result");
function fun_1(){
x.value += '1';
}
function fun_2(){
x.value += '2';
}
function fun_3(){
x.value += '3';
}
function fun_4(){
x.value += '4';
}
function fun_5(){
x.value += '5';
}
function fun_6(){
x.value += '6';
}
function fun_7(){
x.value += '7';
}
function fun_8(){
x.value += '8';
}
function fun_9(){
x.value += '9';
}
function fun_add(){
x.value += '+';
}
function fun_sub(){
x.value += '-';
}
function fun_mul(){
x.value += '*';
}
function fun_div(){
x.value += '/';
}
function fun_0(){
x.value += '0';
}
function fun_00(){
x.value += '00';
}
function fun_dot(){
x.value += '.';
}
function fun_clear(){
x.value = '';
y.value = '';
}
script>
<script>
function ShowResult(data){
var y = document.getElementById('txt_result')
y.value = data['result']
}
script>
<script>
$('#lgbut_compute').click(function(){
$.ajax({
url:'/compute/',
type:'POST',
data:{
'code':$('#txt_code').val()
},
dataType:'json',
success:ShowResult
})
})
script>
body>
html>
2.在css文件夹中创建一个style.css文件并填入以下内容:
body{
background-image:url("../img/bg.jpg");
background-position:center 0;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
-webkit-background-size:cover;
-o-background-size:cover;
-moz-background-size:cover;
-ms-background-size:cover;
}
.input_show{
margin-top:35px;
max-width:280px;
height:35px;
}
.btn_num{
margin:1px 1px 1px 1px;
width:60px;
}
.btn_clear{
margin-left:40px;
margin-right:20px;
}
.extendContent{
height:300px;
}
1.配置视图处理函数,编辑views.py文件,填入以下代码:
from django.shortcuts import render
import subprocess
from django.views.decorators.http import require_POST
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import warnings
warnings.filterwarnings('ignore')
# Create your views here.
def home(request):
return render(request, 'index.html')
def run_code(code):
try:
code = 'print(' + code + ')'
output = subprocess.check_output(['python', '-c', code],
universal_newlines=True,
stderr=subprocess.STDOUT,
timeout=30)
except subprocess.CalledProcessError as e:
output = '公式输入有误'
return output
@csrf_exempt
@require_POST
def compute(request):
code = request.POST.get('code')
result = run_code(code)
return JsonResponse(data={'result':result})
2.配置settings.py文件,找到INSTALLED_APPS字段,将创建的app应用添加进来,代码如下:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app', #在此处添加应用
]
找到ALLOWED_HOSTS字段并修改,编辑代码如下:
ALLOWED_HOSTS = ['*',]
3.配置访问路由,编辑urls.py文件,填入以下代码:
from django.contrib import admin
from django.urls import path
from app.views import home, compute
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name='home'),
path('compute/', compute, name='compute'),
]
在终端切换到manage.py文件所在目录,输入以下命令运行项目,然后在浏览器中输入“http://127.0.0.1:8000”查看运行结果
python manage.py runserver
出现以下结果说明运行成功!
若计算时遇到问题:
0.01s - Debugger warning: It seems that frozen modules are being used, which may0.00s - make the debugger miss breakpoints. Please pass-Xfrozen_modules=off0.00s - to python to disable frozen modules.0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.
可以尝试在启动 Django 服务时添加 --noreload
参数来解决这个问题。如下所示:
python manage.py runserver --noreload
这个问题是由于 Django 的自动重载机制导致的,自动重载机制会导致 Python 解释器重新加载模块,从而导致调试器无法正确地识别断点位置。使用 --noreload
参数可以禁用自动重载机制,并避免这个问题的发生。
我是一只有趣的兔子,感谢你的喜欢!