Django---第三方

第三方:

3.富文本编辑器:此处以tinymce为例

使用编辑器的显示效果为:

1.下载安装

在网站pypi网站搜索并下载"django-tinymce-2.4.0"

解压

tar zxvf django-tinymce-2.4.0.tar.gz

进入解压后的目录,工作在虚拟环境,安装           python setup.py install应用到项目中

2.在settings.py中为INSTALLED_APPS添加编辑器应用

INSTALLED_APPS = (

    ...

    'tinymce',

)

3.在settings.py中添加编辑配置项

TINYMCE_DEFAULT_CONFIG = {

    'theme': 'advanced',

    'width': 600,

    'height': 400,

}

在根urls.py中配置

urlpatterns = [

    ...

    url(r'^tinymce/', include('tinymce.urls')),

]

在应用中定义模型的属性

from django.db import models

from tinymce.models import HTMLField

 

class HeroInfo(models.Model):

    ...

    hcontent = HTMLField()

在后台管理界面中,就会显示为富文本编辑器,而不是多行文本框

自定义使用:

定义视图editor,用于显示编辑器并完成提交

def editor(request):

    return render(request, 'other/editor.html')

配置url

urlpatterns = [

    ...

    url(r'^editor/$', views.editor, name='editor'),

]

创建模板editor.html

<!DOCTYPE html>

<html>

<head>

    <title></title>

    <script type="text/javascript" src='/static/tiny_mce/tiny_mce.js'></script>

    <script type="text/javascript">

        tinyMCE.init({

            'mode':'textareas',

            'theme':'advanced',

            'width':400,

            'height':100

        });

    </script>

</head>

<body>

<form method="post" action="/content/">

    <input type="text" name="hname">

    <br>

    <textarea name='hcontent'>哈哈,这是啥呀</textarea>

    <br>

    <input type="submit" value="提交">

</form>

</body>

</html>

定义视图content,接收请求,并更新heroinfo对象

def content(request):

    hname = request.POST['hname']

    hcontent = request.POST['hcontent']

 

    heroinfo = HeroInfo.objects.get(pk=1)

    heroinfo.hname = hname

    heroinfo.hcontent = hcontent

    heroinfo.save()

 

    return render(request, 'other/content.html', {'hero': heroinfo})

添加url项

urlpatterns = [

    ...

    url(r'^content/$', views.content, name='content'),

]

定义模板content.html

<!DOCTYPE html>

<html>

<head>

    <title></title>

</head>

<body>

姓名:{{hero.hname}}

<hr>

{%autoescape off%}

{{hero.hcontent}}

{%endautoescape%}

</body>

</html>

4.缓存:Django自带了一个健壮的缓存系统来保存动态页面,避免对于每次请求都重新计算,Django提供了不同级别的缓存粒度:可以缓存特定视图的输出、可以仅仅缓存那些很难生产出来的部分、或者可以缓存整个网站.

设置缓存:通过设置把数据缓存在数据库,文件系统,内存

1.通过setting文件的CACHES配置来实现,参数TIMEOUT:缓存的默认过期时间,以秒为单位,默认5分钟;设置TIMEOUT为None表示永远不会过期,值设置成0造成缓存立即失效

CACHES={

    'default': {

        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',

        'TIMEOUT': 60,

    }

}

2.Redis数据库缓存:可以将cache存到redis中,默认采用1数据库,需要安装包并配置如下:

安装包:pip install django-redis-cache

CACHES = {

    "default": {

        "BACKEND": "redis_cache.cache.RedisCache",

        "LOCATION": "localhost:6379",

        'TIMEOUT': 60,

    },

}

可以连接redis查看存的数据

连接:redis-cli

切换数据库:select 1

查看键:keys *

查看值:get 键

单个view缓存

django.views.decorators.cache定义了cache_page装饰器,用于对视图的输出进行缓存

示例代码如下:

from django.views.decorators.cache import cache_page

@cache_page(60 * 15)

def index(request):

return HttpResponse('hello1')

cache_page接受一个参数:timeout,秒为单位,上例中缓存了15分钟

视图缓存与URL无关,如果多个URL指向同一视图,每个URL将会分别缓存

5.模板片断缓存:使用cache模板标签来缓存模板的一个片段

需要两个参数:时间,名称

示例代码如下:

{% load cache %}

{% cache 500 hello %}

hello1

