富文本編輯器、全文檢索和django發送郵件

1.富文本編輯器

1.1快速瞭解

藉助富文本編輯器,網站的編輯人員可以像使用offfice同樣編寫出漂亮的、所見即所得的頁面。此處以tinymce爲例,其它富文本編輯器的使用也是相似的。

在虛擬環境中安裝包。

pip install django-tinymce==2.6.0
安裝完成後,可使用在Admin管理中,也能夠自定義表單使用。

示例
1)在test6/settings.py中爲INSTALLED_APPS添加編輯器應用。

INSTALLED_APPS = (
    ...
    'tinymce',
)
2)在test6/settings.py中添加編輯器配置。

TINYMCE_DEFAULT_CONFIG = {
    'theme': 'advanced',
    'width': 600,
    'height': 400,
}
3)在test6/urls.py中配置編輯器url。

urlpatterns = [
    ...
    url(r'^tinymce/', include('tinymce.urls')),
]
接下來介紹在Admin頁面、自定義表單頁面的使用方式。

 

1.2在Admin中使用

1)在booktest/models.py中,定義模型的屬性爲HTMLField()類型。

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

class GoodsInfo(models.Model):
    gcontent=HTMLField()

 

2)生成遷移文件。

python manage.py makemigrations

 

3)執行遷移。javascript

python manage.py migrate

4)在本示例中沒有定義其它的模型類,可是數據庫中有這些表,提示是否刪除,輸入no後回車,表示不刪除,由於其它的示例中須要使用這些表。html

 

5)遷移完成,新開終端,鏈接mysql,使用test2數據庫,查看錶以下:java

 

6)發現並無表GoodsInfo,解決辦法是刪除遷移表中關於booktest應用的數據。python

delete from django_migrations where app='booktest';

7)再次執行遷移。mysql

python manage.py migrate

成功完成遷移,記得不刪除no。redis

 

8)在booktest/admin.py中註冊模型類GoodsInfosql

from django.contrib import admin
from booktest.models import *
class GoodsInfoAdmin(admin.ModelAdmin):
    list_display = ['id']

admin.site.register(GoodsInfo,GoodsInfoAdmin)

 

9)運行服務器,進入admin後臺管理,點擊GoodsInfo的添加,效果以下圖數據庫

 

在編輯器中編輯內容後保存。django

 

 1.3自定義使用

1)在booktest/views.py中定義視圖editor,用於顯示編輯器。

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

 

2)在booktest/urls.py中配置url。api

url(r'^editor/',views.editor),

3)在項目目錄下建立靜態文件目錄以下圖:

 

4)打開py_django虛擬環境的目錄,找到tinymce的目錄。

/home/python/.virtualenvs/py_django/lib/python3.5/site-packages/tinymce/static/tiny_mce

5)拷貝tiny_mce_src.js文件、langs文件夾以及themes文件夾拷貝到項目目錄下的static/js/目錄下。

 

6)在test6/settings.py中配置靜態文件查找路徑。

STATICFILES_DIRS=[
    os.path.join(BASE_DIR,'static'),
]

 

7)在templates/booktest/目錄下建立editor.html模板。

<html>
<head>
    <title>自定義使用tinymce</title>
    <script type="text/javascript" src='/static/js/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="#">
    <textarea name='gcontent'>哈哈,這是啥呀</textarea>
</form>
</body>
</html>

 

8)運行服務器,在瀏覽器中輸入以下網址:

http://127.0.0.1:8000/editor/

瀏覽效果以下圖:

 

 

1.4顯示

經過富文本編輯器產生的字符串是包含html的。 在數據庫中查詢以下圖:

 

在模板中顯示字符串時,默認會進行html轉義,若是想正常顯示須要關閉轉義。

問:在模板中怎麼關閉轉義

  • 方式一:過濾器safe
  • 方式二:標籤autoescape off

1)在booktest/views.py中定義視圖show,用於顯示富文本編輯器的內容。

from booktest.models import *
...
def show(request):
    goods=GoodsInfo.objects.get(pk=1)
    context={'g':goods}
    return render(request,'booktest/show.html',context)

 

2)在booktest/urls.py中配置url。

url(r'^show/', views.show),

3)在templates/booktest/目錄下建立show.html模板。

<html>
<head>
    <title>展現富文本編輯器內容</title>
</head>
<body>
id:{{g.id}}
<hr>
{%autoescape off%}
{{g.gcontent}}
{%endautoescape%}
<hr>
{{g.gcontent|safe}}
</body>
</html>

 

4)運行服務器,在瀏覽器中輸入以下網址:

