定义数据模型
一、Django定义数据模型在App中的models.py文件,数据库的表名称以类的形式来定义:
[root@133 web]# cd /opt/python/django/web/blog/ [root@133 blog]# vim models.py from django.db import models # Create your models here. class Host(models.Model): hostname = models.CharField(max_length = 50) ip = models.IPAddressField()
二、查看模型的语法和逻辑是否正确:python manage.py validate , 0 errors 没有语法错误
[root@133 blog]# cd /opt/python/django/web [root@133 web]# ls blog db.sqlite3 manage.py web [root@133 web]# python manage.py validate 0 errors found
三、管理数据库
初始化数据模型到数据库:python manage.py syncdb (默认使用的slqite数据库,在setting.py可以看到)
[root@133 web]# cd /opt/python/django/web/web/ [root@133 web]# vim settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(__file__))#base_dir是seting.py的上级目录的上级目录:/opt/python/django/web/ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } 前提是安装sqlite [root@133 web]# cd /opt/python/django/web/ [root@133 web]# python manage.py dbshell SQLite version 3.6.20 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> .tables sqlite> .exit #后台演示同步数据库的时候数据库的创建过程, [root@133 web]# python manage.py sqlall blog BEGIN; CREATE TABLE "blog_host" ( "id" integer NOT NULL PRIMARY KEY, "hostname" varchar(50) NOT NULL, "ip" char(15) NOT NULL ) ; COMMIT; #同步数据库,会创建表blog_host,创建管理用户 [root@133 web]# python manage.py syncdb Creating tables ... Creating table django_admin_log Creating table auth_permission Creating table auth_group_permissions Creating table auth_group Creating table auth_user_groups Creating table auth_user_user_permissions Creating table auth_user Creating table django_content_type Creating table django_session Creating table blog_host You just installed Django's auth system, which means you don't have any superusers defined. Would you like to create one now? (yes/no): yes Username (leave blank to use 'root'): root #创建管理用户 Email address: david-dai@zamplus.com #输入管理用户的邮箱 Password: #输入管理用户的密码 Password (again): Superuser created successfully. Installing custom SQL ... Installing indexes ... Installed 0 object(s) from 0 fixture(s) [root@133 web]# ll 总用量 48 drwxr-xr-x 3 root root 4096 1月 3 09:50 blog -rw-r--r-- 1 root root 34816 1月 3 10:12 db.sqlite3 #大小不为0 -rwxr-xr-x 1 root root 246 1月 1 23:11 manage.py drwxr-xr-x 2 root root 4096 1月 3 10:02 web
查看数据库
方法一:通过admin的页面查看数据库
1、启动django
[root@133 web]# nohup python manage.py runserver 11.65.140.13:8080 &
2、在chrome浏览器中访问:输入用户名root和密码,默认是看不到数据库,需要把表注册到admin.py中,admin才能识别
[root@133 blog]# cd /opt/python/django/web/blog/ [root@133 blog]# vim admin.py from django.contrib import admin from blog.models import Host #加载app应用models # Register your models here. class HostAdmin(admin.ModelAdmin): list_display = ['hostname', 'ip'] #固定属性,类似表中的字段 admin.site.register(Host,HostAdmin) #注册两个表, 刷新网页,多了一个host列,点击增加一个host,输入主机名和IP,点击保存,多了一个主机,可以查看
方法二:命令行方式登录查看数据库
[root@133 blog]# cd /opt/python/django/web/ [root@133 web]# ll 总用量 52 drwxr-xr-x 3 root root 4096 1月 3 10:28 blog -rw-r--r-- 1 root root 34816 1月 3 10:32 db.sqlite3 -rwxr-xr-x 1 root root 246 1月 1 23:11 manage.py -rw------- 1 root root 2125 1月 3 10:37 nohup.out drwxr-xr-x 2 root root 4096 1月 3 10:02 web [root@133 web]# sqlite3 db.sqlite3 SQLite version 3.6.20 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> .tables auth_group auth_user_user_permissions auth_group_permissions blog_host auth_permission django_admin_log auth_user django_content_type auth_user_groups django_session sqlite> select * from blog_host; 1|132|112.65.140.132 sqlite>.exit [root@133 web]# python manage.py dbshell sqlite> .tables auth_group auth_user_user_permissions auth_group_permissions blog_host auth_permission django_admin_log auth_user django_content_type auth_user_groups django_session sqlite> select * from blog_host; 1|132|112.65.140.132
访问数据库(一)
1、命令行的交互式方法(类似ipython登陆):
#命令行交互式登录 [root@133 web]# python manage.py shell /opt/amos/python2.7/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py:58: RuntimeWarning: SQLite received a naive datetime (2017-01-03 15:11:34.737126) while time zone support is active. RuntimeWarning) Python 2.7.3 (default, Jan 1 2017, 21:43:50) Type "copyright", "credits" or "license" for more information. IPython 5.1.0 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]: import sys In [2]: sys.path Out[2]: ['', '/opt/python/django/web', #项目的路径/opt/python/django/web成为环境变量 …… …… #导入表 In [3]: from blog.models import Host #blog 包中的modes.py文件,倒入类class:Host In [5]: Host.objects.all() Out[5]: [<Host: Host object>] #返回是一个列表[],每个元素是一个class #显示数据 In [6]: nodes = Host.objects.all() In [7]: nodes.values() #查看表中的内容 Out[7]: [{'ip': u'112.65.140.132', 'hostname': u'132', u'id': 1}] #增加数据添加一个host In [8]: Host(hostname='node02',ip='192.168.1.2') Out[8]: <Host: Host object> In [9]: n =Host(hostname='node02',ip='192.168.1.2') #实例化一个对象 In [10]: n.save() #保存n In [11]: nodes = Host.objects.all() In [12]: nodes.values() Out[12]: [{'ip': u'112.65.140.132', 'hostname': u'132', u'id': 1}, {'ip': u'192.168.1.2', 'hostname': u'node02', u'id': 2}] 另一种方法添加一个host In [13]: n = Host() In [18]: n.hostname = 'node03' In [19]: n.ip = '192.168.1.3' In [20]: n.save() #写入表 In [21]: nodes = Host.objects.all() In [22]: nodes.values() Out[22]: [{'ip': u'112.65.140.132', 'hostname': u'132', u'id': 1}, {'ip': u'192.168.1.2', 'hostname': u'node02', u'id': 2}, {'ip': u'192.168.1.3', 'hostname': u'node03', u'id': 3}] 浏览器查看多了一个node03 In [23]: n1 = nodes[0] In [24]: n1.hostname Out[24]: u'132' In [25]: n1.ip Out[25]: u'112.65.140.132' In [26]: n1.ip = '192.168.1.1' #直接修改n1的ip值 In [29]: n1.save() 浏览器刷新可以看到主机132的ip已经变为192.168.1.1 In [3]: from blog.models import Host In [4]: nodes = Host.objects.all() In [5]: nodes.values() Out[5]: [{'ip': u'192.168.1.1', 'hostname': u'132', u'id': 1}, {'ip': u'192.168.1.2', 'hostname': u'node02', u'id': 2}, {'ip': u'192.168.1.3', 'hostname': u'node03', u'id': 3}] In [6]: for i in nodes: print i.hostname 132 node02 node03 In [7]: for i in nodes: print i.hostname,i.ip 132 192.168.1.1 node02 192.168.1.2 node03 192.168.1.3
2、访问数据库二
通过视图文件views.py来访问数据
1、在urls.py文件里定义urls访问路径
[root@133 web]# cd /opt/python/django/web/web [root@133 web]# vim urls.py from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'web.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^blog/index/$', 'blog.views.index'), url(r'^db/$','blog.views.db'), #增加url配置文件 )
2、在views.py里定义访问方法
[root@133 web]# cd /opt/python/django/web/blog/ [root@133 blog]# vim views.py from django.shortcuts import render from django.http import HttpResponse from django.template import loader, Context from blog.models import Host #从blog.models导入Host # Create your views here. def index(request): t = loader.get_template('index.html') c = Context({}) return HttpResponse(t.render(c)) def db(req): h = Host() h.hostname = 'nodes04' h.ip = '192.168.1.4' h.save() return HttpResponse('OK')
网页访问:http://11.65.140.13:8080/db/ 返回ok
注意:
request或者req是形式参数,形参可以随便定义,不是非得叫request或者req,可以叫abc。
访问数据库(三)/数据库传递post和get
定义API
1、urls.py
2、views.py定义访问方法(API)
[root@133 blog]# vim views.py from django.shortcuts import render from django.http import HttpResponse from django.template import loader, Context from blog.models import Host # Create your views here. def index(request): t = loader.get_template('index.html') c = Context({}) return HttpResponse(t.render(c)) def db(req): h = Host() h.hostname = 'nodes04' h.ip = '192.168.1.4' h.save() return HttpResponse('OK') #添加collect方法 def collect(request): #if request.method == 'POST': if request.POST: hostname = request.POST.get('hostname') ip = request.POST.get('ip') host = Host() host.hostname = hostname host.ip = ip host.save() return HttpResponse('OK,OK') else: return HttpResponse('not data') #修改collect转发规则 [root@133 web]# cd /opt/python/django/web/web/ [root@133 web]# vim urls.py from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'web.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^blog/index/$', 'blog.views.index'), url(r'^db/$','blog.views.db'), url(r'^collect/$','blog.views.collect'), #增加collect转发规则 ) 浏览器访问: http://11.65.140.13:8080/collect/ 返回:not data 需要修改setting文件,注释中间件,才能使用curl传数据,否则django不识别 [root@133 web]# vim settings.py # 'django.middleware.csrf.CsrfViewMiddleware', #使用-d参数post方法传hostname和ip [root@133 blog]# curl -d hostname='node05' -d ip='192.168.1.5' http://112.65.140.133:8080/collect/ OK,OK 服务器端会用get方法提取hostname和ip,然后保存。 可以查看到node05
通过get方法,先修改配置,然后通过浏览器传递。get方法是明文的,不是很安全
[root@133 blog]# vim views.py from django.shortcuts import render from django.http import HttpResponse from django.template import loader, Context from blog.models import Host # Create your views here. def index(request): t = loader.get_template('index.html') c = Context({}) return HttpResponse(t.render(c)) def db(req): h = Host() h.hostname = 'nodes04' h.ip = '192.168.1.4' h.save() return HttpResponse('OK') def collect(request): #if request.method == 'POST': if request.POST: hostname = request.POST.get('hostname') ip = request.POST.get('ip') host = Host() host.hostname = hostname host.ip = ip host.save() return HttpResponse('OK,OK') elif: request.method == 'GET': #定义get方法 hostname = request.GET.get('hostname') ip = request.GET.get('ip') host = Host() host.hostname = hostname host.ip = ip host.save() return HttpResponse('OK...') else: return HttpResponse('not data')
浏览器访问,指定hostname=node07,ip=192.168.1.7:
http://11.65.140.13:8080/collect/?hostname=node07&ip=192.168.1.7
返回:OK...
http://11.65.140.13:8080/admin/blog/host/
发现host07已经存在,使用浏览器的get方法传数据成功,明文,数据量小
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。