Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Define the data model & access the database

2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Define the data model

1. Django defines the models.py file of the data model in App, and the table name of the database is defined in the form of classes:

[root@133 web] # cd / opt/python/django/web/blog/ [root@133 blog] # vim models.pyfrom django.db import models# Create your models here.class Host (models.Model): hostname = models.CharField (max_length = 50) ip = models.IPAddressField ()

Second, check whether the syntax and logic of the model are correct: python manage.py validate, 0 errors has no syntax errors

[root@133 blog] # cd / opt/python/django/web [root@133 web] # lsblog db.sqlite3 manage.py web [root@133 web] # python manage.py validate0 errors found

III. Manage databases

Initialize the data model to the database: python manage.py syncdb (slqite database used by default, which can be seen in setting.py)

[root@133 web] # cd / opt/python/django/web/web/ [root@133 web] # vim settings.pyimport osBASE_DIR = os.path.dirname (os.path.dirname (_ _ file__)) # base_dir is the parent directory of seting.py 's parent directory: / opt/python/django/web/DATABASES = {'default': {' ENGINE': 'django.db.backends.sqlite3',' NAME': os.path.join (BASE_DIR) 'db.sqlite3'),}} only if sqlite [root @ 133 web] # cd / opt/python/django/web/ [root@133 web] # python manage.py dbshellSQLite version 3.6.20Enter ".help" for instructionsEnter SQL statements terminated with a "is installed "sqlite > .tablessqlite > .exit # background demonstrates the process of database creation when synchronizing the database, [root@133 web] # python manage.py sqlall blogBEGIN;CREATE TABLE" blog_host "(" id "integer NOT NULL PRIMARY KEY," hostname "varchar (50) NOT NULL," ip "char (15) NOT NULL); COMMIT # synchronize the database, create table blog_host, create administrative user [root@133 web] # python manage.py syncdb Creating tables... Creating table django_admin_logCreating table auth_permissionCreating table auth_group_permissionsCreating table auth_groupCreating table auth_user_groupsCreating table auth_user_user_permissionsCreating table auth_userCreating table django_content_typeCreating table django_sessionCreating table blog_hostYou just installed Django's auth system, which means you don't have any superusers defined.Would you like to create one now? (yes/no): yesUsername (leave blank to use 'root'): root # create administrative user Email address: david-dai@zamplus.com # enter administrative user's mailbox Password: # enter administrative user's password Password (again): Superuser created successfully. Installing custom SQL... Installing indexes... Installed 0 object (s) from 0 fixture (s) [root@133 web] # ll Total amount 48drwxr-xr-x 3 root root 4096 January 3 09:50 blog-rw-r--r-- 1 root root 34816 January 3 10:12 db.sqlite3 # size not 0-rwxr-xr-x 1 root root 246 January 1 23:11 manage.pydrwxr-xr-x 2 root root 4096 January 3 10:02 web

View the database

Method 1: view the database through the page of admin

1. Start django

[root@133 web] # nohup python manage.py runserver 11.65.140.13 8080 &

2. Access in the chrome browser: enter the user name root and password. The database cannot be seen by default. You need to register the table in admin.py before admin can recognize it.

[root@133 blog] # cd / opt/python/django/web/blog/ [root@133 blog] # vim admin.pyfrom django.contrib import adminfrom blog.models import Host # load app application models# Register your models here.class HostAdmin (admin.ModelAdmin): list_display = ['hostname',' ip'] # fixed attribute, similar to the field admin.site.register (Host,HostAdmin) # in the table, register two tables, refresh the web page, and add a host column Click to add a host, enter the host name and IP, and click Save. If you have one more host, you can view it.

Method 2: log in and view the database on the command line

[root@133 blog] # cd / opt/python/django/web/ [root@133 web] # ll Total usage 52drwxr-xr-x 3 root root 4096 January 3 10:28 blog-rw-r--r-- 1 root root 34816 January 3 10:32 db.sqlite3-rwxr-xr-x 1 root root 246 January 1 23:11 manage.py-rw- 1 root root 2125 January 3 10:37 nohup.outdrwxr-xr-x 2 root root 4096 January 3 10:02 web [root@133 web] # sqlite3 db.sqlite3 SQLite version 3.6.20Enter ".help" for instructionsEnter SQL statements terminated with a " "sqlite > .tablesauth _ group auth_user_user_permissionsauth_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.132sqlite > .exit [root@133 web] # python manage.py dbshellsqlite > .tablesauth _ group auth_user_user_permissionsauth_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 |

Access to Database (1)

1. Command-line interactive method (similar to ipython login):

