《Django开发教程》2.2 Django模型

1、安装Mongodb

Ubuntu下安装 docker mongo

// 先安装docker,如果没有的话
# snap install docker
# docker pull mongo:latest
# docker images
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
mongo        latest    c8b57c4bf7e3   11 hours ago   701MB

启动mongo

# docker run -itd --name mongo -p 9000:9000 mongo
# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                                                  NAMES
f7e37b92cf3a   mongo     "docker-entrypoint.s…"   46 seconds ago   Up 19 seconds   0.0.0.0:9000->9000/tcp, :::9000->9000/tcp, 27017/tcp   mongo

mongo非常吃内存,如果内存不够可能会比较卡。

停止运行:

# docker mongo stop

非docker安装

# sudo apt install mongodb

安装过程会提示界面选择,按回车就可以了,安装完成后需要重启一下系统,然后mongo服务才会自动运行起来。

修改绑定的地址和端口:

# vim /etc/mongodb.conf
bind_ip = 0.0.0.0
port = 9999

bind_ip:0.0.0.0表示绑定所有地址,127.0.0.1表示本地可访问。

查看服务:

root@hecs-131173:~# ps -ef|grep mongo
mongodb    857     1  0 22:48 ?        00:00:00 /usr/bin/mongod --unixSocketPrefix=/run/mongodb --config /etc/mongodb.conf

开启服务

sudo service mongodb start

停止服务

sudo service mongodb stop

重启服务

sudo service mongodb restart

命令行连接,我们创建一个管理员用户admin,超级用户root, 和一个普通用户app用于业务数据读写。

# mongo --port 9999
MongoDB shell version v3.6.8
connecting to: mongodb://127.0.0.1:9999/
Implicit session: session { "id" : UUID("efe5a036-9e9b-42b9-abec-7cc59e27949d") }
MongoDB server version: 3.6.8
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
	http://docs.mongodb.org/
Questions? Try the support group
	http://groups.google.com/group/mongodb-user
Server has startup warnings: 
2022-06-15T22:54:22.928+0800 I STORAGE  [initandlisten] 
2022-06-15T22:54:22.928+0800 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2022-06-15T22:54:22.929+0800 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2022-06-15T22:54:23.906+0800 I CONTROL  [initandlisten] 
2022-06-15T22:54:23.906+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2022-06-15T22:54:23.906+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2022-06-15T22:54:23.906+0800 I CONTROL  [initandlisten] 
> db.createUser({ user: "admin", customData: {description:"admin"}, pwd: "123456", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]})
Successfully added user: {
	"user" : "admin",
	"customData" : {
		"description" : "admin"
	},
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		}
	]
}
 > db.auth("admin", "abc!@#123")
1

cusomData字段,为任意内容,例如可以为用户全名介绍;

roles字段,指定用户的角色,可以用一个空数组给新用户设定空角色。在roles字段,可以指定内置角色和用户定义的角色。

超级用户的role有两种,userAdmin或者userAdminAnyDatabase(比前一种多加了对所有数据库的访问,仅仅是访问而已)。

db是指定数据库的名字,admin是管理数据库。

不能用admin数据库中的用户登录其他数据库。注:只能查看当前数据库中的用户,哪怕当前数据库admin数据库,也只能查看admin数据库中创建的用户。

创建一个不受访问限制的超级用户:

> db.createUser({user: "root", pwd:"123456", roles: ["root"]})
Successfully added user: { "user" : "root", "roles" : [ "root" ] }
> db.auth("root", "123456")
1

创建一个业务数据库管理员用户:

> use daozy
switched to db daozy
> db.createUser({user:"app", pwd:"123456",customData:{name:'daozy'},roles:[{role:"readWrite",db:"daozy"}, 'read']})
Successfully added user: {
	"user" : "app",
	"customData" : {
		"name" : "daozy"
	},
	"roles" : [
		{
			"role" : "readWrite",
			"db" : "daozy"
		},
		"read"
	]
}
> db.auth("app", "123456")
1

数据库用户角色:read、readWrite;

数据库管理角色:dbAdmin、dbOwner、userAdmin;

集群管理角色:clusterAdmin、clusterManager、4. clusterMonitor、hostManage;

备份恢复角色:backup、restore;

所有数据库角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase

超级用户角色:root

内部角色:__system

Read:允许用户读取指定数据库

readWrite:允许用户读写指定数据库

dbAdmin:允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile

