个人博客

A web front-end programmer's personal blog.

Django笔记第一部分

Django

Django 是一个可以使Web开发工作愉快并且高效的Web开发框架。 使用Django,使你能够以最小的代价构建和维护高质量的Web应用。

学习中用到的版本是 django-1.6.10,Python版本为2.7.6。这里整理下学习过程中遇到的问题和解决方法,方便以后快速回忆。

####开始一个项目

转到相应的创建目录,并运行命令django-admin.py startproject +项目名,如:

django-admin.py startproject mysite

运行后在当前目录中会生成如下内容文件:

.
└── mysite
    ├── manage.py
    └── mysite
        ├── __init__.py
        ├── settings.py
        ├── urls.py
        └── wsgi.py
2 directories, 5 files
  1. __init__.py :让 Python 把该目录当成一个开发包 (即一组模块)所需的文件。 这是一个空文件,一般你不需要修改它。
  2. manage.py :一种命令行工具,允许你以多种方式与该 Django 项目进行交互。 键入python manage.py help,看一下它能做什么。 你应当不需要编辑这个文件;在这个目录下生成它纯是为了方便。
  3. settings.py :该 Django 项目的设置或配置。 查看并理解这个文件中可用的设置类型及其默认值。
  4. urls.py:Django项目的URL设置。 可视其为你的django网站的目录。 目前,它是空的。

####运行服务器

命令行执行下面的命令,即可启动服务。

python manage.py runserver

默认情况下, runserver 命令在 8000 端口启动开发服务器,且仅监听本地连接。 要想要更改服务器端口的话,可将端口作为命令行参数传入

通过指定一个 IP 地址,你可以告诉服务器–允许非本地连接访问。 如果你想和其他开发人员共享同一开发站点的话,该功能特别有用。 0.0.0.0 这个 IP 地址,告诉服务器去侦听任意的网络接口,命令如下:

python manage.py runserver 0.0.0.0:8000

####如何创建一个简单的视图

在mysite文件夹中,创建一个叫做views.py的空文件,与urls.py、setting.py等在同级目录中。这个Python模块将包含这一章的视图。 请留意,Django对于view.py的文件命名没有特别的要求,它不在乎这个文件叫什么。但是根据约定,把它命名成view.py是个好主意,这样有利于其他开发者读懂你的代码,正如你很容易的往下读懂本文。

1、view.py 添加两个视图函数分别为hello 和home

from django.http import HttpResponse
def hello(request):
   return HttpResponse("Hello world")
def home(request):
   return HttpResponse('This is Home Page.')

2、urls.py 配置正则路径对应的视图函数

from django.conf.urls import patterns, include, url
from mysite.view import hello,home
urlpatterns = patterns('',
    url('^$', home),
    url('^hello/$', hello),
)

PS : from mysite.view import hello,home 中的每一个视图函数要与下面的url对应

  • view.py 文件为视图文件,通过在其中定义视图函数来完成我们的视图。
  • urls.py 文件为路由文件,通过在其中设置路由正则来指定不同的url用不同的视图函数来渲染。

引入外部的模板文件

1、修改view.py文件的内容如下:

from django.shortcuts import render_to_response
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    return render_to_response('mysite-tmp.html',{'current_date': now,'content' : 'hello world'})

其中 render_to_response 模块包含了 import HttpResponse 和 import template 两个模块。import datetime 为django中的获取时间模块

2、修改urls.py文件内容如下:

from django.conf.urls import patterns, include, url
from mysite.view import current_datetime
urlpatterns = patterns('',
    url('^time/$', current_datetime),
)

3、创建templates文件夹,用于存放模板文件,在templates下创建mysite-tmp.html 模板文件,内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>  </h1>
<p> <div class="page-content wc-container">

<div class="post">
	<h1>jquery中的animate与SVG的使用</h1>
	<span class="post-date">25 Mar 2015</span>
	<div class="post">
		<p>####<strong>jquery</strong>中的<strong>animate</strong>改变特殊属性</p>

