Python Web之Django
一、环境需求
1、OS:Windows10
2、IDE:PyCharm 2019.2
3、Interpreter:Python 3.7
二、项目搭建
1、构建Django工程,打开PyCharm,点击【File】==》【New Project...】==》【Django】。
2、项目工程保存路径、工程名称、解释器选择,点击【Create】创建项目工程,如下图所示:
3、创建好的项目工程目录结构如下图所示:
4、条件需要的相关依赖包,点击【File】==》【Settings...】打开如下图所示界面,根据图中标注的编码顺序添加需要的相关模块依赖。
5、搜索相关依赖包,安装相关依赖包,根据下图所示编码顺序执行。
6、连接MySQL数据库相关配置如下:
7、创建功能模块,创建【models.py】文件编辑模块功能表信息,如下图所示:
8、创建数据模型表,依次执行如下语句创建相关数据表。
Ps:执行命令时可能出现【No installed app with label 'login'.】报错,在settings.py文件中添加如下图所示内容即可。
9、创建相关接口文件,如下:
【views.py】内容如下:
from django.shortcuts import render from .models import User from django.core import serializers import json from django.http import HttpResponse from django.db import connection # Create your views here. def query(request): rs = User.objects.all() to_json = serializers.serialize('json', rs) res_json = json.loads(to_json) # return render(request, template_name="pages/index.html", context=res_json, content_type="application/json;charset=utf8", # status=200) return HttpResponse(content=to_json, status=200) def add(request): user_name = request.GET.get("userName") user_pwd = request.GET.get("userPwd") user = User() user.user_name = user_name user.user_pwd = user_pwd success = {"success": "success"} try: user.save() except Exception as e: success["success"] = "error" return render(request, template_name="pages/index.html", context=success, status=200) def add_filter(request): user_name = request.GET.get("userName") user_pwd = request.GET.get("userPwd") sex = request.GET.get("sex") success = {"success": "success"} try: sql = "INSERT INTO test.login_user(user_name,user_pwd,sex,create_time,update_time) values(%s,%s,%s,now(),now())" cursor = connection.cursor() cursor.execute(sql, [user_name, user_pwd, sex]) except Exception as e: success["success"] = "error" return render(request, template_name="pages/index.html", context=success, status=200) def delete(request): user_id = request.GET.get("userId") success = {"success": "success"} try: user = User.objects.get(user_id=user_id) user.delete() except Exception as e: success["success"] = "error" return render(request, template_name="pages/index.html", context=success, status=200) def update(request): user_id = request.GET.get("userId") user_name = request.GET.get("userName") user = User.objects.get(user_id=user_id) user.user_name = user_name user.save() return render(request, template_name="pages/index.html", context={"success": "success"}, status=200)
10、编辑接口地址连接信息,如下图所示:
11、配置前端跳转页面,如下图所示:
三、测试验证
四、总结发言
以上内容为简单示例内容,完整可用于投产的项目,还需要进行进一步的完善,有兴趣的同学可以再研究研究。