Linux下Django+MySQL+Nginx
前言
本文详细介绍Python+Django+MySQL+uWSGI+Nginx开发环境(框架)在CentOS下的安装部署,曾经在部署过程中也遇到过各种各样的问题,经历几番挣扎终于跑通。这篇教程分享给需要的同学们,希望有所帮助(可能是目前为止最细致的教程了)。如遇其他问题欢迎留言讨论。
该架构下软件集合安装部署的顺序也是按照标题所示。
- Python
- Django
- MySQL
- Django+MySQL
- uWSGI+Django
- Nginx+uWSGI+Django
1_Python的安装和配置
如果你已有此环境那么可以跳过此步,Python版本为3.6.5(如果你已经安装了3.x基本上是没问题的),同时确保安装了pip工具即可。下面是python安装教程。https://blog.csdn.net/ShyLoneGirl/article/details/83017139
2_Django安装部署
2_1/3_使用pip工具安装django模块
执行命令
[root@VM_0_13_centos ~]# pip install django
******省略******
Successfully installed django-2.1.2 pytz-2018.5
Tips: 如果出现pip版本低需要升级时,执行如下命令升级pip
You are using pip version 9.0.1, however version 18.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
[root@VM_0_13_centos ~]# pip install --upgrade pip
******省略******
Uninstalling pip-9.0.1:
Successfully uninstalled pip-9.0.1
Successfully installed pip-18.1
2_2/3_创建应用
执行如下命令创建新的目录,创建新的工程,注意命令“django-admin startproject djotest .”的末尾有一个“点”
[root@VM_0_13_centos ~]# mkdir /home/test
[root@VM_0_13_centos ~]# cd /home/test/
[root@VM_0_13_centos test]# django-admin startproject djotest .
[root@VM_0_13_centos test]# ls
djotest manage.py
[root@VM_0_13_centos test]# python3 manage.py migrate
之后将会看到如下信息
Operations to perform:
Apply all migrations: admin, auth, contenttypes, 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 sessions.0001_initial… OK
2_3/3_启动服务测试
执行如下命令启动服务
[root@VM_0_13_centos test]# python3 manage.py runserver 0.0.0.0:8000
有如下输出
Performing system checks…
System check identified no issues (0 silenced).
July 06, 2018 - 11:46:37
Django version 2.0.7, using settings ‘djotest.settings’
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
这时可在浏览器中输入网址测试服务 [ip地址]:8000
Tips
如果遇到如图所示问题,同时在终端也出现错误码,此时可Ctrl+C回退到命令行,然后再在Settings里添加ALLOWED,如果遇到如图所示问题,需要添加ALLOWED,
执行命令
[root@VM_0_13_centos test]# vim djotest/settings.py
找到ALLOWED_HOSTS,[]内添加 ’*’ 如图。
保存退出(i进入编辑状态,:wq保存退出)后,重新启动服务
[root@VM_0_13_centos test]# python3 /home/test/manage.py runserver 0.0.0.0:8000
重新访问结果如图
则说明安装成功。
3_MySQL安装
3_1/4_添加源
执行命令,注意这个下载地址,可以到https://repo.mysql.com/找合适的版本。
[root@VM_0_13_centos test]# yum install https://repo.mysql.com/mysql80-community-release-el7-1.noarch.rpm
******省略******
Installed size: 31 k
Is this ok [y/d/N]: y
******省略******
Complete!
下载mysql
[root@VM_0_13_centos test]# yum install mysql-community-server -y
******省略******
Complete!
下载完成。
3_2/4_首次登陆及修改密码
首先启动数据库服务试一下
[root@VM_0_13_centos test]# service mysqld start
Redirecting to /bin/systemctl start mysqld.service
Ctrl+C退出,然后执行命令查看初始密码,
[root@VM_0_13_centos test]# grep 'temporary password' /var/log/mysqld.log
2018-07-06T13:24:54.141460Z 5 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: =!wi:<4%tsHn
然后使用默认密 =!wi:<4%tsHn 登陆,Linux下的密码输入是看不到****这样的位数的,确保输入完成后回车即可。
[root@VM_0_13_centos test]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.11
Copyright © 2000, 2018, Oracle and/or its affiliates. All rights reserved.
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>
到这里就登陆成功了,接下来要做的是修改密码。
mysql> ALTER USER 'root'@'localhost' IDEnTIFIED BY 'Test_001';
Query OK, 0 rows affected (0.07 sec)
退出并重新登陆
mysql> exit;
Bye
[root@VM_0_13_centos test]# mysql -uroot -p -P3306 -h127.0.0.1
Enter password:
******省略******
mysql>
这样,密码也修改好了,记住你的数据库密码!
3_3/4_创建数据库测试
启动MySQL查看数据库
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.00 sec)
创建一个新的数据库
mysql> create database mtestdb default charset=utf8;
Query OK, 1 row affected, 1 warning (0.05 sec)
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mtestdb |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.00 sec)
(务必)再创建一个名为barbers的数据库,以备下节使用
mysql> create database barbers;
Query OK, 1 row affected (0.19 sec)
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| barbers |
| information_schema |
| mtestdb |
| mysql |
| performance_schema |
| sys |
+--------------------+
6 rows in set (0.00 sec)
还可以可以使用命令查看一下,数据库内是空的。
mysql> use barbers;
mysql> show tables;
Tips数据库设计[非必要步骤,如果你足够熟悉数据库内容,可忽略这个Tips]
mysql> use barbers;
Database changed
mysql> create table mtesttable(Name varchar(20),Tel varchar(20),Address varchar(20));
Query OK, 0 rows affected (0.12 sec)
mysql> insert into mtesttable values('Allen','123456','黑龙江');
Query OK, 1 row affected (0.05 sec)
mysql> select * from mtesttable;
+-------+--------+-----------+
| Name | Tel | Address |
+-------+--------+-----------+
| Allen | 123456 | 黑龙江 |
+-------+--------+-----------+
1 row in set (0.00 sec)
3_4/4_启动数据库服务
执行如下命令设置启动MySQL服务,很关键。
[root@VM_0_13_centos test]# chkconfig mysqld on
Note: Forwarding request to 'systemctl enable mysqld.service'.
4_Django连接MySQL数据库
4_1/7_安装配置Pymysql模块
[root@VM_0_13_centos test]# pip install pymysql
******省略******
Successfully installed asn1crypto-0.24.0 cffi-1.11.5 cryptography-2.2.2 idna-2.7 pycparser-2.18 pymysql-0.9.2 six-1.11.0
将模块添加到django项目,编辑__init__.py文件
[root@VM_0_13_centos test]# cd djotest/
[root@VM_0_13_centos djotest]# vim __init__.py
写 入如下代码
import pymysql
pymysql.install_as_MySQLdb()
然后去找settings.py文件,修改
[root@VM_0_13_centos djotest]# vim settings.py
相同位置改成如下,注意中/英符号和代码对齐。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'barbers',
'USER': 'root',
'PASSWORD':'Test_001',
'HOST':'127.0.0.1',
'PORT':'3306',
}
}
然后执行如下代码
[root@VM_0_13_centos test]# python3 manage.py migrate
将会显示下面信息
Operations to perform:
Apply all migrations: admin, auth, contenttypes, 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 sessions.0001_initial… OK
4_2/7_在数据库中查看
启动数据库并登陆
[root@VM_0_13_centos test]# mysql -uroot -p -P3306 -h127.0.0.1
Enter password:
******省略******
mysql>
输入SQL语句,观察到barbers数据库内有10个表。对比3_3/4步(空表),Pymysql模块写入数据已经成功。
mysql> use barbers;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> show tables;
+----------------------------+
| Tables_in_barbers |
+----------------------------+
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
+----------------------------+
10 rows in set (0.00 sec)
4_3/7_创建超级用户
[root@VM_0_13_centos test]# python3 manage.py createsuperuser
Username (leave blank to use 'root'): dmuser
Email address: 可空
Password: Test_001
Password (again):
Superuser created successfully.
进行网页测试
[root@VM_0_13_centos test]# python3 manage.py runserver 0.0.0.0:8000
注意在浏览器上输入的地址应为 [ip地址]:8000/admin
可看到如图
输入账号密码登陆看到如下视图
至此,超级用户也创建成功。
4_4/7_创建应用
[root@VM_0_13_centos test]# python3 manage.py startapp barbershop
[root@VM_0_13_centos test]# ls
barbershop db.sqlite3 djotest manage.py
编辑settings文件,看下图,一点点也不要写错,修改后保存退出,如何保存退出上面有说。
[root@VM_0_13_centos test]# cd djotest/
[root@VM_0_13_centos djotest]# vim settings.py
修改models.py如图
[root@VM_0_13_centos djotest]# cd ../
[root@VM_0_13_centos test]# cd barbershop/
[root@VM_0_13_centos barbershop]# vim models.py
from django.db import models
# Create your models here.
class BarberInfo(models.Model):
barber_no = models.IntegerField(unique=True)
barber_name = models.CharField(max_length = 20)
barber_nickname = models.CharField(max_length = 20)
barber_address = models.CharField(max_length = 20)
执行命令
[root@VM_0_13_centos barbershop]# cd ../
[root@VM_0_13_centos test]# python3 manage.py makemigrations
Migrations for 'barbershop':
barbershop/migrations/0001_initial.py
- Create model BarberInfo
[root@VM_0_13_centos test]# python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, barbershop, contenttypes, sessions
Running migrations:
Applying barbershop.0001_initial... OK
4_5/7_数据库下查看
[root@VM_0_13_centos test]mysql -uroot -p -P3306 -h127.0.0.1
Enter password:
******省略******
mysql> use barbers;
******省略******
mysql> show tables;
结果如图所示,由10行变为11行,多了一个barbershop_barberinfo 的表
至此,django对数据库表操作实验完成。
4_6/7_编写数据操作
修改admin.py
[root@VM_0_13_centos test]# vim barbershop/admin.py
from django.contrib import admin
from barbershop.models import BarberInfo
# Register your models here.
class Barber_Admin(admin.ModelAdmin):
list_display = ['barber_no','barber_name','barber_nickname','barber_address']
admin.site.register(BarberInfo,Barber_Admin)
启动服务
[root@VM_0_13_centos test]# python3 manage.py runserver 0.0.0.0:8000
这时浏览器访问一下/admin
点击add,添加新的用户信息。
保存后可以看到数据列表
再次到数据库里查看一下,数据已经写入库啦。
[root@VM_0_13_centos test]# mysql -uroot -p -P3306 -h127.0.0.1
mysql> uses barbers;
mysql> select * from barbershop_barberinfo;
+----+-----------+-------------+-----------------+----------------+
| id | barber_no | barber_name | barber_nickname | barber_address |
+----+-----------+-------------+-----------------+----------------+
| 1 | 1 | 王铁柱 | Allen | 丹东 |
+----+-----------+-------------+-----------------+----------------+
1 row in set (0.00 sec)
可以看到这样就实现了操作MySQL数据库。
4_7/7_添加一个前端信息展示页
执行
[root@VM_0_13_centos test]# cd barbershop
[root@VM_0_13_centos barbershop]# mkdir templates/
[root@VM_0_13_centos barbershop]# ls
admin.py apps.py __init__.py migrations models.py __pycache__ templates tests.py views.py
[root@VM_0_13_centos barbershop]# vi templates/index.html
添加网页前端代码
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="my django testpage">
<meta name="author" content="xueliangwang">
<title>Welcome to my barbershop</title>
</head>
<body>
<h>This is barbers'info</h>
<table>
{% for bi in barbers_list %}
<tr>
<td>{{ bi.barber_no }}</td>
<td>{{ bi.barber_name }}</td>
<td>{{ bi.barber_nickname }}</td>
<td>{{ bi.barber_address }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
修改
[root@VM_0_13_centos test]# vim barbershop/views.py
添加
from django.shortcuts import render
from barbershop.models import BarberInfo
# Create your views here.
def Barber_index(request):
barbers_list = BarberInfo.objects.all()
return render(request,'index.html',{'barbers_list':barbers_list})
添加urls,亲注意不要写错哦。
[root@VM_0_13_centos test]# vim djotest/urls.py
from django.contrib import admin
from django.urls import path
from barbershop import views
urlpatterns = [
path('admin/', admin.site.urls),
path('barbershop/', views.Barber_index),
]
执行
[root@VM_0_13_centos test]# python3 manage.py makemigrations
[root@VM_0_13_centos test]# python3 manage.py migrate
启动服务
[root@VM_0_13_centos test]# python3 manage.py runserver 0.0.0.0:8000
访问 /barbershop如图
5_通过uWSGI启动
5_1/4_安装gcc,py-devel,uwsgi
必要的是需要c编译器
[root@VM_0_13_centos test]# yum install gcc-c++ -y
还有 python-devel,注意对应好版本啊不然会出大问题的。
[root@VM_0_13_centos test]# yum install python36u-devel.x86_64
******省略******
Is this ok [y/d/N]: y
******省略******
Complete!
安装 uWSGI
[root@VM_0_13_centos test]# pip install uwsgi
******省略******
Successfully installed uwsgi-2.0.17.1
5_2/4_测试uWSGI
[root@VM_0_13_centos test]# vim /home/test/utest.py
写入代码如下,注意格式也不要有问题,python讲对齐的。再次确定你使用的python版本,是否是3.x,语法还是有一丢丢区别的,2.x版本会出问题(python2.x的语法是 return “Hello World” )。
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return [b"Hello World"]
保存退出
输入命令启动uwsgi
[root@VM_0_13_centos ~]# uwsgi --http :8001 --wsgi-file /home/test/utest.py
开启服务,会出很多信息,
访问 [ip]:8001
5_3/4_uWSGI+Django测试
[root@VM_0_13_centos test]# uwsgi --http :8000 --module djotest.wsgi
访问 [ip]:8000/barbershop可以看到发廊信息。
5_4/4_将配置写入文件
创建配置文件
[root@VM_0_13_centos test]# vim ustart.ini
写入
[uwsgi]
socket = 127.0.0.1:9001
chdir = /home/test
wsgi-file = djotest/wsgi.py
module = djotest.wsgi
master = true
processses = 2
threads = 2
这下就可以通过执行配置文件来执行了
[root@VM_0_13_centos test]# uwsgi --ini ustart.ini
访问无问题
6_Nginx安装配置
6_1/2_安装Nginx
[root@VM_0_13_centos test]# yum install nginx -y
******省略******
Complete!
开启
[root@VM_0_13_centos test]# nginx -c /etc/nginx/nginx.conf
直接访问IP地址出现Nginx的Logo
6_2/2_配置Nginx
[root@VM_0_13_centos test]# vim /etc/nginx/nginx.conf
include /etc/nginx/uwsgi_params;
uwsgi_pass 127.0.0.1:9001;
uwsgi_param UWSGI_SCRIPT djotest.wsgi;
uwsgi_param UWSGI_CHDIR /home/test;
index index.html index.htm;
再次启动
[root@VM_0_13_centos test]# nginx -c /etc/nginx/nginx.conf
[root@VM_0_13_centos test]# uwsgi --ini ustart.ini
访问==[ip]/barbershop==
至此全部配置完成,接下来使用它来做开发吧。
结束语
整个过程虽然繁琐,但是每当遇到一个问题都会有相应的解决方案,仔细查找排错不要半途而废。希望对同学们有帮助。
.
.
.
.
.
.
-桃花仙人种桃树,又摘桃花换酒钱。
更多推荐
所有评论(0)