IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 大数据 -> 《Django开发教程》2.2 Django模型 -> 正文阅读

[大数据]《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 select,insert,update,delete on daozy.* to app@"%";
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


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

  大数据 最新文章
实现Kafka至少消费一次
亚马逊云科技:还在苦于ETL?Zero ETL的时代
初探MapReduce
【SpringBoot框架篇】32.基于注解+redis实现
Elasticsearch:如何减少 Elasticsearch 集
Go redis操作
Redis面试题
专题五 Redis高并发场景
基于GBase8s和Calcite的多数据源查询
Redis——底层数据结构原理
上一篇文章      下一篇文章      查看所有文章
加:2022-06-16 21:45:45  更:2022-06-16 21:47:40 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/29 8:00:19-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码