通常我们通过如下形式使用animate:

animate( params, [duration], [easing], [callback] ) 

这个函数的关键在于指定动画形式及结果样式属性对象。这个对象中每个属性都表示一个可以变化的样式属性(如“height”、“top”或“opacity”)。注意:所有指定的属性必须用骆驼形式,比如用marginLeft代替margin-left.

关于animate还有种使用方式,可用于改变一些特殊的属性值,用法如下:

.animate( properties, options )

更多关于参数的问题,参考官方API

下面通过在SVG中创建基本图形并改变相关属性实现相应的效果为例,展示animate中改变特殊属性的方式:

#####核心HTML

<style>
.box{width:500px; height: 300px; border: 1px solid #ccc;}
</style>
<script src="jquery-1.11.2.min.js"></script>
<script src="jquery-tween.js"></script>
</head>
<body>
    <div class="box" id="div1"></div>
</body>

#####核心JS

<script>
    window.onload = function(){
        var oDiv1 = document.getElementById('div1');

        var oSvg = createXMLTag('svg',{
            'width' : '100%',
            'height' : '100%'
        });

        var oG = createXMLTag('g',{
            'style' : 'cursor: pointer'
        });

        var oEllipse = createXMLTag('ellipse',{
            'rx' : '50',
            'ry' : '30',
            'cx' : '150',
            'cy' : '150',
            'fill' : 'transparent',
            'stroke' : '#0cf',
            'stroke-width' : '2'
        });

        var oText = createXMLTag('text',{
            'x' : '150',
            'y' : '158',
            'font-size' : '20',
            'fill' : '#0cf',
            'text-anchor' : 'middle'
        });

        oText.innerHTML = 'SVG';

        oG.appendChild(oEllipse);
        oG.appendChild(oText);
        oSvg.appendChild(oG);

        $('#div1').append($(oSvg));
    
        $(oG).mouseenter(function(){


            $(this).find('ellipse').stop(true).animate({'rx':100},{
                duration: 500,
                easing : 'backIn',
                queue: false,
                step: function(now,fx) { 
                    fx.start = 50; 
                    $(this).attr("rx", now);
                },
                complete : function(){
                    console.log('complete in');
                }
            });
            $(this).find('ellipse').animate({'ry': 60},{
                duration: 500,
                queue: false,
                easing : 'easeInStrong',
                step: function(now,fx) { 
                    fx.start = 30; 
                    $(this).attr("ry", now);
                }
            });

            $(oText).stop(true).animate({'font-size':'30px'});
        }).mouseleave(function(event) {

            $(this).find('ellipse').stop(true).animate({'rx':50},{
                duration: 500,
                queue: false,
                easing : 'backIn',
                step: function(now,fx) {
                    fx.start = 100; 
                    $(this).attr("rx", now);
                },
                complete : function(){
                    console.log('complete out');
                }
            });
            $(this).find('ellipse').animate({'ry': 30},{
                duration: 500,
                queue: false,
                easing : 'easeInStrong',
                step: function(now,fx) { 
                    fx.start = 60; 
                    $(this).attr("ry", now);
                }
            });

            $(oText).stop(true).animate({'font-size':'20px'});
        });
        
        function createXMLTag(tagName,objAttr){
            var svgNS = 'http://www.w3.org/2000/svg';

            var oTag = document.createElementNS(svgNS,tagName);

            for(var attr in objAttr){
                oTag.setAttribute(attr,objAttr[attr]);
            }

            return oTag;
        }
    };
</script>

部分补充说明:

  1. 创建svg中的元素节点,通过封装 createXMLTag 函数,传入要创建的xml标签节点名称和要设置的属性对象值,来实现创建SVG中的元素节点
  2. 由于目前还没发现 通过animate( properties, options )这个方法,同时改变多个特殊的属性值,故示例中要同时改变 rx 和 ry 需要分别写两个animate函数。ps : 注意通过使用 queue: false 来避免队列,使两个animate的同时进行。
  3. animate( properties, options )方法中的step,默认是从 0 开始,可以通过 第二个参数 fx 来设置一个初始值 : fx.start = [初始值]
  4. 如果存在子节点与父节点的一些影响可使用 mouseenter和mouseleave事件。
  5. complete回调可能会执行多次,通过.stop(true)阻止complete函数执行多次。
  6. jquery-tween为jquery添加多种运动形式,代码附在最后。另外发现一个比较不错的运动库Transit,可方便的制作各种酷炫的运动包括3D效果。
  7. oText的animate添加stop(),阻止掉一些队列带来的影响。

#####jquery-tween.js

$.extend(jQuery.easing , {

    easeIn: function(x,t, b, c, d){  //加速曲线
        return c*(t/=d)*t + b;
    },
    easeOut: function(x,t, b, c, d){  //减速曲线
        return -c *(t/=d)*(t-2) + b;
    },
    easeBoth: function(x,t, b, c, d){  //加速减速曲线
        if ((t/=d/2) < 1) {
            return c/2*t*t + b;
        }
        return -c/2 * ((--t)*(t-2) - 1) + b;
    },
    easeInStrong: function(x,t, b, c, d){  //加加速曲线
        return c*(t/=d)*t*t*t + b;
    },
    easeOutStrong: function(x,t, b, c, d){  //减减速曲线
        return -c * ((t=t/d-1)*t*t*t - 1) + b;
    },
    easeBothStrong: function(x,t, b, c, d){  //加加速减减速曲线
        if ((t/=d/2) < 1) {
            return c/2*t*t*t*t + b;
        }
        return -c/2 * ((t-=2)*t*t*t - 2) + b;
    },
    elasticIn: function(x,t, b, c, d, a, p){  //正弦衰减曲线(弹动渐入)
        if (t === 0) { 
            return b; 
        }
        if ( (t /= d) == 1 ) {
            return b+c; 
        }
        if (!p) {
            p=d*0.3; 
        }
        if (!a || a < Math.abs(c)) {
            a = c; 
            var s = p/4;
        } else {
            var s = p/(2*Math.PI) * Math.asin (c/a);
        }
        return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
    },
    elasticOut: function(x,t, b, c, d, a, p){    //正弦增强曲线(弹动渐出)
        if (t === 0) {
            return b;
        }
        if ( (t /= d) == 1 ) {
            return b+c;
        }
        if (!p) {
            p=d*0.3;
        }
        if (!a || a < Math.abs(c)) {
            a = c;
            var s = p / 4;
        } else {
            var s = p/(2*Math.PI) * Math.asin (c/a);
        }
        return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
    },    
    elasticBoth: function(x,t, b, c, d, a, p){
        if (t === 0) {
            return b;
        }
        if ( (t /= d/2) == 2 ) {
            return b+c;
        }
        if (!p) {
            p = d*(0.3*1.5);
        }
        if ( !a || a < Math.abs(c) ) {
            a = c; 
            var s = p/4;
        }
        else {
            var s = p/(2*Math.PI) * Math.asin (c/a);
        }
        if (t < 1) {
            return - 0.5*(a*Math.pow(2,10*(t-=1)) * 
                    Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
        }
        return a*Math.pow(2,-10*(t-=1)) * 
                Math.sin( (t*d-s)*(2*Math.PI)/p )*0.5 + c + b;
    },
    backIn: function(x,t, b, c, d, s){     //回退加速(回退渐入)
        if (typeof s == 'undefined') {
           s = 1.70158;
        }
        return c*(t/=d)*t*((s+1)*t - s) + b;
    },
    backOut: function(x,t, b, c, d, s){
        if (typeof s == 'undefined') {
            s = 3.70158;  //回缩的距离
        }
        return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
    }, 
    backBoth: function(x,t, b, c, d, s){
        if (typeof s == 'undefined') {
            s = 1.70158; 
        }
        if ((t /= d/2 ) < 1) {
            return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
        }
        return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
    },
    bounceIn: function(x,t, b, c, d){    //弹球减振(弹球渐出)
        return c - this['bounceOut'](x,d-t, 0, c, d) + b;
    },       
    bounceOut: function(x,t, b, c, d){
        if ((t/=d) < (1/2.75)) {
            return c*(7.5625*t*t) + b;
        } else if (t < (2/2.75)) {
            return c*(7.5625*(t-=(1.5/2.75))*t + 0.75) + b;
        } else if (t < (2.5/2.75)) {
            return c*(7.5625*(t-=(2.25/2.75))*t + 0.9375) + b;
        }
        return c*(7.5625*(t-=(2.625/2.75))*t + 0.984375) + b;
    },      
    bounceBoth: function(x,t, b, c, d){
        if (t < d/2) {
            return this['bounceIn'](x,t*2, 0, c, d) * 0.5 + b;
        }
        return this['bounceOut'](x,t*2-d, 0, c, d) * 0.5 + c*0.5 + b;
    }
    
});
	</div>
</div>



<div class="related">
	<h4>近期文章(Related Posts)</h2>
	<ul class="posts">
	    
	    <li>
		  <span>12 Jun 2019 &raquo;</span>
		  <a href="http://coolnuanfeng.github.io/webpack">webpack 使用总结</a>
	    </li>
	    
	    <li>
		  <span>24 Jan 2019 &raquo;</span>
		  <a href="http://coolnuanfeng.github.io/webpush">web push 实现示例</a>
	    </li>
	    
	    <li>
		  <span>12 Dec 2018 &raquo;</span>
		  <a href="http://coolnuanfeng.github.io/javascript-design">前端设计模式</a>
	    </li>
	    
	</ul>
</div>


<div class="post-footer">
	<div class="column-1">
		
			<a href="http://coolnuanfeng.github.io/meta"><< Older</a>
		
	</div>
	<div class="column-2"><a href="http://coolnuanfeng.github.io/ ">Home</a></div>
	<div class="column-3">
		
			<a href="http://coolnuanfeng.github.io/django-partOne">Newer >></a>
		
	</div>
</div>

</div> </p> </body> </html>

4、配置setting.py文件,设置template的模板路径。 在setting.py中找到 import os 模块,在其下方加入如下内容:

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = (
    BASE_DIR+'/templates',
)

此时整个文件的目录结构如下:

.
├── manage.py
├── mysite
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── settings.py
│   ├── settings.pyc
│   ├── urls.py
│   ├── urls.pyc
│   ├── view.py
│   ├── view.pyc
│   ├── wsgi.py
│   └── wsgi.pyc
└── templates
    └── mysite-tmp.html

2 directories, 12 files

####链接MySQL数据库

1、修改view.py 内容如下:

from django.shortcuts import render_to_response
import datetime
import MySQLdb

def current_datetime(request):
    now = datetime.datetime.now()
    return render_to_response('mysite-tmp.html', {'current_date': now,'content' : 'hello world'})

def userInfo(request):
    db = MySQLdb.connect(user='root', db='mydata', passwd='123456', host='localhost')
    cursor = db.cursor()
    cursor.execute('SELECT username,age FROM users')
    name = [row[0] for row in cursor.fetchall()]
    age = [row[1] for row in cursor.fetchall()]
    db.close()
    return render_to_response('mysite-tmp.html', {'username': name,'age' : age})

2、urls.py修改为如下内容:

from django.conf.urls import patterns, include, url
from mysite.view import current_datetime,userInfo
urlpatterns = patterns('',
    url('^time/$', current_datetime),
    url('^user/$',userInfo),
)

3、配置setting.py中的DATABASES内容为:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydata',
    }
}

其中设置django数据库为MySQL,要连接的数据库名字为 mydata。

以上为django学习的第一部分,简单介绍了如何简单使用django制作页面,并从数据库读取数据渲染页面显示。更多更详细的内容请参考这里