django基础
项目笔记
创建项目
django-admin startproject tedu_note
创建应用
python manage.py startapp user
创建数据库并指定编码为utf8
create database tedu_note1 default charset utf8;
#csrf
{% csrf token %}
# 局部防范
from django.views.decorators.csrf import csrf_exempt
setting配置文件
"""
Django settings for tedu_note1 project.
Generated by 'django-admin startproject' using Django 2.2.12.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '4y201*d@pey)w1*w983vhq^dj1&d37yy!qixvd6f*8yd6bx%qt'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'user',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'tedu_note1.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'tedu_note1.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mytest',
'USER':'root',
'PASSWORD':'123456',
'HOST':'101.132.151.37',
'PORT':'3306',
# 'NAME':'mytest',
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
models文件
from django.db import models
# Create your models here.
class User(models.Model):
username = models.CharField('用户名',max_length=30,unique=True)
password = models.CharField('密码',max_length=32)
created_time = models.DateTimeField('创建时间',auto_now_add=True)
updated_time = models.DateTimeField('更新时间时间',auto_now=True)
from django.db import models
from user.models import User
# Create your models here.
class Note(models.Model):
title = models.CharField('标题',max_length=100)
content = models.TextField('内容')
created_time = models.DateTimeField('创建时间',auto_now_add=True)
updated_time = models.DateTimeField('更新时间',auto_now = True)
user = models.ForeignKey(User,on_delete=models.CASCADE)
views.py
from django.shortcuts import render,HttpResponse,HttpResponseRedirect
from .models import User
import hashlib
# Create your views here.
def reg_views(request):
if request.method == 'GET':
if request.session.get('username') and request.session.get('uid'):
return HttpResponseRedirect('/index/')
# return HttpResponse('已经登录了')
c_username = request.COOKIES.get('username')
c_uid = request.COOKIES.get('uid')
if c_uid and c_username:
request.session['username'] = c_username
request.session['uid'] = c_uid
return HttpResponseRedirect('/index/')
# return HttpResponse('已登录')
return render(request,'user/register.html')
if request.method == 'POST':
username = request.POST['username']
password_1 = request.POST['password_1']
password_2 = request.POST['password_2']
if password_1 != password_2:
return HttpResponse('密码不一致')
m = hashlib.md5()
m.update(password_2.encode())
password_m = m.hexdigest()
old_user = User.objects.filter(username=username)
if old_user:
return HttpResponse('用户名已注册')
try:
user=User.objects.create(username=username,password=password_m)
except Exception as e:
print(e)
return HttpResponse('用户名已注册')
request.session['username'] = username
request.session['uid'] = user.id
#TODO 修改session存储时间为一天
return HttpResponseRedirect('/index/')
def login_view(request):
if request.method == 'GET':
return render(request,'user/login.html')
elif request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
try:
user = User.objects.get(username=username)
except Exception as e:
print(e)
return HttpResponse('用户名或密码错误')
m = hashlib.md5()
m.update(password.encode())
if m.hexdigest() != user.password:
return HttpResponse('用户名或者密码错误')
# 记录会话状态
request.session['username'] = username
request.session['uid'] = user.id
resp = HttpResponseRedirect('/index/')
# resp = HttpResponse('登陆成功')
if 'remember' in request.POST:
resp.set_cookie('username',username,3600*24*3)
resp.set_cookie('uid',user.id,3600*24*3)
return resp
缓存
python manage.py createcachetable
CACHES = {
'default':{
'BACKEND':'django.core.cache.backends.db.DatabaseCache',
'LOCATION':'my_cache_table',
'TIMEOUT':300,
'OPTIONS':{
'MAX_ENTRIES':300,
'CULL_FREQUENCY':2,
}
}
}
# 路由实现缓存
from django.views.decorators.cache import cache_page
urlpatterns = [
path('foo/',cache_page(60)(my_view)),
]
中间件
from django.utils.deprecation import MiddlewareMixin
class MyMW(MiddlewareMixin):
def process_request(self,request):
print('My MW process_request do - - - -')
def process_view(self,request,callback,callback_args,callback_kwargs):
print('MyMW process_views do ---')
def process_response(self,request,response):
print('MyMW process_response do ---')
return response
#ip 访问禁止++++++++++++++++++
class VisitLimt(MiddlewareMixin):
visit_times = {}
def process_request(self,request):
ip_address = request.META['REMOTE_ADDR']
path_url = request.path_info
if not re.match('^/test',path_url):
return
times = self.visit_times.get(ip_address,0)
print('ip',ip_address,'已经访问',times)
self.visit_times['ip_address'] = times + 1
if times < 5:
return
return HttpResponse('您已经访问过了'+str(times) + '次,访问被静止')
登陆验证
def check_login(func):
def wrap(request,*args,**kwargs):
if 'username' not in request.session or 'uid' not in request.session:
#检查cookies
c_username = request.COOKIES.get('username')
c_uid = request.COOKIES.get('uid')
if not c_username or not c_uid:
return HttpResponseRedirect('/user/login')
else:
request.session['username'] = c_username
request.session['uid'] = c_uid
return func(request,*args,**kwargs)
return wrap
#分页
pagintor = Paginator(object_list,per_page)
参数
- object_list 需要分数据的对象列表
- per_page 每页数据个数
返回值
- Paginator 的对象
- count: 需要分页数据的数据总数
- num_pages:分页后的页面总数
- page_range: 从一开始的range对象,用于记录当前面码数
- per_page 每页数据的个数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>分页</title>
</head>
<body>
{% for p in c_page %}
<p>
{{ p }}
</p>
{% endfor %}
{% if c_page.has_previous %}
<a href="/test_page?page={{ cpage.previous_page_number }}">上一页</a>
{% else %}
上一页
{% endif %}
{% for p_num in paginator.page_range %}
{% if p_num == c_page.number %}
{{ p_num }}
{% else %}
<a href="test_page?page={{ p_num }}">{{ p_num }}</a>
{% endif %}
{% endfor %}
{% if c_page.has_next %}
<a href="/test_page?page={{ cpage.next_page_number }}">下一页</a>
{% else %}
下一页
{% endif %}
</body>
</html>
def test_page(request):
page_num = request.GET.get('page',1)
all_data = ['a','b','c','d','e']
# 初始化paginator
paginator = Paginator(all_data,2)
c_page = paginator.page(int(page_num))
return render(request,'test_page.html',locals())
#项目部署
# x项目迁移
settings.py修改
DEBUG=False
ALLOWED_HOSTS=['网站域名']
sudo scp -r /home/django/mysite
root@公网ip:/home/root/xxx
uwsgi安装
第一步:sudo apt-get install python3-dev
第二步:sudo apt-get install python3-pip
第三部:sudo pip3 install uwsgi
uwsgi.ini 配置
[uwsgi]
http=127.0.0.1:8000
chdir=/home/tedu_note1
wsgi-file=tedu_note1/wsgi.py
process=2
threads=2
# 服务的pid记录文件
pidfile=uwsgi.pid
# 服务的目志文件位置
daemonize=uwsgi.log
# 开启主进程管理模式
master=true
--启动uwsgi
cd到uwsgi配置文件所在的目录
uwsgi --ini uwsgi.ini
-- 停止uwsgi
cd到uwsgi配置文件所在目录
uwsgi --stop uwsgi.pid
# 查看启动的进程
px aux|grep 'uwsgi'
ps -ef | grep 'uwsgi'
nginx配置
-- 修改nginx的配置文件/etc/nginx/sites-enabled/default;
sudo vim该文件
修改nginx以后需要重启ngnix
启动-sudo/etc/init.d/nginx start
停止 -sudo/etc/init.d/nginx stop
重启 -sudo/etc/init.d/nginx restart
sudo ngnix -t
location里面新加入这俩
uwsgi_pass 101.132.151.37:8000;
include /etc/nginx/uwsgi_params;
location/static{
root /home/tedu/mysite7_static;
}
报错文件需要在cd /var/log/nginx/error里面查看
till
top 于实时显示系统中各进行对各种个资源的占用情况
host 命令
把一个主机名解析到一个网际地址或把一个网际地址解析到一个主机名。
teil -n-30
# 加上 sudo
# 根据进程 pid 查看端口
lsof -i | grep pid
# 根据端口查看进程
lsof -i:port
# 根据进程 pid 查看端口
netstat -nap | grep pid
# 根据端口查看进程号
netstat -nap | grep port
netstat -lnp|grep 8000
urls
"""dadablog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('test_cors',views.test_cors),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings
"""
Django settings for dadablog project.
Generated by 'django-admin startproject' using Django 2.2.12.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '81)rfqg#6s+6eyyidz$i%vxonxg9w53&ju!22j!j!7t)isr&*2'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'user',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'dadablog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'dadablog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dadablog',
'USER':'root',
'PASSWORD':'123456',
'HOST':'101.132.151.37',
'PPRT':'3306'
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
)
CORS_ALLOW_HEADERS = (
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)
# 图片路径
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
models
from django.db import models
import random
# Create your models here.
def default_sign():
signs = ['来吧,兄弟']
return random.choice(signs)
class UserProfile(models.Model):
username = models.CharField(max_length=11,verbose_name='用户名',primary_key=True)
nickname = models.CharField(max_length=30,verbose_name='昵称')
password = models.CharField(max_length=32)
email = models.EmailField()
phone = models.CharField(max_length=11)
avatar = models.ImageField(upload_to='avatar',null=True)
sign = models.CharField(max_length=50,verbose_name='个人签名',default=default_sign)
info = models.CharField(max_length=150,verbose_name='个人简介',default='')
created_time = models.DateTimeField(auto_now_add=True)
updated_time = models.DateTimeField(auto_now=True)
class Meta:
db_table = 'user_user_profile'
--views.py
from django.http import JsonResponse
def test_cors(request):
return JsonResponse({'msg':'CORS is ok'})

浙公网安备 33010602011771号