django实现前后台交互实例

yipeiwu_com6年前Python基础

本文介绍了django实现前后台交互实例,分享给大家,希望对大家有所帮助

准备工作:

前端框架:AngularJS+bootstap

数据库:sqlite3

前端代码:
index.html

<!DOCTYPE html> 
<html> 
  <head> 
    <link href="/WebApi/scripts/bootstrap/dist/css/bootstrap.min.css" rel="external nofollow" rel="stylesheet" type="text/css" /> 
    <script type="text/javascript" src="/WebApi/scripts/angular/angular.min.js"></script> 
    <script type="text/javascript" src="/WebApi/controller/controller.js"></script> 
    <script type="text/javascript" src="/WebApi/service/service.js"></script> 
    <title>hello</title> 
  </head> 
  <body ng-app="myApp" ng-controller="myCtrl"> 
    <h2>hello world!</h2> 
     
<!--   <form role="form"> --> 
    <table> 
      <tr> 
        <td> 
          <div class="form-group"> 
            <input type="text" class="form-control" id="name"  
          placeholder="请输入用户名" ng-model="username"> 
          </div> 
        </td> 
      </tr> 
      <tr> 
        <td> 
          <div class="form-group"> 
            <input type="passwd" class="form-control" id="name"  
          placeholder="请输入密码" ng-model="password"> 
          </div> 
        </td> 
      </tr> 
      <tr> 
        <td> 
          <button type="button" class="btn btn-primary" ng-click="my_submit()">保存</button> 
        </td> 
      </tr> 
    </table> 
<!--   </form> 
 --> 
 
    <p class="text-danger">[[ result ]]</p> 
  </body> 
</html> 

controller.js

var app = angular.module("myApp", []); 
app.config( 
  function($interpolateProvider) { 
    $interpolateProvider.startSymbol('[['); 
    $interpolateProvider.endSymbol(']]'); 
  })  
  .config(['$httpProvider', function($httpProvider) { 
    $httpProvider.defaults.xsrfCookieName = 'csrftoken'; 
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; 
}]); 
app.controller("myCtrl", ["$scope", "service", function($scope, service) { 
  $scope.result = ""; 
  $scope.my_submit = function() { 
    console.log($scope.username); 
    console.log($scope.password); 
    service.do_save_info($scope.username, $scope.password, function(response){ 
      console.log(response); 
      $scope.result = response.result; 
    }); 
  }; 
}]); 

service.js

app.service("service", ["$http", function($http) { 
  this.do_save_info = function(username, password, callback) { 
    $http({ 
      method: 'POST', 
      url: '/do_save_info', 
      data: { 
        'username': username, 
        'password': password 
      }, 
      headers: {'Content-Type': undefined}, 
    }).success(function(response){ 
      callback(response); 
    }); 
  }; 
}]); 

后端代码:

urls.py

from django.conf.urls import patterns, include, url 
 
urlpatterns = patterns('app.views', 
  url(r'^index$', 'index'), 
  url(r'^/index$', 'index'), 
  url(r'^$', 'index'), 
  url(r'^/$', 'index'), 
  url(r'^do_save_info$', 'do_save_info'), 
) 

views.py

from django.shortcuts import render_to_response 
from django.template import RequestContext 
from django.http import HttpResponse 
from django.views.decorators.csrf import ensure_csrf_cookie, csrf_exempt 
import json 
import models 
 
# Create your views here. 
@ensure_csrf_cookie 
def index(request): 
  return render_to_response('static/index.html', 
    context_instance=RequestContext(request)) 
 
def do_save_info(request): 
  result = {'result':'save success'} 
  try: 
    data = json.loads(request.body) 
    username = data.get("username", None) 
    password = data.get("password", None) 
    models.do_save_info(username, password) 
  except Exception, e: 
    result['result'] = 'save error' 
  return HttpResponse(json.dumps(result)) 

models.py

#!/bin/python 
# -*- coding: utf-8 -*- 
 
import os 
import sys 
import sqlite3 
 
def do_save_info(username, password): 
  db_path = os.path.normpath('/home/zhubao/Code/django_code/hello/db.sqlite3') 
  try: 
    conn = sqlite3.connect(db_path) 
    sql = "insert into t_user(username, password) values('%s', '%s')" % (username, password) 
    conn.execute(sql) 
    conn.commit() 
    conn.close() 
    print 'save success...' 
  except Exception, e: 
    print '------', str(e) 
    try: 
      conn.close() 
    except Exception, e: 
      pass 

t_user表结构:

create table t_user(username varchar(255), password varchar(255)); 

页面演示:

刚打开页面如下:


输入数据,点击保存:


后台查看数据库:

可以看到,已经保存在数据库里面了。

这只是个小示例,在此不考虑页面排版和安全性问题。。。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现通过解析域名获取ip地址的方法分析

Python实现通过解析域名获取ip地址的方法分析

本文实例讲述了Python实现通过解析域名获取ip地址的方法。分享给大家供大家参考,具体如下: 从网上查找的一些资料,特此做个笔记 案例1: def getIP(domain):...

简单谈谈python基本数据类型

int(整型) 在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647 在64位系统上,整数的位数为64位,取值范围为...

Python函数参数类型及排序原理总结

这篇文章主要介绍了Python函数参数类型及排序原理总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Python中函数的参数问题有...

使用 python pyautogui实现鼠标键盘控制功能

pyautogui是一个可以控制鼠标和键盘的python库,类似的还有pywin32。 pyautogui的安装 pip3 install python3-xlib 依赖库 sudo a...

pytorch多GPU并行运算的实现

Pytorch多GPU运行 设置可用GPU环境变量。例如,使用0号和1号GPU' os.environ["CUDA_VISIBLE_DEVICES"] = '0,1' 设置模型...