django 教程
2020-05-10 本文已影响0人
LoveToday2020
步骤一
1.搭建虚拟环境
a.安装virtualenv与virtualenvwrapper
# 虚拟环境库
pip install virtualenv
#虚拟环境管理器
pip install virtualenvwrapper
b.配置环境变量
打开.bash_profile
vim ~/.bash_profile
编辑.bash_profile
#打开
vim ~/.bash_profile
#添加环境变量
export WORKON_HOME=~/py_envs
# 路径使用which python或是which python3查找
export VIRTUALENVWRAPPER_PYTHON=/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
# 使用sudo find / -name virtualenvwrapper.h查看路径
source /Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh
# 使得.bash_profile立即生效
source ~/.bash_profile
c. 创建虚拟环境
# 创建虚拟环境目录
mkdir ~/py_envs
# 进入虚拟环境目录中
cd ~/py_envs
# 创建虚拟环境
virtualenv '自己要定义的名字'
d.一些其他的命令
# 激活虚拟环境
source ./bin/activate
# 退出虚拟环境
deactivate
# 删除环境
rmvirtualenv '虚拟环境名称'
# 通过wrapper创建工作空间
mkvirtualenv py_db
# 切换虚拟环境
workon '环境名称'
# 列出所有的虚拟环境
lsvirtualenv -b
# 查看所有命令
virtualenvwrapper -help
Mac 安装
首先进入到虚拟环境中并且激活
pip3 install Django==2.2
查看安装版本
python3 -m django --version
创建项目
django-admin startproject testdj
创建应用
# 切换到创建的项目
cd testdj
# 创建应用
python3 manage.py startapp mytest
启动服务
python manage.py runserver
项目URL配置
a. 在 testdj中的settings.py 中修改
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mytest',
]
b. testdj中的urls.py修改
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
urlpatterns = [
path('^admin/', admin.site.urls),
url('^', include('mytest.urls'))
]
c. mytest中新建urls.py 文件
from django.conf.urls import url
from mytest.views import *
urlpatterns = [
url('^index/$', index)
]
d. views.py中新增代码
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
# 返回响应报文
return HttpResponse('Hello world')
浏览器输入 127.0.0.1:8080/index
解决启动中的错误
Error: That port is already in use.说明端口被占用了
解决
1.打开终端。输入命令 ps aux | grep -I manage
2.找到python manage.py runserver对应的 pid(进程id,如图框中部分)。输入命令 kill -9 4988
这样就可以kill掉进程,释放端口号(free up port 8000)。如有多个,重复操作。
SSL任证
[Django开启https(不用nginx)]
pip install django-extensions
pip install django-werkzeug-debugger-runserver
pip install pyOpenSSL
添加到INSTALLED_APPS里
INSTALLED_APPS = [
...
'werkzeug_debugger_runserver', # 开启https需要的服务
'django_extensions', # 开启https需要的服务
...
]
启动https服务
python manage.py runserver_plus --cert server.crt 0.0.0.0:8000
不用https服务仅仅使用http
python manage.py runserver 0.0.0.0:8000