# Command Line Interactive Login [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 RuntimeWarning 11applv 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 sysIn [2]: sys.pathOut [2]: [','/ opt/python/django/web', # the path / opt/python/django/web of the project becomes an environment variable. …… # Import table In [3]: modes.py file in from blog.models import Host # blog package, pour class class:Host In [5]: Host.objects.all () Out [5]: [] # return is a list [] Each element is a class# display data In [6]: nodes = Host.objects.all () In [7]: nodes.values () # View the contents of the table Out [7]: [{'ip': utilisation 112.65.140.132,' hostname': uplink 132, utilisation: 1}] # add a hostIn [8]: Host (hostname='node02') Ip='192.168.1.2') Out [8]: In [9]: n = Host (hostname='node02',ip='192.168.1.2') # instantiate an object In [10]: n.save () # Save nIn [11]: nodes = Host.objects.all () In [12]: nodes.values () Out [12]: [{'ip': utilisation 112.65.140.132' 'hostname': upright 132, upright: 1}, {' ip': upright 192.168.1.2, 'hostname': upright Node02' Another way to add a hostIn [13]: n = Host () In [18]: n.hostname = 'node03'In [19]: n.ip =' 192.168.1.3'In [20]: n.save () # write table In [21]: nodes = Host.objects.all () In [22]: nodes.values () Out [22]: [{'ip': upright 112.65.140.132' 'hostname': upright 132, upright: 1}, {' ip': upright 192.168.1.2, 'hostname': upright 02, upright: 2}, {' ip': upright 192.168.1.3, 'hostname': upright 03' The browser views an extra node03In [23]: N1 = nodes [0] In [24]: n1.hostnameOut [24]: u'132'In [25]: n1.ip Out [25]: u'112.65.140.132'In [26]: n1.ip = '192.168.1.1' # directly modify the IP value of N1 In [29]: n1.save () browser refresh can see that the ip of host 132has been Changed to 192.168.1.1In [3]: from blog.models import HostIn [4]: nodes = Host.objects.all () In [5]: nodes.values () Out [5]: [{'ip': uplink 192.168.1.1' 'hostname': uplink 132, ubiquitous: 1}, {' ip': upright 192.168.1.2, 'hostname': upright: 02, upright: 2}, {' ip': upright 192.168.1.3, 'hostname': upright: 03, utilisation: 3}] In [6]: for i in nodes: print i.hostname132node02node03In [7]: for i in nodes: print i.hostname I.ip132 192.168.1.1node02 192.168.1.2node03 192.168.1.3

2. Access database 2

Access data through the view file views.py

1. Define the urls access path in the urls.py file

[root@133 web] # cd / opt/python/django/web/web [root@133 web] # vim urls.pyfrom django.conf.urls import patterns, include, urlfrom django.contrib import adminadmin.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'), # add url configuration file)

2. Define the access method in views.py

[root@133 web] # cd / opt/python/django/web/blog/ [root@133 blog] # vim views.pyfrom django.shortcuts import renderfrom django.http import HttpResponsefrom django.template import loader Contextfrom blog.models import Host# imports Host# Create your views here.def index (request) from blog.models: 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')

Web access: http://11.65.140.13:8080/db/ returns ok

Note:

Request or req are formal parameters, and formal parameters can be defined freely. They don't have to be called request or req, but can be called abc.

Visit the database (3) / transfer post and get to the database

Define API

1 、 urls.py

2. Views.py defines the access method (API)

[root@133 blog] # vim views.pyfrom django.shortcuts import renderfrom django.http import HttpResponsefrom django.template import loader Contextfrom 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') # add collect method 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') # modify collect forwarding rules [root@133 web] # cd / opt/python/django/web/web/ [root@133 web] # vim urls.pyfrom django.conf.urls import patterns, include, urlfrom django.contrib import adminadmin.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') # add collect forwarding rules) browser access: http://11.65.140.13:8080/collect/ returned: not data needs to modify setting file Annotation middleware can be used to transmit data using curl, otherwise django does not recognize [root@133 web] # vim settings.py# 'django.middleware.csrf.CsrfViewMiddleware',# using the-d parameter post method to pass hostname and IP [root @ 133blog] # curl-d hostname='node05'-d ip='192.168.1.5' http://112.65.140.133:8080/collect/OK,OK server will use the get method to extract hostname and ip And save it. You can view the node05

Through the get method, modify the configuration first, and then pass it through the browser. The get method is plaintext and not very secure.

[root@133 blog] # vim views.pyfrom django.shortcuts import renderfrom django.http import HttpResponsefrom django.template import loader Contextfrom 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': # define the get method 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')

Browser access, specify hostname=node07,ip=192.168.1.7:

Http://11.65.140.13:8080/collect/?hostname=node07&ip=192.168.1.7

Return: OK...

Http://11.65.140.13:8080/admin/blog/host/

Found that host07 already exists, using the browser's get method to transmit data successfully, plaintext, a small amount of data

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report