定义数据模型&访问数据库-创新互联
定义数据模型
我们提供的服务有:成都做网站、网站制作、微信公众号开发、网站优化、网站认证、昌吉ssl等。为超过千家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的昌吉网站制作公司一、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]: [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方法传数据成功,明文,数据量小
另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
分享题目:定义数据模型&访问数据库-创新互联
网站网址:http://scyanting.com/article/dishsh.html