定義數(shù)據(jù)模型
我們提供的服務(wù)有:成都做網(wǎng)站、網(wǎng)站制作、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認證、昌吉ssl等。為超過千家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學管理、有技術(shù)的昌吉網(wǎng)站制作公司一、Django定義數(shù)據(jù)模型在App中的models.py文件,數(shù)據(jù)庫的表名稱以類的形式來定義:
[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三、管理數(shù)據(jù)庫
初始化數(shù)據(jù)模型到數(shù)據(jù)庫:python manage.py syncdb (默認使用的slqite數(shù)據(jù)庫,在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 #后臺演示同步數(shù)據(jù)庫的時候數(shù)據(jù)庫的創(chuàng)建過程, [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; #同步數(shù)據(jù)庫,會創(chuàng)建表blog_host,創(chuàng)建管理用戶 [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 #創(chuàng)建管理用戶 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查看數(shù)據(jù)庫
方法一:通過admin的頁面查看數(shù)據(jù)庫
1、啟動django
[root@133 web]# nohup python manage.py runserver 11.65.140.13:8080 &2、在chrome瀏覽器中訪問:輸入用戶名root和密碼,默認是看不到數(shù)據(jù)庫,需要把表注冊到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) #注冊兩個表, 刷新網(wǎng)頁,多了一個host列,點擊增加一個host,輸入主機名和IP,點擊保存,多了一個主機,可以查看方法二:命令行方式登錄查看數(shù)據(jù)庫
[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訪問數(shù)據(jù)庫(一)
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成為環(huán)境變量 …… …… #導入表 In [3]: from blog.models import Host #blog 包中的modes.py文件,倒入類class:Host In [5]: Host.objects.all() Out[5]: [2、訪問數(shù)據(jù)庫二
通過視圖文件views.py來訪問數(shù)據(jù)
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')網(wǎng)頁訪問:http://11.65.140.13:8080/db/ 返回ok
注意:
request或者req是形式參數(shù),形參可以隨便定義,不是非得叫request或者req,可以叫abc。
訪問數(shù)據(jù)庫(三)/數(shù)據(jù)庫傳遞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轉(zhuǎn)發(fā)規(guī)則 [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轉(zhuǎn)發(fā)規(guī)則 ) 瀏覽器訪問: http://11.65.140.13:8080/collect/ 返回:not data 需要修改setting文件,注釋中間件,才能使用curl傳數(shù)據(jù),否則django不識別 [root@133 web]# vim settings.py # 'django.middleware.csrf.CsrfViewMiddleware', #使用-d參數(shù)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 服務(wù)器端會用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/
發(fā)現(xiàn)host07已經(jīng)存在,使用瀏覽器的get方法傳數(shù)據(jù)成功,明文,數(shù)據(jù)量小
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。