日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

python+html實(shí)現(xiàn)前后端數(shù)據(jù)交互界面顯示的全過程_python

作者:代碼的女朋友 ? 更新時(shí)間: 2022-08-03 編程語言

前言

最近剛剛開始學(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="請(qǐng)輸入x"/><br>
    <input type="text" name="y" placeholder="請(qǐng)輸入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é)

原文鏈接:https://blog.csdn.net/thzhaopan/article/details/123513504

欄目分類
最近更新