DjangoTask2
发布于: 刚刚
Django 项目
django-admin startproject 项目名
### 保证在manage.py的目录下执行
python manage.py runserver #启动自带服务器
python manage.py startapp 应用名 #创建应用
复制代码
0.1 users APP
# 新建app,setting注册
python manage.py atartapp users
# model.py
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
GENDER_CHOICES = (
("male","男"),
("female","女")
)
class UserProfile(AbstractUser):
gender = models.CharField(verbose_name = '性别',choices=GENDER_CHOICES, max_length=50)
mobile = models.CharField(max_length=11,unique=True,verbose_name='手机号码')
class meta:
verbose_name = '用户信息'
verbose_name_plural = verbose_name
def __str__(self):
return self.username
# settings.py
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
AUTH_USER_MODEL = "users.UserProfile"
复制代码
文件权限不够,在宝塔界面设置
![](https://static001.geekbang.org/infoq/0a/0a5cb16e25ae819d6fe5d163104afc19.png)
云服务器安全组和防火墙都需要开放端口
runserver 启动后,提示 Error: That port is already in use.
ps aux | grep -i manage #查看进程
sudo lsof -i:8000
kill -9 进程id
复制代码
1.将新建的 APP 与项目进行关联
修改的文件名是 setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog', # 新建APP
]
复制代码
2.创建超级用户前,同步数据库
python manage.py migrate # 同步表
python manage.py createsuperuser # 创建超级用户
复制代码
![](https://static001.geekbang.org/infoq/01/015467b17c3a14299c71e246002debf6.png)
3.修改后台语言
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
复制代码
4.APP 里创建表,然后,添加到后台显示
###### models.py #####
from django.db import models
# Create your models here.
class Blog(models.Model):
title = models.CharField(max_length=50, verbose_name='标题')
content = models.TextField(verbose_name='文章内容', default='')
count = models.IntegerField(verbose_name='阅读次数', default=0)
creat_time = models.DateTimeField(auto_now=True,verbose_name='创建时间')
class Meta:
verbose_name = '博客' # 表名注释
verbose_name_plural = verbose_name #没有这条语句,表名+s
def __str__(self):
return self.title # 标题内容显示表内title
###### admin.py #####
from django.contrib import admin
from .models import Blog
# Register your models here.
# admin.site.register(Blog)
@admin.register(Blog)
class BlogAdmin(admin.ModelAdmin):
list_display=('title','creat_time','count') # 选择性显示
# list_editable=('title','content')
复制代码
5.同步到数据库
python manage.py makemigrations
python manage.py migrate
复制代码
6.编写页面逻辑
1.添加页面模板文件夹
修改 settings.py
import os
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')], #在此添加路径
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
复制代码
添加路径前需要先导入 OS 库
修改 views.py 文件
from django.shortcuts import render
from .models import Blog # 使得html文件显示数据库的内容
# Create your views here.
def index(request): # request前端请求
blogs = Blog.objects.all() # 查询所有文章
print(blogs)
return render(request,'index.html',
{'blogs':blogs}
) # 将blog传到前端
def read_blog(request,id):
print(f'{id}:我是通过前端点击链接来的')
return render(request,'index.html')
复制代码
修改 urls.py 文件
from blog.views import index
urlpatterns = [
path('admin/', admin.site.urls),
path('',index,name='index'),
path('read/<int:id>',read_blog,name='read_blog'),
]
复制代码
将我们定义的方法引入,然后定义好访问什么路径来执行这个方法
在 templates 文件夹下创建一个 html 文件
<html>
<head>
<title>我的首页</title>
</head>
<body>
<h1>欢迎来到我的网站!</h1>
<ul>
{% for blog in blogs %}
<li>
<a href='{% url 'read_blog' blog.id %}'>{{blog.title}}</a>
</li>
<p>{{blog.creat_time}}</p>
{% endfor %}
</ul>
</body>
</html>
复制代码
7.添加文章详情页
content.html
<html>
<head>
<title>我的首页</title>
</head>
<body>
<h1 style='float:right'>
<a href='/'>回到首页<a>
</h1>
<h1>{{blog.title}}</h1>
<div>
{{blog.content}}
</div>
</body>
</html>
复制代码
编写业务逻辑 views.py
def read_blog(request,id):
blog = Blog.objects.get(id=id)
print(f'{id}:我是通过前端点击链接来的')
return render(request,'content.html',{'blog':blog})
复制代码
修改 urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('',index,name='index'),
path('read/<int:id>',read_blog,name='read_blog'),
]
复制代码
8.部署,安装 pymysql
安装 pymysql
pip install pymysql
复制代码
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'blog',
'USER': 'blog',
'PASSWORD': '密码',
'HOST': 'ip',
'PORT': '3306',
}
}
pip install pymysql # python控制mysql的包
mysql -uyuancong -p # 查看mysql是否安装成功 注意和自己的数据库名字一致
复制代码
宝塔修改数据库权限
修改_config>init_.py 文件
import pymysql
pymysql.install_as_MySQLdb()
复制代码
show databases; # 查询数据库
use blog
show tables #
exit()
复制代码
安装一下重要应用
1.supervisor
sudo apt install supervisor -y # 在ubantu非虚拟环境下装
复制代码
![](https://static001.geekbang.org/infoq/c0/c0f24501d94792d8388bc8c4ab08ebcd.png)
2.在虚拟环境安装 gunicorn
pip install gunicorn # 在虚拟环境下
复制代码
![](https://static001.geekbang.org/infoq/b1/b18dad791d22c910a4c47def7bee6932.png)
1.在项目根目录下创建一个 gunicorn_start.sh 文件
#!/bin/bash
NAME="MyBlog"
DJANGODIR=/home/tango/Desktop/DjangoDev/www/MyBlog #Django project directory 改
USER=tango # the user to run as 改
GROUP=tango # the group to run as 改
NUM_WORKERS=1 # how many worker processes should Gunicorn spawn
DJANGO_SETTINGS_MODULE=config.settings # which settings file should Django use 改
DJANGO_WSGI_MODULE=config.wsgi # WSGI module name 改
echo "Starting $NAME as `whoami`"
# Activate the virtual environment
cd $DJANGODIR
source /home/tango/Desktop/DjangoDev/env/bin/activate # 改
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DJANGODIR:$PYTHONPATH
# Create the run directory if it doesn't exist
RUNDIR=$(dirname $SOCKFILE)
test -d $RUNDIR || mkdir -p $RUNDIR
# Start your Django Unicorn
# Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon)
exec /home/tango/Desktop/DjangoDev/env/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ # 改
--name $NAME \
--workers $NUM_WORKERS \
--user=$USER --group=$GROUP \
--log-level=debug \
--log-file=-
复制代码
2.修改权限
chmod +x gunicorn_start.sh
复制代码
3.运行
./gunicorn_start.sh
复制代码
配置 Nginx
location /static/ {
alias /home/www/MyBlog/static/;
expires max;
access_log off;
log_not_found off;
}
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_redirect off;
if (!-f $request_filename) {
proxy_pass http://127.0.0.1:8000;
break;
}
}
复制代码
4. 配置 Supervisor
sudo vim /etc/supervisor/conf.d/myblog.conf
复制代码
复制代码
并写入如下内容
[program:myblog]
command = *******/gunicorn_start.sh
user = server
autostart=true
autorestart=true
redirect_stderr = true
stdout_logfile = /var/log/myblog.log
stderr_logfile=/var/log/myblog.err
复制代码
复制代码
user = server
同样也要修改成为自己的用户名
最后更新一下我们设置的一系列内容
sudo supervisorctl update
sudo supervisorctl reload
复制代码
5. 关于后台静态样式丢失问题
修改 settings.py
STATIC_ROOT = os.path.join(BASE_DIR, "static")
复制代码
复制代码
![](https://static001.geekbang.org/infoq/0d/0d57b0d20f39efdebf1bde5669e9a9b8.png)
并在项目目录下新建一个 static 的文件夹
运行如下命令进行静态文件收集
python manage.py collectstatic
复制代码
复制代码
其他
1.Sql 注入攻击的危害
非法读取、篡改、删除数据库中的数据
盗取用户的各类敏感信息、获取利益
通过修改数据库来修改网页上的内容
注入木马
划线
评论
复制
发布于: 刚刚阅读数: 2
ZERO
关注
还未添加个人签名 2021.06.12 加入
还未添加个人简介
评论