python+html實(shí)現(xiàn)前后端數(shù)據(jù)交互界面顯示的全過程
前言
最近剛剛開始學(xué)習(xí)如何將python后臺(tái)與html前端結(jié)合起來,現(xiàn)在寫一篇blog記錄一下,我采用的是前后端不分離形式。
話不多說,先來實(shí)現(xiàn)一個(gè)簡單的計(jì)算功能吧,前端輸入計(jì)算的數(shù)據(jù),后端計(jì)算結(jié)果,返回結(jié)果至前端進(jìn)行顯示。
1.python開發(fā)工具
我選用的是pycharm專業(yè)版,因?yàn)樯鐓^(qū)版本無法創(chuàng)建django程序
2.項(xiàng)目創(chuàng)建
第一步:打開pycharm,創(chuàng)建一個(gè)django程序

藍(lán)圈圈起來的為自定義的名字,點(diǎn)擊右下角的create可以創(chuàng)建一個(gè)django項(xiàng)目
如下圖,圈起來的名字與上圖相對(duì)應(yīng)

第二步:編寫后端代碼
①在blog文件夾下面的views.py中編寫以下代碼:
from django.shortcuts import render
from calculate import jisuan
# Create your views here.
def calculate(request):
return render(request, 'hello.html')
def show(request):
x = request.POST.get('x')
y = request.POST.get('y')
result = jisuan(x, y)
return render(request, 'result.html', {'result': result})②在csdn文件夾下面的urls.py中添加下面加粗部分那兩行代碼
from django.shortcuts import render
from calculate import jisuan
# Create your views here.
def calculate(request):
return render(request, 'hello.html')
def show(request):
x = request.POST.get('x')
y = request.POST.get('y')
result = jisuan(x, y)
return render(request, 'result.html', {'result': result})③新建calculate.py文件,內(nèi)容為:
def jisuan(x, y):
x = int(x)
y = int(y)
return (x+y)第三步:編寫前端代碼
①數(shù)據(jù)輸入的頁面hello.html,內(nèi)容為:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="/getdata/">
{% csrf_token %}
<input type="text" name="x" placeholder="請輸入x"/><br>
<input type="text" name="y" placeholder="請輸入y"><br>
<input type="submit" value="進(jìn)行計(jì)算">
</form>
</body>
</html>②結(jié)果返回的頁面result.html,內(nèi)容為:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 style="color:blue">計(jì)算結(jié)果為{{ result }}</h1>
</body>
</html>第四步:啟動(dòng)后臺(tái)程序
在瀏覽器地址欄輸入http://127.0.0.1:8000/jisuan
回車可進(jìn)入數(shù)據(jù)輸入頁面

我們輸入x=10, y=20

點(diǎn)擊進(jìn)行計(jì)算按鈕,頁面跳轉(zhuǎn),顯示計(jì)算結(jié)果

好啦,一個(gè)簡單的django項(xiàng)目就完成啦
如果想要進(jìn)行復(fù)雜的計(jì)算操作,可以在calculate.py編寫更加復(fù)雜的函數(shù)
源碼資源鏈接:django學(xué)習(xí),前后端不分離
總結(jié)
到此這篇關(guān)于python+html實(shí)現(xiàn)前后端數(shù)據(jù)交互界面顯示的文章就介紹到這了,更多相關(guān)python+html前后端數(shù)據(jù)交互內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用python-Jenkins批量創(chuàng)建及修改jobs操作
這篇文章主要介紹了使用python-Jenkins批量創(chuàng)建及修改jobs操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Python獲取系統(tǒng)所有進(jìn)程PID及進(jìn)程名稱的方法示例
這篇文章主要介紹了Python獲取系統(tǒng)所有進(jìn)程PID及進(jìn)程名稱的方法,涉及Python使用psutil對(duì)系統(tǒng)進(jìn)程進(jìn)行操作的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-05-05