http://127.0.0.1:8000/show/

瀏覽效果以下圖:

 

 2.全文檢索

2.1快速瞭解

全文檢索不一樣於特定字段的模糊查詢,使用全文檢索的效率更高,而且可以對於中文進行分詞處理。

  • haystack:全文檢索的框架,支持whoosh、solr、Xapian、Elasticsearc四種全文檢索引擎,點擊查看官方網站
  • whoosh:純Python編寫的全文搜索引擎,雖然性能比不上sphinx、xapian、Elasticsearc等,可是無二進制包,程序不會莫名其妙的崩潰,對於小型的站點,whoosh已經足夠使用,點擊查看whoosh文檔
  • jieba:一款免費的中文分詞包,若是以爲很差用可使用一些收費產品。

1)在虛擬環境中依次安裝須要的包。

pip install django-haystack
pip install whoosh
pip install jieba

 

2)修改test6/settings.py文件,安裝應用haystack。

INSTALLED_APPS = (
    ...
    'haystack',
)

 

3)在test6/settings.py文件中配置搜索引擎。

...
HAYSTACK_CONNECTIONS = {
    'default': {
        #使用whoosh引擎
        'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
        #索引文件路徑
        'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
    }
}

#當添加、修改、刪除數據時,自動生成索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

 

4)在test6/urls.py中添加搜索的配置。

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

 

 

2.2建立引擎及索引

1)在booktest目錄下建立search_indexes.py文件。

from haystack import indexes
from booktest.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()

 

2)在templates目錄下建立"search/indexes/booktest/"目錄。

 

3)在上面的目錄中建立"goodsinfo_text.txt"文件。

#指定索引的屬性
{{object.gcontent}}

4)找到虛擬環境py_django下的haystack目錄。

/home/python/.virtualenvs/py_django/lib/python3.5/site-packages/haystack/backends/

5)在上面的目錄中建立ChineseAnalyzer.py文件。

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()

 

6)複製whoosh_backend.py文件,改成以下名稱:

注意:複製出來的文件名,末尾會有一個空格,記得要刪除這個空格。

whoosh_cn_backend.py

7)打開復製出來的新文件,引入中文分析類,內部採用jieba分詞。

from .ChineseAnalyzer import ChineseAnalyzer

8)更改詞語分析類。

查找
analyzer=StemmingAnalyzer()
改成
analyzer=ChineseAnalyzer()

9)初始化索引數據。

python manage.py rebuild_index

10)按提示輸入y後回車,生成索引。

 

11)索引生成後目錄結構以下圖:

 

 

2.3使用

按照配置,在admin管理中添加數據後,會自動爲數據建立索引,能夠直接進行搜索,能夠先建立一些測試數據。

1)在booktest/views.py中定義視圖query。

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

 

2)在booktest/urls.py中配置。

url(r'^query/', views.query),

3)在templates/booktest/目錄中建立模板query.html。

參數q表示搜索內容,傳遞到模板中的數據爲query。

<html>
<head>
    <title>全文檢索</title>
</head>
<body>
<form method='get' action="/search/" target="_blank">
    <input type="text" name="q">
    <br>
    <input type="submit" value="查詢">
</form>
</body>
</html>

 

4)自定義搜索結果模板:在templates/search/目錄下建立search.html。

搜索結果進行分頁,視圖向模板中傳遞的上下文以下:

  • query:搜索關鍵字
  • page:當前頁的page對象
  • paginator:分頁paginator對象

視圖接收的參數以下:

  • 參數q表示搜索內容,傳遞到模板中的數據爲query
  • 參數page表示當前頁碼
<html>
<head>
    <title>全文檢索--結果頁</title>
</head>
<body>
<h1>搜索&nbsp;<b>{{query}}</b>&nbsp;結果以下:</h1>
<ul>
{%for item in page%}
    <li>{{item.object.id}}--{{item.object.gcontent|safe}}</li>
{%empty%}
    <li>啥也沒找到</li>
{%endfor%}
</ul>
<hr>
{%for pindex in page.paginator.page_range%}
    {%if pindex == page.number%}
        {{pindex}}&nbsp;&nbsp;
    {%else%}
        <a href="?q={{query}}&amp;page={{pindex}}">{{pindex}}</a>&nbsp;&nbsp;
    {%endif%}
{%endfor%}
</body>
</html>

 

5)運行服務器,在瀏覽器中輸入以下地址:

http://127.0.0.1:8000/query/

在文本框中填寫要搜索的信息,點擊」搜索「按鈕。

 

搜索結果以下:

 

 

 

