Redhat7 python3 django安裝使用mysql mariadb

  • yum install mysql mysql-server -y
  • service mysql start  報錯
[root@hz-build-cloud-cbts02-okqvd ~]# service mysql start
Redirecting to /bin/systemctl start mysql.service
Failed to start mysql.service: Unit not found.


[root@hz-build-cloud-cbts02-okqvd ~]# mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
[root@hz-build-cloud-cbts02-okqvd ~]# ls /var/lib/mysql/
[root@hz-build-cloud-cbts02-okqvd ~]# vi /etc/my.cnf
[root@hz-build-cloud-cbts02-okqvd ~]# ls /var/lib/mysql/my.cnf
ls: cannot access /var/lib/mysql/my.cnf: No such file or directory
[root@hz-build-cloud-cbts02-okqvd ~]# ls /etc/init.d/mysql
ls: cannot access /etc/init.d/mysql: No such file or directory
  • 嘗試卸載mysql-server,安裝mariadb, 啓動mariadb服務即可。
[root@hz-build-cloud-cbts02-okqvd ~]# yum remove mysql-server
[root@hz-build-cloud-cbts02-okqvd ~]# yum erase mysql-community-common.x86_64
[root@hz-build-cloud-cbts02-okqvd ~]# yum list installed |grep mysql
mysql57-community-release.noarch   el7-9                    installed           
[root@hz-build-cloud-cbts02-okqvd ~]# yum erase mysql57-community-release.noarch

[root@hz-build-cloud-cbts02-okqvd ~]#  yum install mariadb  mariadb-libs mariadb-server -y
Loaded plugins: langpacks, product-id, search-disabled-repos, subscription-manager
This system is not registered with an entitlement server. You can use subscription-manager to register.
Package 3:mariadb-10.1.20-2.el7.x86_64 already installed and latest version
Package 3:mariadb-libs-10.1.20-2.el7.x86_64 already installed and latest version
Package 3:mariadb-server-10.1.20-2.el7.x86_64 already installed and latest version
Nothing to do
[root@hz-build-cloud-cbts02-okqvd ~]# systemctl start mariadb.service
[root@hz-build-cloud-cbts02-okqvd ~]# systemctl enable mariadb.service
Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb.service to /usr/lib/systemd/system/mariadb.service.
[root@hz-build-cloud-cbts02-okqvd ~]# 
[root@hz-build-cloud-cbts02-okqvd ~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 10.1.20-MariaDB MariaDB Server

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]>
  • mysql安裝成功後,啓用django服務,報錯如下,考慮安裝MySQL-python模塊:
  File "/usr/lib64/python3.4/site-packages/django/db/models/options.py", line 205, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/usr/lib64/python3.4/site-packages/django/db/__init__.py", line 33, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/usr/lib64/python3.4/site-packages/django/db/utils.py", line 202, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/usr/lib64/python3.4/site-packages/django/db/utils.py", line 110, in load_backend
    return import_module('%s.base' % backend_name)
  File "/usr/lib64/python3.4/importlib/__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/usr/lib64/python3.4/site-packages/django/db/backends/mysql/base.py", line 22, in <module>
    from MySQLdb.constants import CLIENT, FIELD_TYPE                # isort:skip
ImportError: No module named 'MySQLdb.constants'
[root@hz-build-cloud-cbts02-okqvd ~]# pip3 install MySQL-python
DEPRECATION: Python 3.4 support has been deprecated. pip 19.1 will be the last one supporting it. Please upgrade your Python as Python 3.4 won't be maintained after March 2019 (cf PEP 429).
Collecting MySQL-python
  Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-lr5nst8s/MySQL-python/setup.py", line 13, in <module>
        from setup_posix import get_config
      File "/tmp/pip-install-lr5nst8s/MySQL-python/setup_posix.py", line 2, in <module>
        from ConfigParser import SafeConfigParser
    ImportError: No module named 'ConfigParser'
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-lr5nst8s/MySQL-python/
You are using pip version 19.0.2, however version 19.0.3 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
[root@hz-build-cloud-cbts02-okqvd ~]# python3
Python 3.4.9 (default, Aug 14 2018, 21:28:57) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ConfigParser
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'ConfigParser'
>>> 
  • In Python 3, ConfigParser has been renamed to configparser for PEP 8 compliance. It looks like the package(MySQL-python) you are installing does not support Python 3. 嘗試安裝mysql-connector。
  • [root@hz-build-cloud-cbts02-okqvd ~]# pip3 install mysql-connector
    還是報相同錯誤。
  • 安裝pymysql,並修改settings.py
[root@hz-build-cloud-cbts02-okqvd ~]# pip3 install pymysql
import pymysql

pymysql.install_as_MySQLdb()
  • 測試mysql,用root用戶連接,輸入密碼後校驗失敗:
xxx@hz-build-cloud-cbts02-okqvd alice_django_cbts]$ mysql -u root -p
Enter password: 
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
  • 經查,mariadb默認的密碼爲空,爲了安全性考慮,修改root密碼:
  • update mysql.user set password=password("1234") where user="root"; 存儲的是密文密碼
  • update mysql.user set password="1234" where user="root"; 存儲的是明文密碼
xxx@hz-build-cloud-cbts02-okqvd alice_django_cbts]$ mysql -u root -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 22
Server version: 10.1.20-MariaDB MariaDB Server

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]> update mysql.user set password=password("1234") where user="root";
Query OK, 0 rows affected (0.00 sec)
Rows matched: 4  Changed: 0  Warnings: 0

