django视图获取用户请求信息以及请求头

一. request可以直接在前端用,不需要在render里再定义。

 

request.body  //前端页面数据内容的原生值。如果前端不是从POST,GET,FILES里面获取的数据,就从body里获取

request.POST  //从request.body里拿数据再封装到request.POST里面

request.FILES  //从request.body里拿数据再封装到request.FILES里面

request.GET  //从request.body里拿数据再封装到request.GET里面

request.XXX.getlist  //获取列表

request.post.getlist  //获取列表

 

request.Meta  (request headers)  //获取请求头相关的信息。

request.method  //请求方法

request.path_info  //获取URL

request.COOKIES  //获取cookies

 

二.cookie信息或在rep里添加的键值对将会写到response headers里面

 

a= ‘python’

rep = HttpResponse(…) 或 rep = render(request, …)或rep =redirect(‘/index/’)

a= ‘python’

rep = HttpResponse(a)

rep[‘name’] = ‘zhou’

rep.set_cookie()

return rep

HttpResponse可以返回字节和字符串

 

三.request.environ/request.META

 

{
‘ALLUSERSPROFILE’: ‘C:\\ProgramData’,
‘APPDATA’: ‘C:\\Users\\wenguoli\\AppData\\Roaming’,
‘COMMONPROGRAMFILES’: ‘C:\\Program Files (x86)\\Common Files’,
‘COMMONPROGRAMFILES(X86)’: ‘C:\\Program Files (x86)\\Common Files’,
‘COMMONPROGRAMW6432’: ‘C:\\Program Files\\Common Files’,
‘COMPUTERNAME’: ‘LAPTOP-B96OIQJU’,
‘COMSPEC’: ‘C:\\WINDOWS\\system32\\cmd.exe’,
‘CONFIGSETROOT’: ‘C:\\WINDOWS\\ConfigSetRoot’,
‘FPS_BROWSER_APP_PROFILE_STRING’: ‘Internet Explorer’,
‘FPS_BROWSER_USER_PROFILE_STRING’: ‘Default’,
‘GOPATH’: ‘D:\\software\\GOPATH’,
‘GOROOT’: ‘D:\\software\\go’,
‘HOMEDRIVE’: ‘C:’,
‘HOMEPATH’: ‘\\Users\\wenguoli’,
‘LOCALAPPDATA’: ‘C:\\Users\\wenguoli\\AppData\\Local’,
‘LOGONSERVER’: ‘\\\\LAPTOP-B96OIQJU’,
‘NODE_PATH’: ‘D:\\software\\nodejs\\node_global\\node_modules’,
‘NUMBER_OF_PROCESSORS’: ‘8’,
‘ONEDRIVE’: ‘D:\\OneDrive’,
‘OS’: ‘Windows_NT’,
‘PATH’: ‘D:\\python\\Envs\\django2.0\\Scripts;D:\\software\\python3.6.5\\Scripts\\;D:\\software\\python3.6.5\\;C:\\Program Files (x86)\\Intel\\iCLS Client\\;C:\\Program Files\\Intel\\iCLS Client\\;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\IPT;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\IPT;C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common;D:\\software\\git\\bin;D:\\software\\git\\Git\\cmd;D:\\software\\nodejs\\;D:\\software\\redis\\Redis-3.2.100;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;D:\\software\\mingw\\bin;C:\\wamp\\bin\\php\\php5.6.25;D:\\software\\composer;D:\\software\\go\\bin;C:\\Program Files (x86)\\Xoreax\\IncrediBuild;D:\\software\\python3.6.5\\Lib\\site-packages\\Django-1.11.13-py3.6.egg\\django\\bin;C:\\Program Files\\cURL\\bin;D:\\software\\svn\\bin;D:\\software\\cmder\\cmder;D:\\software\\javajdk\\bin;D:\\software\\java\\bin;D:\\software\\GOPATH\\bin;C:\\Users\\wenguoli\\AppData\\Local\\Microsoft\\WindowsApps;D:\\software\\nodejs\\node_global;D:\\software\\FileZilla\\Fiddler;C:\\Users\\wenguoli\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\wenguoli\\AppData\\Roaming\\Composer\\vendor\\bin;C:\\Users\\wenguoli\\AppData\\Local\\atom\\bin;D:\\software\\VSCode\\Microsoft VS Code\\bin’,
‘PATHEXT’: ‘.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW’,
‘PROCESSOR_ARCHITECTURE’: ‘x86’,
‘PROCESSOR_ARCHITEW6432’: ‘AMD64’,
‘PROCESSOR_IDENTIFIER’: ‘Intel64 Family 6 Model 142 Stepping 10, GenuineIntel’,
‘PROCESSOR_LEVEL’: ‘6’,
‘PROCESSOR_REVISION’: ‘8e0a’,
‘PROGRAMDATA’: ‘C:\\ProgramData’,
‘PROGRAMFILES’: ‘C:\\Program Files (x86)’,
‘PROGRAMFILES(X86)’: ‘C:\\Program Files (x86)’,
‘PROGRAMW6432’: ‘C:\\Program Files’,
‘PROMPT’: ‘(django2.0) $P$G’,
‘PSMODULEPATH’: ‘C:\\Program Files\\WindowsPowerShell\\Modules;C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\Modules’,
‘PUBLIC’: ‘C:\\Users\\Public’,
‘SESSIONNAME’: ‘Console’,
‘SYSTEMDRIVE’: ‘C:’,
‘SYSTEMROOT’: ‘C:\\WINDOWS’,
‘TEMP’: ‘C:\\Users\\wenguoli\\AppData\\Local\\Temp’,
‘TMP’: ‘C:\\Users\\wenguoli\\AppData\\Local\\Temp’,
‘UID’: ‘10103’,
‘USERDOMAIN’: ‘LAPTOP-B96OIQJU’,
‘USERDOMAIN_ROAMINGPROFILE’: ‘LAPTOP-B96OIQJU’,
‘USERNAME’: ‘wenguoli’,
‘USERPROFILE’: ‘C:\\Users\\wenguoli’,
‘VENV’: ‘django2.0’,
‘VIRTUALENVWRAPPER_PROJECT_FILENAME’: ‘.project’,
‘VIRTUAL_ENV’: ‘D:\\python\\Envs\\django2.0’,
‘WINDIR’: ‘C:\\WINDOWS’,
‘WORKON_HOME’: ‘D:\\python\\Envs’,
‘_OLD_VIRTUAL_PATH’: ‘D:\\software\\python3.6.5\\Scripts\\;D:\\software\\python3.6.5\\;C:\\Program Files (x86)\\Intel\\iCLS Client\\;C:\\Program Files\\Intel\\iCLS Client\\;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\IPT;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\IPT;C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common;D:\\software\\git\\bin;D:\\software\\git\\Git\\cmd;D:\\software\\nodejs\\;D:\\software\\redis\\Redis-3.2.100;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;D:\\software\\mingw\\bin;C:\\wamp\\bin\\php\\php5.6.25;D:\\software\\composer;D:\\software\\go\\bin;C:\\Program Files (x86)\\Xoreax\\IncrediBuild;D:\\software\\python3.6.5\\Lib\\site-packages\\Django-1.11.13-py3.6.egg\\django\\bin;C:\\Program Files\\cURL\\bin;D:\\software\\svn\\bin;D:\\software\\cmder\\cmder;D:\\software\\javajdk\\bin;D:\\software\\java\\bin;D:\\software\\GOPATH\\bin;C:\\Users\\wenguoli\\AppData\\Local\\Microsoft\\WindowsApps;D:\\software\\nodejs\\node_global;D:\\software\\FileZilla\\Fiddler;C:\\Users\\wenguoli\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\wenguoli\\AppData\\Roaming\\Composer\\vendor\\bin;C:\\Users\\wenguoli\\AppData\\Local\\atom\\bin;D:\\software\\VSCode\\Microsoft VS Code\\bin’,
‘_OLD_VIRTUAL_PROMPT’: ‘$P$G’,
‘DJANGO_SETTINGS_MODULE’: ‘bige.settings’,
‘RUN_MAIN’: ‘true’,
‘SERVER_NAME’: ‘LAPTOP-B96OIQJU’,
‘GATEWAY_INTERFACE’: ‘CGI/1.1’,
‘SERVER_PORT’: ‘8000’,
‘REMOTE_HOST’: ”,
‘CONTENT_LENGTH’: ”,
‘SCRIPT_NAME’: ”,
‘SERVER_PROTOCOL’: ‘HTTP/1.1’,
‘SERVER_SOFTWARE’: ‘WSGIServer/0.2’,
‘REQUEST_METHOD’: ‘GET’,
‘PATH_INFO’: ‘/api/v1/user/7/’,
‘QUERY_STRING’: ”,
‘REMOTE_ADDR’: ‘127.0.0.1’,
‘CONTENT_TYPE’: ‘text/plain’,
‘HTTP_TOKEN’: ‘12121212’,
‘HTTP_CACHE_CONTROL’: ‘no-cache’,
‘HTTP_POSTMAN_TOKEN’: ‘432aad28-fbca-4023-9f89-fad29e737b14’,
‘HTTP_USER_AGENT’: ‘PostmanRuntime/7.1.1’,
‘HTTP_ACCEPT’: ‘*/*’,
‘HTTP_HOST’: ‘127.0.0.1:8000’,
‘HTTP_ACCEPT_ENCODING’: ‘gzip, deflate’,
‘HTTP_CONNECTION’: ‘keep-alive’,
‘wsgi.input’: < _io.BufferedReader name = 1168 > ,
‘wsgi.errors’: < _io.TextIOWrapper name = ‘<stderr>’
mode = ‘w’
encoding = ‘utf-8’ > ,
‘wsgi.version’: (1, 0),
‘wsgi.run_once’: False,
‘wsgi.url_scheme’: ‘http’,
‘wsgi.multithread’: True,
‘wsgi.multiprocess’: False,
‘wsgi.file_wrapper’: < class ‘wsgiref.util.FileWrapper’ >
}

 

Django-部署

布署

  • 从uwsgi、nginx、静态文件三个方面处理

服务器介绍

  • 服务器:私有服务器、公有服务器
  • 私有服务器:公司自己购买、自己维护,只布署自己的应用,可供公司内部或外网访问
  • 公有服务器:集成好运营环境,销售空间或主机,供其布署自己的应用
  • 私有服务器成本高,需要专业人员维护,适合大公司使用
  • 公有服务器适合初创公司使用,成本低
  • 常用的公有服务器,如阿里云、青云等,可根据需要,按流量收费或按时间收费
  • 此处的服务器是物理上的一台非常高、线路全、运行稳定的机器

服务器环境配置

  • 在本地的虚拟环境中,项目根目录下,执行命令收集所有包
pip freeze > plist.txt
  • 通过ftp软件将开发好的项目上传到此服务器的某个目录
  • 安装并创建虚拟环境,如果已有则跳过此步
sudo apt-get install python-virtualenv
sudo easy_install virtualenvwrapper
mkvirtualenv [虚拟环境名称]
  • 在虚拟环境上工作,安装所有需要的包
workon [虚拟环境名称]
pip install -r plist.txt
  • 更改settings.py文件
DEBUG = False
ALLOW_HOSTS=['*',]表示可以访问服务器的ip
  • 启动服务器,运行正常,但是静态文件无法加载

WSGI

  • python manage.py runserver:这是一款适合开发阶段使用的服务器,不适合运行在真实的生产环境中
  • 在生产环境中使用WSGI
  • WSGI:Web服务器网关接口,英文为Python Web Server Gateway Interface,缩写为WSGI,是Python应用程序或框架和Web服务器之间的一种接口,被广泛接受
  • WSGI没有官方的实现, 因为WSGI更像一个协议,只要遵照这些协议,WSGI应用(Application)都可以在任何服务器(Server)上运行
  • 命令django-admin startproject会生成一个简单的wsgi.py文件,确定了settings、application对象
    • application对象:在Python模块中使用application对象与应用服务器交互
    • settings模块:Django需要导入settings模块,这里是应用定义的地方
  • 此处的服务器是一个软件,可以监听网卡端口、遵从网络层传输协议,收发http协议级别的数据

uWSGI

  • uWSGI实现了WSGI的所有接口,是一个快速、自我修复、开发人员和系统管理员友好的服务器
  • uWSGI代码完全用C编写
  • 安装uWSGI
pip install uwsgi
  • 配置uWSGI,在项目中新建文件uwsgi.ini,编写如下配置
[uwsgi]
socket=外网ip:端口(使用nginx连接时,使用socket)
http=外网ip:端口(直接做web服务器,使用http)
chdir=项目根目录
wsgi-file=项目中wsgi.py文件的目录,相对于项目根目录
processes=4
threads=2
master=True
pidfile=uwsgi.pid
daemonize=uswgi.log
  • 启动:uwsgi –ini uwsgi.ini
  • 停止:uwsgi –stop uwsgi.pid
  • 重启:uwsgi –reload uwsgi.pid
  • 使用http协议查看网站运行情况,运行正常,但是静态文件无法加载

nginx

  • 使用nginx的作用
    • 负载均衡:多台服务器轮流处理请求
    • 反射代理:隐藏真实服务器
  • 实现构架:客户端请求nginx,再由nginx请求uwsgi,运行django框架下的python代码
  • nginx+uwsgi也可以用于其它框架的python web代码,不限于django
  • 到官网下载nginx压缩文件或通过命令安装
sudo apt-get nginx
  • 这里以下载压缩文件为例演示
解压缩:
tar zxvf nginx-1.6.3.tar.gz

进入nginx-1.6.3目录依次执行如下命令进行安装:
./configure
make
sudo make install
  • 默认安装到/usr/local/nginx目录,进入此目录执行命令
  • 查看版本:sudo sbin/nginx -v
  • 启动:sudo sbin/nginx
  • 停止:sudo sbin/nginx -s stop
  • 重启:sudo sbin/nginx -s reload
  • 通过浏览器查看nginx运行结果
  • 指向uwsgi项目:编辑conf/nginx.conf文件
sudo conf/nginx.conf

在server下添加新的location项,指向uwsgi的ip与端口
location / {
    include uwsgi_params;将所有的参数转到uwsgi下
    uwsgi_pass uwsgi的ip与端口;
}
  • 修改uwsgi.ini文件,启动socket,禁用http
  • 重启nginx、uwsgi
  • 在浏览器中查看项目,发现静态文件加载不正常,接下来解决静态文件的问题

静态文件

  • 静态文件一直都找不到,现在终于可以解决了
  • 所有的静态文件都会由nginx处理,不会将请求转到uwsgi
  • 配置nginx的静态项,打开conf/nginx.conf文件,找到server,添加新location
location /static {
    alias /var/www/test5/static/;
}
  • 在服务器上创建目录结构“/var/www/test5/”
  • 修改目录权限
sudo chmod 777 /var/www/test5
  • 创建static目录,注意顺序是先分配权限,再创建目录
mkdir static
  • 最终目录结构如下图:
  • 修改settings.py文件
STATIC_ROOT='/var/www/test5/static/'
STATIC_URL='/static/'
  • 收集所有静态文件到static_root指定目录:python manage.py collectstatic
  • 重启nginx、uwsgi

Django-全文搜索

1.创建app

python manage.py startapp booktest

2.安装富文本库

pip install django-haystack
pip install whoosh
pip install jieba

3.setting添加booktest,配置文件存放位置


INSTALLED_APPS = [
    'multi_captcha_admin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'booktest',
    # 'blog',
    'tinymce',
    'haystack'
]
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
        'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
    }
}

# 自动生成索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

4.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
    re_path(r'^search/', include('haystack.urls')),
]

5.配置booktest/urls

from django.urls import path, re_path
from . import views

urlpatterns = [
re_path(r'^mysearch/$', views.mysearch),
]

注:最新版本2.0以上使用path 或者re_path

6.编写views

# coding=utf-8
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from .models import *
from django.views.decorators.cache import cache_page
from django.core.cache import cache
# 全文检索+中文分词
def mysearch(request):
    return render(request, 'booktest/mysearch.html')


7.编写全文搜索文件booktest/search_indexs.py

 

# coding=utf-8
from haystack import indexes
from .models import Test1


class Test1Index(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)

    def get_model(self):
        return Test1

    def index_queryset(self, using=None):
        return self.get_model().objects.all()



8.在目录“templates/search/indexes/应用名称/”下创建“模型类名称_text.txt”文件

{{ object.content }}

9.在目录“templates/search/”下建立search.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
{% if query %}
    <h3>搜索结果如下:</h3>
    {% for result in page.object_list %}
        {{ result.object.id }}
        <br>
        {{ result.object.content|safe }}
        <hr>
    {% empty %}
        <p>啥也没找到</p>
    {% endfor %}

    {% if page.has_previous or page.has_next %}
        <div>
            {% if page.has_previous %}<a href="?q={{ query }}&amp;page={{ page.previous_page_number }}">{% endif %}&laquo; 上一页{% if page.has_previous %}</a>{% endif %}
        |
            {% if page.has_next %}<a href="?q={{ query }}&amp;page={{ page.next_page_number }}">{% endif %}下一页 &raquo;{% if page.has_next %}</a>{% endif %}
        </div>
    {% endif %}
{% endif %}
</body>
</html>


10.建立ChineseAnalyzer.py文件

  • 保存在haystack的安装文件夹下,路径如“/site-packages/haystack/backends”
import jieba
from whoosh.analysis import Tokenizer, Token


class ChineseTokenizer(Tokenizer):
    def __call__(self, value, positions=False, chars=False,
                 keeporiginal=False, removestops=True,
                 start_pos=0, start_char=0, mode='', **kwargs):
        t = Token(positions, chars, removestops=removestops, mode=mode,
                  **kwargs)
        seglist = jieba.cut(value, cut_all=True)
        for w in seglist:
            t.original = t.text = w
            t.boost = 1.0
            if positions:
                t.pos = start_pos + value.find(w)
            if chars:
                t.startchar = start_char + value.find(w)
                t.endchar = start_char + value.find(w) + len(w)
            yield t


def ChineseAnalyzer():
    return ChineseTokenizer()

11.复制whoosh_backend.py文件,改名为whoosh_cn_backend.py

from .ChineseAnalyzer import ChineseAnalyzer 
查找
analyzer=StemmingAnalyzer()
改为
analyzer=ChineseAnalyzer()


12.生成索引

python manage.py rebuild_index

13.在模板中创建搜索栏

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/search/" target="_blank" method="get">
<input type="text" name="q"><input type="submit" value="搜索">
</form>
</body>
</html>

Django-cache-redis

1.创建app

python manage.py startapp booktest

2.安装富文本库

pip install django-redis-cache

3.setting添加booktest,配置文件存放位置


INSTALLED_APPS = [
    'multi_captcha_admin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'booktest'
]

# 配置cache到redis
CACHES = {
    "default": {
        "BACKEND": "redis_cache.cache.RedisCache",
        "LOCATION": "localhost:6379",
        'TIMEOUT': 60,
    },
}

4.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest'))
]

5.配置booktest/urls

from django.urls import path, re_path
from . import views

urlpatterns = [
    re_path(r'^cache1/$', views.cache1)

]

注:最新版本2.0以上使用path 或者re_path

6.编写views

# coding=utf-8
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from .models import *
from django.views.decorators.cache import cache_page
from django.core.cache import cache


# 缓存
@cache_page(60*10)
def cache1(request):
    return HttpResponse('hello1')
    # return HttpResponse('hello2')
    # cache.set('key1', 'value1', 600)
    # print(cache.get('key1'))
    # return render(request, 'booktest/cache1.html')
    # cache.clear()
    # return HttpResponse('ok')

7.redis操作
连接:redis-cli
切换数据库:select 1
查看键:keys *
查看值:get 键

 

Django-富文本

1.创建app

python manage.py startapp booktest

2.安装富文本库

pip install django-tinymce

3.setting添加booktest,配置文件存放位置


INSTALLED_APPS = [
    'multi_captcha_admin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'booktest',
    'tinymce',
]

TINYMCE_DEFAULT_CONFIG = {
    'theme': 'advanced',
    'width': 600,
    'height': 400,
}


4.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
    re_path(r'^tinymce/', include('tinymce.urls')),
]

5.配置booktest/urls

from django.urls import path, re_path
from . import views

urlpatterns = [
    re_path(r'^htmlEditor/$', views.htmlEditor),
    re_path(r'^htmlEditorHandle/$', views.htmlEditorHandle),

]

注:最新版本2.0以上使用path 或者re_path

6.编写富文本 booktest/models

from django.db import models
from tinymce.models import HTMLField


class AreaInfo(models.Model):
    title = models.CharField(max_length=20)
    parea = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL)


class Test1(models.Model):
    content = HTMLField()


7.编写富文本admin 后台界面booktest/admin

from django.contrib import admin
from .models import *

admin.site.register(Test1)


8.views编辑

from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from .models import *
from django.views.decorators.cache import cache_page
from django.core.cache import cache


# 自定义编辑器
def htmlEditor(request):
    return render(request, 'booktest/htmlEditor.html')


def htmlEditorHandle(request):
    html = request.POST['hcontent']
    # test1=Test1.objects.get(pk=1)
    # test1.content=html
    # test1.save()
    test1 = Test1()
    test1.content = html
    test1.save()
    context = {'content': html}
    return render(request, 'booktest/htmlShow.html', context)

Django-上传图片

1.创建app

python manage.py startapp booktest

2.setting添加booktest,配置文件存放位置

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media/')

3.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    # 2.0以后,反向解析使用以下方式
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
]

4.配置booktest/urls

from django.urls import path , re_path
from . import views

urlpatterns = [
    re_path(r'^uploadPic$', views.uploadPic),
    re_path(r'^uploadHandle$', views.uploadHandle),

]

注:最新版本2.0以上使用path 或者re_path

 

5.编写视图

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
import os
from django.conf import settings
# from models import *
from django.core.paginator import *
import json
import logging


def uploadPic(request):
    return render(request, 'booktest/uploadPic.html')


def uploadHandle(request):
    pic1 = request.FILES['pic1']
    logging.debug("图片信息:%s " % (pic1.name))
    picName = os.path.join(settings.MEDIA_ROOT, pic1.name)
    # 使用wb+写入二进制,只要w写不进去
    with open(picName, 'wb+') as pic:
        for c in pic1.chunks():
            pic.write(c)
    return HttpResponse('<img src="/static/media/%s"/>' % pic1.name)

6.templates/booktest文件

uploadPic

Django-中间件,错误中间件

1.创建app

python manage.py startapp booktest

2.setting添加booktest

3.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
]

注:最新版本2.0以上使用path 或者re_path

4.中间件设置,增加booktest/MyException文件

from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin

# 自定义异常处理
class MyException(MiddlewareMixin):
    def process_exception(request, response, exception):
        return HttpResponse('abc')

注:一定要传入MiddlewareMixin,否则编译不成功

5.设置setting配置的中间件’booktest.MyException.MyException’,

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',
    'booktest.MyException.MyException',
]

Django-验证码

1.创建app

python manage.py startapp booktest

2.安装验证码库

# 安装验证码,图片包
pip install pillow

# 验证码库
pip install django-multi-captcha-admin django-simple-captcha

simple-captcha https://github.com/mbi/django-simple-captcha
recaptcha https://github.com/praekelt/django-recaptcha
recaptcha2 https://github.com/kbytesys/django-recaptcha2

 

3.setting添加booktest,同时添加验证码库multi_captcha_admin

INSTALLED_APPS = [
    'multi_captcha_admin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'booktest',
]
# admin站点动态验证码
MULTI_CAPTCHA_ADMIN = {
    'engine': 'simple-captcha'
}

4. 验证码数据库迁移,否则显示不出来

python manage.py migrate

注:一定要迁移,admin才能显示验证码

5.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^captcha/', include('captcha.urls')),
    path('blog/', include('blog.urls')),
    # path('booktest/', include('booktest.urls', 'booktest')),
    # 2.0以后,反向解析使用以下方式
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
]

6.配置booktest/urls

from django.urls import path, re_path
from . import views

urlpatterns = [
    re_path(r'^verifyCode$', views.verifyCode),
    re_path(r'^verifyTest1', views.verifyTest1),
    re_path(r'^verifyTest2', views.verifyTest2),

]

注:最新版本2.0以上使用path 或者re_path

 

7.编写视图

# coding=utf-8

from django.shortcuts import render
from django.http import HttpResponse
from booktest.models import HeroInfo
import logging


# 验证码
def verifyCode(request):
    from PIL import Image, ImageDraw, ImageFont
    import random
    # 创建背景色
    bgColor = (random.randrange(50, 100), random.randrange(50, 100), 0)
    # 规定宽高
    width = 100
    height = 25
    # 创建画布
    image = Image.new('RGB', (width, height), bgColor)
    # 构造字体对象
    # font = ImageFont.truetype('FreeMono.ttf', 24)
    font = ImageFont.load_default().font
    # 创建画笔
    draw = ImageDraw.Draw(image)
    # 创建文本内容
    text = '0123ABCD'
    # 逐个绘制字符
    textTemp = ''
    for i in range(4):
        textTemp1 = text[random.randrange(0, len(text))]
        textTemp += textTemp1
        draw.text((i * 25, 0),
                  textTemp1,
                  (255, 255, 255),
                  font)
    request.session['code'] = textTemp
    # 保存到内存流中
    # import cStringIO
    # buf = cStringIO.StringIO()
    # image.save(buf, 'png')

    # 内存文件操作-->此方法为python3的
    import io
    buf = io.BytesIO()
    # 将图片保存在内存中,文件类型为png
    image.save(buf, 'png')
    # 将内存流中的内容输出到客户端
    return HttpResponse(buf.getvalue(), 'image/png')


def verifyTest1(request):
    return render(request, 'booktest/verifyTest1.html')


def verifyTest2(request):
    code1 = request.POST['code1']
    code2 = request.session['code']
    if code1 == code2:
        return HttpResponse("ok")
    else:
        return HttpResponse("no")


def verifyCode_方式1(request):
    from PIL import Image, ImageDraw, ImageFont
    # 引入随机函数模块
    import random
    # 定义变量,用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 25
    # 创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    # 构造字体对象,ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”
    # font = ImageFont.truetype('FreeMono.ttf', 23)
    font = ImageFont.load_default().font
    # 构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    # 释放画笔
    del draw
    # 存入session,用于做进一步验证
    request.session['verifycode'] = rand_str
    """
    python2的为
    # 内存文件操作
    import cStringIO
    buf = cStringIO.StringIO()
    """
    # 内存文件操作-->此方法为python3的
    import io
    buf = io.BytesIO()
    # 将图片保存在内存中,文件类型为png
    im.save(buf, 'png')
    # 将内存中的图片数据返回给客户端,MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')

8.templates/booktest文件

verifyTest1

Django-html转义和csrf权限

1.创建app

python manage.py startapp booktest

2.setting添加booktest

3.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^captcha/', include('captcha.urls')),
    path('blog/', include('blog.urls')),
    # path('booktest/', include('booktest.urls', 'booktest')),
    # 2.0以后,反向解析使用以下方式
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
]

4.配置booktest/urls

from django.urls import path, re_path
from . import views

urlpatterns = [
    re_path(r'^htmlTest$', views.htmlTest),
    re_path(r'^csrf1$', views.csrf1),
    re_path(r'^csrf2$', views.csrf2),

]

注:最新版本2.0以上使用path 或者re_path

 

5.编写视图

from django.shortcuts import render
from django.http import HttpResponse
from booktest.models import HeroInfo
import logging


# html转义
def htmlTest(request):
    context = {'t1': '<h1>123</h1>'}
    return render(request, 'booktest/htmlTest.html', context)


# csrf
def csrf1(request):
    return render(request, 'booktest/csrf1.html')


def csrf2(request):
    uname = request.POST['uname']
    return HttpResponse(uname)

6.templates/booktest文件

csrf1 htmlTest

Django-session-redis

1.安装django-redis-sessions

pip install django-redis-sessions

注:前提的linux或win安装好redis服务端

2.配置setting文件

SESSION_ENGINE = ‘redis_sessions.session’
SESSION_REDIS_HOST = ‘localhost’
SESSION_REDIS_PORT = 6379
SESSION_REDIS_DB = 0
SESSION_REDIS_PASSWORD = ”
SESSION_REDIS_PREFIX = ‘session’

3.其他操作访问按上篇

django-session

4.查看redis

 

5.django存储的是base64方式,可解密