3.發送郵件

3.1使用django發送

Django中內置了郵件發送功能,被定義在django.core.mail模塊中。發送郵件須要使用SMTP服務器,經常使用的免費服務器有:163126QQ,下面以163郵件爲例。

1)註冊163郵箱itcast88,登陸後設置。

 

2)在新頁面中點擊「客戶端受權密碼」,勾選「開啓」,彈出新窗口填寫手機驗證碼。

 

3)填寫受權碼。

 

4)提示開啓成功。

 

5)打開test6/settings.py文件,點擊下圖配置。

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.163.com'
EMAIL_PORT = 25
#發送郵件的郵箱
EMAIL_HOST_USER = 'itcast88@163.com'
#在郵箱中設置的客戶端受權密碼
EMAIL_HOST_PASSWORD = 'python808'
#收件人看到的發件人
EMAIL_FROM = 'python<itcast88@163.com>'

 

6)在booktest/views.py文件中新建視圖send。

from django.conf import settings
from django.core.mail import send_mail
from django.http import HttpResponse
...
def send(request):
    msg='<a href="http://www.itcast.cn/subject/pythonzly/index.shtml" target="_blank">點擊激活</a>'
    send_mail('註冊激活','',settings.EMAIL_FROM,
              ['itcast88@163.com'],
              html_message=msg)
    return HttpResponse('ok')

 

7)在booktest/urls.py文件中配置。

url(r'^send/$',views.send),

8)啓動服務器,在瀏覽器中輸入以下網址:

http://127.0.0.1:8000/send/

郵件發送成功後,在郵箱中查看郵件以下圖:

3.2使用celery異步任務隊列發送郵件

情景:用戶發起request,並等待response返回。在本些views中,可能須要執行一段耗時的程序,那麼用戶就會等待很長時間,形成很差的用戶體驗,好比發送郵件、手機驗證碼等。

使用celery後,狀況就不同了。解決:將耗時的程序放到celery中執行。

celery名詞:

  • 任務task:就是一個Python函數。
  • 隊列queue:將須要執行的任務加入到隊列中。
  • 工人worker:在一個新進程中,負責執行隊列中的任務。
  • 代理人broker:負責調度,在佈置環境中使用redis。

安裝包:

celery==3.1.25
django-celery==3.1.17

1)在booktest/views.py文件中建立視圖sayhello。

import time
...
def sayhello(request):
    print('hello ...')
    time.sleep(2)
    print('world ...')
    return HttpResponse("hello world")

 

2)在booktest/urls.py中配置。

url(r'^sayhello$',views.sayhello),

3)啓動服務器,在瀏覽器中輸入以下網址:

http://127.0.0.1:8000/sayhello/

4)在終端中效果以下圖,兩次輸出之間等待一段時間纔會返回結果。

 

5)在test6/settings.py中安裝。

INSTALLED_APPS = (
  ...
  'djcelery',
}

 

6)在test6/settings.py文件中配置代理和任務模塊。

import djcelery
djcelery.setup_loader()
BROKER_URL = 'redis://127.0.0.1:6379/2'

 

7)在booktest/目錄下建立tasks.py文件。

import time
from celery import task

@task
def sayhello():
    print('hello ...')
    time.sleep(2)
    print('world ...')

 

8)打開booktest/views.py文件,修改sayhello視圖以下:

from booktest import tasks
...
def sayhello(request):
    # print('hello ...')
    # time.sleep(2)
    # print('world ...')
    tasks.sayhello.delay()
    return HttpResponse("hello world")

 

9)執行遷移生成celery須要的數據表。

python manage.py migrate

生成表以下:

 

10)啓動Redis,若是已經啓動則不須要啓動。

sudo service redis start

11)啓動worker。

python manage.py celery worker --loglevel=info

啓動成功後提示以下圖:

 

11)打開新終端,進入虛擬環境,啓動服務器,刷新瀏覽器。 在舊終端中兩個輸出間仍有時間間隔。

 

運行完成後以下圖,注意兩個終端中的時間,服務器的響應是當即返回的。

 

12)打開booktest/task.py文件,修改成發送郵件的代碼,就能夠實現無阻塞發送郵件。

from django.conf import settings
from django.core.mail import send_mail
from celery import task

@task
def sayhello():
    msg='<a href="http://www.itcast.cn/subject/pythonzly/index.shtml" target="_blank">點擊激活</a>'
    send_mail('註冊激活','',settings.EMAIL_FROM,
              ['itcast88@163.com'],
              html_message=msg)
相關文章
相關標籤/搜索