<!--hello2-->

{% endcache %}

底层的缓存API

from django.core.cache import cache

设置:cache.set(键,值,有效时间)

获取:cache.get(键)

删除:cache.delete(键)

清空:cache.clear()

 

 

 

 

6.全文检索:全文检索不同于特定字段的模糊查询,使用全文检索的效率更高,并且能够对于中文进行分词处理

工具包:

1.haystack(与Python交互的包):django的一个包,可以方便地对model里面的内容进行索引、搜索,设计为支持whoosh,solr,Xapian,Elasticsearc四种全文检索引擎后端,属于一种全文检索的框架

2.whoosh(进行检索的框架):纯Python编写的全文搜索引擎,虽然性能比不上sphinx、xapian、Elasticsearc等,但是无二进制包,程序不会莫名其妙的崩溃,对于小型的站点,whoosh已经足够使用

3.jieba(一句话里面把词分开):一款免费的中文分词包,如果觉得不好用可以使用一些收费产品

操作

1.在虚拟环境中依次安装包

1.pip install django-haystack

2.pip install whoosh

3.pip install jieba

2.修改settings.py文件

添加应用

INSTALLED_APPS = (

    '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'

3.在项目的urls.py中添加url

urlpatterns = [

    url(r'^search/', include('haystack.urls')),

]

4.在应用目录下建立search_indexes.py文件(导入模型类,然后生成索引再进行数据库的交互)

# coding=utf-8

from haystack import indexes

from models import GoodsInfo

class GoodsInfoIndex(indexes.SearchIndex, indexes.Indexable):

    text = indexes.CharField(document=True, use_template=True)

    def get_model(self):

        return GoodsInfo模型

    def index_queryset(self, using=None):

        return self.get_model().objects.all()

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

#goodsinfo_text.txt,这里列出了要对哪些列的内容进行检索

{{ object.gName }}

{{ object.gSubName }}

{{ object.gDes }}

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

<!DOCTYPE html>

<html>

<head>

    <title></title>

</head>

<body>

{% if query %}

    <h3>搜索结果如下:</h3>

    {% for result in page.object_list %}

        <a href="/{{ result.object.id }}/">{{ result.object.gName }}</a><br/>

    {% 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>

7.建立ChineseAnalyzer.py文件(进到安装的目录里面创建对应的文件,然后把代码放进去)

保存在haystack的安装文件夹下,路径如“/home/python/.virtualenvs/django_py2/lib/python2.7/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()

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

注意:复制出来的文件名,末尾会有一个空格,记得要删除这个空格

from .ChineseAnalyzer import ChineseAnalyzer

查找

analyzer=StemmingAnalyzer()

改为

analyzer=ChineseAnalyzer()

9.生成索引

初始化索引数据

python manage.py rebuild_index

10.在模板中创建搜索栏

<form method='get' action="/search/" target="_blank">

    <input type="text" name="q">

    <input type="submit" value="查询">

</form>

 

7.celery:

使用场景:

       1.耗时操作,直接分出进程去执行,避免客户端等待响应太久

       2.定时操作,对于固定的操作,设置定时,到点直接分出进程去操作

名词:

1.任务task:就是一个Python函数

2.队列queue:将需要执行的任务加入到队列中

3.工人worker:在一个新进程中,负责执行队列中的任务

4.代理人broker:负责调度,在布置环境中使用redis

使用:

1.安装包

celery==3.1.25

celery-with-redis==3.0

django-celery==3.1.17

2.配置settings

INSTALLED_APPS = (

  'djcelery',

}

import djcelery

djcelery.setup_loader()

BROKER_URL = 'redis://127.0.0.1:6379/0'

CELERY_IMPORTS = ('应用名称.task')

在应用目录下创建task.py文件

import time

from celery import task

@task

def sayhello():

        print('hello ...')

        time.sleep(2)

        print('world ...')

迁移,生成celery需要的数据表

python manage.py migrate

启动Redis

sudo redis-server /etc/redis/redis.conf

启动worker

python manage.py celery worker --loglevel=info

调用语法

function.delay(parameters)

使用代码

#from task import *

def sayhello(request):

    print('hello ...')

    import time

    time.sleep(10)

    print('world ...')

    # sayhello.delay()

    return HttpResponse("hello world")

posted @ 2018-03-16 12:17  tonyey  阅读(117)  评论(0编辑  收藏  举报