MariaDB [(none)]> select user, host, password from mysql.user;
+------+---------------------------------------+-------------------------------------------+
| user | host                                  | password                                  |
+------+---------------------------------------+-------------------------------------------+
| root | localhost                             | *A4B6157319038724E3560894F7F932C8886EBFCF |
| root | hz-build-cloud-cbts02-okqvd.novalocal | *A4B6157319038724E3560894F7F932C8886EBFCF |
| root | 127.0.0.1                             | *A4B6157319038724E3560894F7F932C8886EBFCF |
| root | ::1                                   | *A4B6157319038724E3560894F7F932C8886EBFCF |
|      | localhost                             |                                           |
|      | hz-build-cloud-cbts02-okqvd.novalocal |                                           |
+------+---------------------------------------+-------------------------------------------+
6 rows in set (0.00 sec)

MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> exit;
Bye
  • 再次用新密碼1234登錄即可:
xxx@hz-build-cloud-cbts02-okqvd alice_django_cbts]$ mysql -u root -p1234
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 24
Server version: 10.1.20-MariaDB MariaDB Server

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]>
  • 創建數據庫:
xxx@hz-build-cloud-cbts02-okqvd alice_django_cbts]$ mysql -u root -p1234
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 26
Server version: 10.1.20-MariaDB MariaDB Server

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]> create database cbts_dashboard;
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]> exit;
Bye
  • 執行migrate:
xxx@hz-build-cloud-cbts02-okqvd alice_django_cbts]$ python3 manage.py migrate
System check identified some issues:

WARNINGS:
?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default'
	HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.0/ref/databases/#mysql-sql-mode
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, login, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying login.0001_initial... OK
  Applying sessions.0001_initial... OK
[xxx@hz-build-cloud-cbts02-okqvd alice_django_cbts]$ python3 manage.py makemigrations build_info
Migrations for 'build_info':
  build_info/migrations/0001_initial.py
    - Create model BuildStatus
[xxx@hz-build-cloud-cbts02-okqvd alice_django_cbts]$ python3 manage.py migrate build_info
System check identified some issues:

WARNINGS:
?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default'
	HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.0/ref/databases/#mysql-sql-mode
Operations to perform:
  Apply all migrations: build_info
Running migrations:
  Applying build_info.0001_initial... OK
  Applying build_info.0002_auto_20190305_1419... OK
  Applying build_info.0003_auto_20190305_1421... OK
[xxx@hz-build-cloud-cbts02-okqvd alice_django_cbts]$
  • 啓動django服務,報錯:
xxx@hz-build-cloud-cbts02-okqvd alice_django_cbts]$ python3 manage.py runserver 127.0.0.1:8080
Performing system checks...

System check identified no issues (0 silenced).
March 06, 2019 - 06:56:29
Django version 2.0.13, using settings 'alice_django_cbts.settings'
Starting development server at http://127.0.0.1:8080/
Quit the server with CONTROL-C.
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f2ffe114a60>
Traceback (most recent call last):
  File "/usr/lib64/python3.4/site-packages/django/utils/module_loading.py", line 20, in import_string
    return getattr(module, class_name)
AttributeError: 'module' object has no attribute 'SessionAuthenticationMiddleware'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib64/python3.4/site-packages/django/core/servers/basehttp.py", line 44, in get_internal_wsgi_application
    return import_string(app_path)
  File "/usr/lib64/python3.4/site-packages/django/utils/module_loading.py", line 17, in import_string
    module = import_module(module_path)
  File "/usr/lib64/python3.4/importlib/__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "/var/fpwork/alice/alice_django_cbts/alice_django_cbts/wsgi.py", line 16, in <module>
    application = get_wsgi_application()
  File "/usr/lib64/python3.4/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
    return WSGIHandler()
  File "/usr/lib64/python3.4/site-packages/django/core/handlers/wsgi.py", line 140, in __init__
    self.load_middleware()
  File "/usr/lib64/python3.4/site-packages/django/core/handlers/base.py", line 37, in load_middleware
    middleware = import_string(middleware_path)
  File "/usr/lib64/python3.4/site-packages/django/utils/module_loading.py", line 24, in import_string
    ) from err
ImportError: Module "django.contrib.auth.middleware" does not define a "SessionAuthenticationMiddleware" attribute/class

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib64/python3.4/site-packages/django/utils/autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "/usr/lib64/python3.4/site-packages/django/core/management/commands/runserver.py", line 140, in inner_run
    handler = self.get_handler(*args, **options)
  File "/usr/lib64/python3.4/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler
    handler = super().get_handler(*args, **options)
  File "/usr/lib64/python3.4/site-packages/django/core/management/commands/runserver.py", line 65, in get_handler
    return get_internal_wsgi_application()
  File "/usr/lib64/python3.4/site-packages/django/core/servers/basehttp.py", line 49, in get_internal_wsgi_application
    ) from err
django.core.exceptions.ImproperlyConfigured: WSGI application 'alice_django_cbts.wsgi.application' could not be loaded; Error importing module.
  • 經查,是Django版本的問題,1.10之前中間件的key爲MIDDLEWARE_CLASSES, 1.10之後,爲MIDDLEWARE。修改settings.py的配置即可:
MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
  • 啓動成功: 
xxx@hz-build-cloud-cbts02-okqvd alice_django_cbts]$ python3 manage.py runserver 127.0.0.1:8080
Performing system checks...

System check identified no issues (0 silenced).
March 06, 2019 - 07:05:00
Django version 2.0.13, using settings 'alice_django_cbts.settings'
Starting development server at http://127.0.0.1:8080/
Quit the server with CONTROL-C.

mariadb常用操作:

MariaDB [(none)]> show databases; 查看所有數據庫

MariaDB [(none)]> use dashboard; 使用名字爲dashboard的數據庫

MariaDB [dashboard]> show tables; 列出所有table信息

MariaDB [dashboard]> select * from test; 查詢test表的信息

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章