您好,登錄后才能下訂單哦!
定義數據模型
一、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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。