@rickyChen
2017-02-14T16:48:44.000000Z
字数 6183
阅读 2429
Python
Django
新建一个app
python manage.py startapp yourappname
新建一些目录,使该app拥有以下目录结构:
.
├── admin.py
├── __init__.py
├── migrations
│ ├── __init__.py
├── models.py
├── static
│ ├── yourappname
│ └── index.css
├── templates
│ └── yourappname
│ └── index.html
├── tests.py
├── urls.py
├── views.py
在settings.py中加入新建的app
INSTALLED_APPS = (
'grappelli',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'yourappname',
)
view.py
内容接口,返回经过渲染的html页面
from django.shortcuts import render
def book_display( request ):
return render( request, 'book/book_display.html' )
数据接口,获取一个接口的数据
from django.http import JsonResponse, HttpResponseBadRequest, HttpResponseServerError, HttpResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
import json
@csrf_exempt #防止Django中的csrf防护
@require_http_methods( [ "POST" ] )
def book_info( request ):
#获取POST请求中的数据
try:
body = json.loads( request.body )
except ValueError as e:
return HttpResponseBadRequest( 'request body couldn\'t be parsed' )
book = [ ... ]
return JsonResponse( { 'result' : book } )
#返回接口数据
urls.py
定义每个url指向的view.py里的接口信息
from django.conf.urls import url
from . import views
urlpatterns = [
url( r'^book_display/$', views.book_display, name='book_display' ),
url( r'^book_info/$', views.book_info, name='book_info' )
]
新建一个app(base),目录结构如下
.
├── admin.py
├── __init__.py
├── migrations
│ ├── __init__.py
├── models.py
├── static //存储整个Web的静态文件
│ ├── base
│ └── index.css
├── templates //存储公共静态html模版
│ └── base
│ └── index.html
├── tests.py
├── urls.py
├── views.py
在base/static/base/
目录下新建文件header.html
作为整个Web公共导航栏
header.html
文件内容如下
{% load staticfiles %}
<!DOCTYPE HTML>
<html>
<head>
<title>数据分析平台</title>
<link rel="stylesheet" href="{% static 'base/bootstrap/css/bootstrap.min.css' %}">
{% block js_content%}{% endblock %}
</head>
<body>
<div class="nav">
<div class="collapse navbar-collapse">
<div class="navbar-header">
<span class="navbar-brand" style="color:#fff">数据分析平台</span>
</div>
<ul class="nav nav-pills navbar-nav ">
<li>
<a href="{% block url_homepage%}/{% endblock%" role="button" >首页</a>
</li>
<li>
<a href="/project/register_project/" role="button">服务申请 </a>
</li>
</ul>
</div>
</div>
{% block page_content %}{% endblock %}
</body>
</html>
home.html
文件中公共模块使用代码如下:
{% extends "base/header.html" %} //模块调用语句
{% load staticfiles %}
{% block url_homepage %}#{% endblock %}
{% block js_content %}
{% endblock%}
{% block page_content %}
{% endblock%}
由实例得出公共模块使用说明
准备工作
新建templatetags
目录,与templates
同一目录。
在该目录下新建__init__.py
,空文件即可,表明这是一个python文件夹。
新建一个python文件,作为你的标签或过滤器存放的文件
mkdir templatetags
cd templatetags
touch __init__.py
自定义标签
定义
from django import template
register = template.Library()
@register.simple_tag
def request_nums(id):
nums = operate(id)
return nums
使用
{% load header_tags %}
<html>
<body>
...
{% request_nums id %}
</body>
</html>
过滤器
定义
from django import template
register = template.Library()
@register.filter
def cut_number(username):
import re
return re.sub('[0-9]+', '', username)
使用
{% load header_tags %}
<html>
<body>
...
{% username | cut_number %}
</body>
</html>
修改某app下model.py文件,创建与表相关的类
from __future__ import unicode_literals
from django.db import models
from django_enumfield import enum
class Publisher( models.Model ):
name = models.CharField( max_length=256, blank=True, null = True )
address = models.CharField( max_length=256, blank=True, null = True )
city = models.CharField( max_length=256, blank=True, null = True )
state_province = models.CharField( max_length=256, blank=True, null = True )
country = models.CharField( max_length=256, blank=True, null = True )
website = models.CharField( max_length=256, blank=True, null = True )
class Meta:
db_table = 'publisher'
同步数据库
python manage.py syncdb
//注意:Django 1.7 及以上的版本需要用以下命令
python manage.py makemigrations
python manage.py migrate
插入数据
from books.models import Publisher
p1 = Publisher(name='Apress', address='2855 Telegraph Avenue', city='Berkeley', state_province='CA', country='U.S.A.', website='http://www.apress.com/')
p1.save()
查询
获取全部对象
Publisher.objects.all()
根据条件查询
Publisher.objects.filter(name='Apress')
//查询名字为Apress的出版社
Publisher.objects.exclude(name='Apress')
//查询名字不为Apress的出版的
查询结果排序
Publisher.objects.filter(name='Apress').order_by("country")
Publisher.objects.filter(name='Apress').order_by("_country")
//结果按倒序排列
限定查询结果
Publisher.objects.filter(name='Apress')[10]
//相当于limit 10
更新
Publisher.objects.filter(id=52).update(name='Apress Publishing')
或
p = Publisher.objects.get(name='Apress') #先查询
p.name = 'Apress Publishing' #更新
p.save() #保存
删除
Publisher.objects.filter(country='USA').delete()
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'elk_portal',
#表名
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'hostname',
'PORT': 'port',
# There is no need to set option when database charset is utf8
'OPTION': {
# 'charset': 'utf8',
# 'init_command': 'SET character_set_client=\'utf8\';SET character_set_connection=\'utf8\';SET character_set_results=\'utf8\'',
# equals to 'init_command': 'SET NAMES \'utf8\'',
}
},
'agg_system':{
'ENGINE': 'django.db.backends.mysql',
'NAME': 'agg_system',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'hostname',
'PORT': 'port',
}
#这里新建了一个名为'agg_system'的路由出口
}
#-*- coding: utf-8 -*-
class MossDBRouter(object):
"""A router to control all database operations on models in
the myapp application"""
def db_for_read(self, model, **hints):
"Point all operations on myapp models to 'other'"
return self.__app_router(model)
def db_for_write(self, model, **hints):
"Point all operations on myapp models to 'other'"
return self.__app_router(model)
def allow_relation(self, obj1, obj2, **hints):
"Allow any relation if a model in myapp is involved"
return obj1._meta.app_label == obj2._meta.app_label
def allow_syncdb(self, db, model):
"Make sure the myapp app only appears on the 'other' db"
return self.__app_router(model) == db
def __app_router(self, model):
"""
为不同的app指定路由出口
"""
if model._meta.app_label == 'analysis':
return 'agg_system'
elif model._meta.app_label == 'report':
return 'agg_system'
else:
return 'default'
DATABASE_ROUTERS = ['portal.dbrouter.MossDBRouter']