微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python+html实现前后端数据交互界面显示

最近刚刚开始学习如何将python后台与html前端结合起来,现在写一篇blog记录一下,我采用的是前后端不分离形式。

话不多说,先来实现一个简单的计算功能吧,前端输入计算的数据,后端计算结果,返回结果至前端进行显示

1.Python开发工具

我选用的是pycharm专业版,因为社区版本无法创建django程序

2.项目创建

第一步:打开pycharm,创建一个django程序

蓝圈圈起来的为自定义的名字,点击右下角的create可以创建一个django项目

如下图,圈起来的名字与上图相对应

第二步:编写后端代码

①在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.contrib import admin
from django.urls import path
from blog import views

urlpatterns = [
    path('admin/',admin.site.urls),path('jisuan/',views.calculate),path('getdata/',views.show)
]

③新建calculate.py文件内容为:

def jisuan(x,y):
    x = int(x)
    y = int(y)
    return (x+y)

第三步:编写前端代码

①数据输入的页面hello.html,内容为:

<!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="进行计算">
</form>

</body>
</html>

②结果返回的页面result.html,内容为:

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 style="color:blue">计算结果为{{ result }}</h1>
</body>
</html>

第四步:启动后台程序

在浏览器地址栏输入http://127.0.0.1:8000/jisuan

回车可进入数据输入页面

我们输入x=10,y=20

点击进行计算按钮,页面跳转显示计算结果

 

 好啦,一个简单的django项目就完成啦

如果想要进行复杂的计算操作,可以在calculate.py编写更加复杂的函数

源码资源链接django学习,前后端不分离-Python文档类资源-CSDN文库

https://download.csdn.net/download/thzhaopan/84989809

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