userAdmin:允许用户向system.users集合写入,可以在指定数据库里创建、删除和管理用户

clusterAdmin:只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限。

readAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读权限

readWriteAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读写权限

userAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的userAdmin权限

dbAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的dbAdmin权限。

root:只在admin数据库中可用。超级账号,超级权限

查看创建的用户:

> show users
{
	"_id" : "daozy.app",
	"userId" : UUID("49329ade-9ea8-4f6b-9ba4-7f507c66b6c8"),
	"user" : "app",
	"db" : "daozy",
	"customData" : {
		"name" : "daozy"
	},
	"roles" : [
		{
			"role" : "readWrite",
			"db" : "daozy"
		},
		{
			"role" : "read",
			"db" : "daozy"
		}
	]
}
> use admin
switched to db admin
> show users
{
	"_id" : "admin.admin",
	"userId" : UUID("a8df7499-18f3-4dee-b7c9-41fe8825f35e"),
	"user" : "admin",
	"db" : "admin",
	"customData" : {
		"description" : "admin"
	},
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		}
	]
}
{
	"_id" : "admin.root",
	"userId" : UUID("892acf52-39ed-4081-b635-a5b1fe201158"),
	"user" : "root",
	"db" : "admin",
	"roles" : [
		{
			"role" : "root",
			"db" : "admin"
		}
	]
}

修改密码:

> use admin
> db.changeUserPassword("username", "xxx")

修改密码和用户信息

> db.runCommand({updateUser:"username",pwd:"xxx",customData:{title:"xxx"}})

删除数据库用户

> use admin
> db.dropUser('user001')

修改配置为连接需要验证:

# vim /etc/mongodb.conf
auth = true
# sudo service mongodb restart

换一台电脑,试一试远程登录:

# mongo www.daozy.net:9999/admin -u admin
MongoDB shell version v3.6.8
Enter password: 
connecting to: mongodb://www.daozy.net:9999/admin
Implicit session: session { "id" : UUID("dcf08731-c745-4826-90fb-967ddd5e4d28") }
MongoDB server version: 3.6.8
> show databases
admin   0.000GB
config  0.000GB
local   0.000GB
> show users
{
	"_id" : "admin.admin",
	"userId" : UUID("a8df7499-18f3-4dee-b7c9-41fe8825f35e"),
	"user" : "admin",
	"db" : "admin",
	"customData" : {
		"description" : "admin"
	},
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		}
	]
}
{
	"_id" : "admin.root",
	"userId" : UUID("892acf52-39ed-4081-b635-a5b1fe201158"),
	"user" : "root",
	"db" : "admin",
	"roles" : [
		{
			"role" : "root",
			"db" : "admin"
		}
	]
}

192.168.1.100: 你的mongodb所在服务器IP地址。
admin: 要连接到的数据库。

django 配置 mongodb

数据库配置

第一步:在settings.py中配置mongodb和mysql,配置如下(可以同时使用mysql和mongodb):

 DATABASES = {
        'default': {
            'ENGINE': 'mongodb',
            'NAME': 'daozy',
            'ENFORCE_SCHEMA': False,
            'CLIENT': {
                'host': '192.168.1.100',
                'port': 9999,
                'username': 'daozy',
                'password': 'password',
                'authSource': 'db-name',
                'authMechanism': 'SCRAM-SHA-1'
            },
            'LOGGING': {
                'version': 1,
                'loggers': {
                    'djongo': {
                        'level': 'DEBUG',
                        'propagate': False,                        
                    }
               },
          },
      }
 }

django连接mongodb

import mongoengine

# 连接mongodb中数据库名称为mongodb的数据库
conn = mongoengine.connect("mongodb")

2、安装 mysql

安装软件

# sudo apt install mysql-server

检查进程运行情况

# ps -ef|grep mysql
mysql     4744     1  0 19:16 ?        00:00:00 /usr/sbin/mysqld --daemonize --pid-file=/run/mysqld/mysqld.pid

登录mysql数据库可以通过如下命令,默认没有密码。

# mysql -u root -p
Enter password: 
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql> exit
Bye

-u 表示选择登陆的用户名, -p 表示登陆的用户密码,现在是mysql数据库是没有密码的,Enter password:处直接回车,就能够进入mysql数据库。

初始化数据库

为了确保数据库的安全性和正常运转,对数据库进行初始化操作。这个初始化操作涉及下面5个步骤。

(1)安装验证密码插件。

(2)设置root管理员在数据库中的专有密码。

