Django框架封装外部函数示例

yipeiwu_com5年前Python基础

本文实例讲述了Django框架封装外部函数。分享给大家供大家参考,具体如下:

需求:我们来模拟用户登录,验证是否输入正确的用户名和密码

1.构建登录表单

  <form method="post">
    <p>用户名:<input type="text" name="username"></p>
    <p>密码:<input type="password" name="pwd"></p>
    <p><input type="submit" value="提交"></p>
    <hr>
  </form>
  <p>
    登录状态提示:{{ result }}
  </p>

2.程序判断

#coding:utf-8
from django.shortcuts import render,render_to_response
# Create your views here.
from django.http import HttpResponse
def hi(request):
  msg = {'result':''}
  if userLogin(request.POST.get('username'),request.POST.get('pwd')):
    msg['result'] = '登录成功'
  else:
    msg['result'] = '登录失败'
  return render_to_response("index.html",msg)
#判断用户登录函数
def userLogin(username,pwd):
  if username == 'jack' and pwd == '123':
    return True
  else:
    return False

验证如果输入的用户名为jack,密码为123,就提示“登录成功”

3.一个小意外

如果你提交上面的表单,会报如下错误,这个是Django框架的验证机制

这里写图片描述

这是为了防止跨域攻击,我们这里暂时不研究这个安全机制,来到settings.py文件注释掉下面这行

这里写图片描述

这样就不会报上面的那个错误了。

如果用户输正确的用户名和密码(jack、123),模板上{{ result }} 就是提示“登录成功”。

4.如何把userLogin函数写到外部?

在views.py文件同级下新建user.py文件

这里写图片描述

然后在views.py里

先引入

import user

使用

user.userLogin()

完整的views.py代码如下:

#coding:utf-8
from django.shortcuts import render,render_to_response
# Create your views here.
from django.http import HttpResponse
import user
def hi(request):
  msg = {'result':''}
  if user.userLogin(request.POST.get('username'),request.POST.get('pwd')):
    msg['result'] = '登录成功'
  else:
    msg['result'] = '登录失败'
  return render_to_response("index.html",msg)

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

相关文章

Python 迭代,for...in遍历,迭代原理与应用示例

本文实例讲述了Python 迭代,for...in遍历,迭代原理与应用。分享给大家供大家参考,具体如下: 迭代是访问集合元素的一种方式。什么时候访问元素,什么时候再迭代,比一次性取出集合...

Python脚本利用adb进行手机控制的方法

一.  adb 相关命令:   1. 关闭adb服务:adb kill-server   2. 启动adb服务  adb start-server   3. 查询当前...

Python3 实现随机生成一组不重复数并按行写入文件

笔主在做一个项目要生成一组随机有序的整型数字,并按行输出到文本文件使用,恰好开始学习Python3,遂决定直接使用Python3解决 思路:与随机数相关的函数都要使用到random这个系...

Django应用程序入口WSGIHandler源码解析

前言 WSGI 有三个部分, 分别为服务器(server), 应用程序(application) 和中间件(middleware). 已经知道, 服务器方面会调用应用程序来处理请求, 在...

Python 下载及安装详细步骤

Python 下载及安装详细步骤

安装python分三个步骤: *下载python *安装python *检查是否安装成功 1、下载Python (1)python下载地址https://www.python.org/d...