(3)随后删除匿名账户,并使用root管理员从远程登录数据库,以确保数据库上运行的业务的安全性。

(4)删除默认的测试数据库,取消测试数据库的一系列访问权限。

(5)刷新授权列表,让初始化的设定立即生效。

下面操作如果出现错误:Failed! Error: SET PASSWORD has no significance for user ‘root‘@‘localhost‘ as the authe,
可以先修改root用户的密码:

# mysql
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password by 'mynewpassword';
Query OK, 0 rows affected (0.01 sec)
mysql> exit
Bye

在开始:

# mysql_secure_installation

Securing the MySQL server deployment.

Connecting to MySQL using a blank password.

VALIDATE PASSWORD PLUGIN can be used to test passwords

and improve security. It checks the strength of password

and allows the users to set only those passwords which are

secure enough. Would you like to setup VALIDATE PASSWORD plugin?    # 要安装验证密码插件吗?

Press y|Y for Yes, any other key for No: N    # 这里我选择N

# Change the password for root ? ((Press y|Y for Yes, any other key for No) : N  #如果前面已经单独设置过密码了,会出现这个选择,选择N

Please set the password for root here.

New password:   # 输入要为root管理员设置的数据库密码

Re-enter new password:   # 再次输入密码

By default, a MySQL installation has an anonymous user,

allowing anyone to log into MySQL without having to have

a user account created for them. This is intended only for

testing, and to make the installation go a bit smoother.

You should remove them before moving into a production

environment.

Remove anonymous users? (Press y|Y for Yes, any other key for No) : y     # 删除匿名账户

Success.

Normally, root should only be allowed to connect from

'localhost'. This ensures that someone cannot guess at

the root password from the network.

Disallow root login remotely? (Press y|Y for Yes, any other key for No) :   y   # 禁止root管理员从远程登录,这里我没有禁止

... skipping.

By default, MySQL comes with a database named 'test' that

anyone can access. This is also intended only for testing,

and should be removed before moving into a production

environment.

Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y   # 删除test数据库并取消对它的访问权限

- Dropping test database...

Success.

- Removing privileges on test database...

Success.

Reloading the privilege tables will ensure that all changes

made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y   # 刷新授权表,让初始化后的设定立即生效

Success.

All done!

上面禁用了root用户远程登陆访问,如果我们想远程访问需要创建一个新用户:

# mysql -u root -p
Enter password: 
mysql> CREATE USER 'test'@'%' IDENTIFIED BY '123456';
Query OK, 0 rows affected (0.00 sec)

test:用户名,localhost:本地访问, 123456:密码
localhost:%, 表示不限制访问地址。

我们来测试一下连接:

# mysql -u test -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.38-0ubuntu0.18.04.1 (Ubuntu)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
+--------------------+
1 row in set (0.00 sec)

你还可以从其他电脑上进行登陆测试。

# mysql -u test -p

修改服务器对外地址和端口

mysql默认端口3306,大家都知道容易被暴力破解,我们为了安全起见可以考虑修改一个其他端口。

# vim /etc/mysql/mysql.conf.d/mysqld.cnf 
bind-address            = 0.0.0.0    	# 所有网卡对外
port                           = 11111 		# 改成自己想要的

重启服务:

# service mysql restart

查看一下端口:

root@hecs-131173:/etc/mysql# netstat -natp|grep 11111
tcp        0      0 0.0.0.0:11111            0.0.0.0:*               LISTEN      31485/mysqld

创建一个业务数据库

# mysql -u root -p
Enter password: 
mysql> CREATE DATABASE IF NOT EXISTS daozy CHARACTER SET UTF8;
Query OK, 1 row affected, 1 warning (0.00 sec) 

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| daozy              |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

给业务用户app分配读写daozy数据库的权限:

# mysql -u root -p
Enter password: 
mysql> grant create,alter,references,index,select,insert,update,delete on daozy.* to app@"%";
Query OK, 0 rows affected (0.01 sec)

撤销权限,如果需要,这里肯定不需要:

mysql> revoke all on daozy.* from app@'%';
Query OK, 0 rows affected (0.01 sec)

我们手动在数据库daozy中创建一个表:

CREATE TABLE user ( \
	id int(11) NOT NULL AUTO_INCREMENT COMMENT '主键', \
	name varchar(64) COMMENT '艺名', \
	PRIMARY KEY (id) \
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户信息表';

连接数据库:

# mysql -u app -p
Enter password: 
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| daozy              |
| information_schema |
+--------------------+
2 rows in set (0.00 sec)
mysql> use daozy
mysql> CREATE TABLE user ( \
    -> id int(11) NOT NULL AUTO_INCREMENT COMMENT '主键', \
    -> name varchar(64) COMMENT '艺名', \
    -> PRIMARY KEY (id) \
    -> ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户信息表';
ERROR 1142 (42000): CREATE command denied to user 'app'@'localhost' for table 'daozy_user'
mysql> exit
Bye

如果遇到上面这个错误,说明用户app没有创建表结构的权限,需要赋予其权限,退出使用root账号登陆。

# mysql -u root -p
Enter password: 
mysql> grant create on daozy.* to app@"%";
Query OK, 0 rows affected (0.01 sec)
mysql> exit
Bye

重新使用app账号登陆:

# mysql -u app -p
Enter password:
mysql> use daozy
Database changed
mysql> CREATE TABLE user ( \
    -> id int(11) NOT NULL AUTO_INCREMENT COMMENT '主键', \
    -> name varchar(64) COMMENT '艺名', \
    -> PRIMARY KEY (id) \
    -> ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户信息表';
Query OK, 0 rows affected, 2 warnings (0.02 sec)

创建数据库成功,我们插入一条记录:

mysql> show tables;
+-----------------+
| Tables_in_daozy |
+-----------------+
| user      |
+-----------------+
1 row in set (0.01 sec)

mysql> insert into user(name) values('wangteacher');
Query OK, 1 row affected (0.01 sec)

mysql> select * from user;
+----+-------------+
| id | name        |
+----+-------------+
|  1 | wangteacher |
+----+-------------+
1 row in set (0.00 sec)

最后清理战场:

mysql> drop table user;
ERROR 1142 (42000): DROP command denied to user 'app'@'localhost' for table 'user'

权限不够,我们通过root用户删除表:

# mysql -u root -p
Enter password:
mysql> drop table daozy.user;
Query OK, 0 rows affected (0.01 sec)

django连接mysql

# python3 -m pip install pymysql

如果在requirements.txt有配置

pymysql==1.0.2

可以这样安装:

# python3 -m pip install -r requirements.txt

settings.py配置:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',    # 数据库引擎
        'NAME': 'daozy', # 数据库名称
        'HOST': '127.0.0.1', # 数据库地址,本机 ip 地址 127.0.0.1
        'PORT': 11111, # 端口
        'USER': 'app',  # 数据库用户名
        'PASSWORD': '123456', # 数据库密码
    }
}

这个时候看django启动日志,可能会报错:django连接MySQL报错Did you install mysqlclient?
虽然本地已安装了 PyMySQL 驱动,但 Django 连接 MySQL 时仍默认使用 MySQLdb 驱动,但 MySQLdb 并不支持 Python3,所以需要手动在项目中进行配置。

在views.py同级目录下的__init__.py文件中增加如下代码:

import pymysql
pymysql.install_as_MySQLdb()

如果报:You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run ‘python manage.py migrate’ to apply them.

执行:

$ python3 manage.py migrate   # 创建表所有结构

3、读写数据库

创建modle,增加一个文件:models.py

$ cd HelloWorld/
$ tree
.
|-- HelloWorld
|   |-- __init__.py
|   |-- asgi.py
|   |-- models.py
|   |-- settings.py
|   |-- urls.py
|   `-- wsgi.py
`-- manage.py

接下来在 settings.py 中找到INSTALLED_APPS这一项,如下:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'HelloWorld',               # 添加此项
)

在文件中写:

from django.db import models


class User(models.Model):
    name = models.CharField(max_length=20)

User代表数据库中表的名字。name:表列

创建或者更新表结构:

$ python3 manage.py makemigrations HelloWorld  # 让 Django 知道我们在我们的模型有一些变更
$ python3 manage.py migrate HelloWorld   # 创建表结构

检查数据库中是否有表HelloWorld_User

mysql> show tables;
+----------------------------+
| Tables_in_daozy            |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| HelloWorld_User                 |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
+----------------------------+
11 rows in set (0.00 sec)

如果我们要修改表结构,需要重新来一次,如下操作:
在models.py删除对应的Model类的代码。
删除==/应用/migrations==目录下对应的临时py文件。
在数据库中django_migrations表中删除对应的记录。
在数据库中删除对应的数据表。

上一课 2.1 Django模版
下一课 2.3 Django表单
《Django开发教程》目录大纲

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

道知极限编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值