django-第三方

6.第三方javascript

經常使用的第三方包或工具

富文本編輯器html

緩存java

全文檢索python

celerymysql

佈署linux

6.1.富文本編輯器

藉助富文本編輯器,管理員可以編輯出來一個包含html的頁面,從而頁面的顯示效果,能夠由管理員定義,而不用徹底依賴於前期開發人員nginx

此處以tinymce爲例,其它富文本編輯器的使用能夠自行學習web

使用編輯器的顯示效果爲:redis

 

 

下載安裝

在網站pypi網站搜索並下載"django-tinymce-2.7.0"sql

解壓

tar zxvf django-tinymce-2.7.0.tar.gz

進入解壓後的目錄,工做在虛擬環境,安裝

python setup.py install

也能夠直接pip安裝

pip install django-tinymce

應用到項目中

找到 tinymce的目錄 個人目錄以下 E:\Virtualenv\testenv\Lib\site-packages\tinymce找到後直接複製該文件到 你的項目文件裏面

在settings.py中爲INSTALLED_APPS添加編輯器應用

INSTALLED_APPS = (
...

    'tinymce',
    'booktest',

)

在settings.py中添加編輯配置項

TINYMCE_DEFAULT_CONFIG = {

    'theme': 'advanced',
    'width': 600,
    'height': 400,

}

在根urls.py中配置

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^tinymce/', include('tinymce.urls'))
]

在應用中定義模型的屬性

# -*- coding:utf-8 -*-

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

class HeroInfo(models.Model):

    hcontent = HTMLField()

在amin.py中註冊定義的模型

from django.contrib import admin
from models import HeroInfo

admin.site.register(HeroInfo)

 

在後臺管理界面中,就會顯示爲富文本編輯器,而不是多行文本框

自定義使用

配置url

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

定義視圖editor,用於顯示編輯器並完成提交

def editor(request):

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

建立模板editor.html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>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,

        'heigh': 100

    })

</script>

</head>

<body>

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

    {% csrf_token %}

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

    <br>

    <textarea name="hcontent">武功絕學</textarea>

    <br>

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

</form>

</body>

</html>
editor.html
 

添加url項

urlpatterns = [
    ...

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

]

定義視圖content,接收請求,並更新heroinfo對象

def content(request):

    hname = request.POST['hname']
    hcontent = request.POST['hcontent']


    heroinfo = HeroInfo()
    heroinfo.hname = hname
    heroinfo.hcontent = hcontent
    heroinfo.save()

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

定義模板content.html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

<p>

    姓名:{{hero.hname}}

</p>

<hr/>

{% autoescape off %}

{{hero.hcontent}}

{% endautoescape %}

</body>

</html>
content.html

 

6.2. 緩存

對於中等流量的網站來講,儘量地減小開銷是必要的。緩存數據就是爲了保存那些須要不少計算資源的結果,這樣的話就沒必要在下次重複消耗計算資源

Django自帶了一個健壯的緩存系統來保存動態頁面,避免對於每次請求都從新計算

Django提供了不一樣級別的緩存粒度:能夠緩存特定視圖的輸出、能夠僅僅緩存那些很難生產出來的部分、或者能夠緩存整個網站

設置緩存

經過設置決定把數據緩存在哪裏,是數據庫中、文件系統仍是在內存中

經過setting文件的CACHES配置來實現

參數TIMEOUT:緩存的默認過時時間,以秒爲單位,這個參數默認是300秒,即5分鐘;設置TIMEOUT爲None表示永遠不會過時,值設置成0形成緩存當即失效。默認利用本地的內存來當緩存。

CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 60,
}
}

能夠將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')
#return HttpResponse('hello2')

 

cache_page接受一個參數:timeout,秒爲單位,上例中緩存了15分鐘

視圖緩存與URL無關,若是多個URL指向同一視圖,每一個URL將會分別緩存

模板片段緩存

使用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.3. 全文檢索

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

haystack:django的一個包,能夠方便地對model裏面的內容進行索引、搜索,設計爲支持whoosh,solr,Xapian,Elasticsearc四種全文檢索引擎後端,屬於一種全文檢索的框架

whoosh:純Python編寫的全文搜索引擎,雖然性能比不上sphinx、xapian、Elasticsearc等,可是無二進制包,程序不會莫名其妙的崩潰,對於小型的站點,whoosh已經足夠使用

jieba:一款免費的中文分詞包,若是以爲很差用可使用一些收費產品

操做

在虛擬環境中依次安裝包

pip install django-haystack
pip install whoosh
pip install jieba

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

在項目的urls.py中添加url

urlpatterns = [
    ...
    url(r'^search/', include('haystack.urls')),
]

在應用目錄下創建search_indexes.py文件

# -*- coding: utf-8 -*-

from haystack import indexes

from models import HeroInfo





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

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



    def get_model(self):

        return HeroInfo



    def index_queryset(self, using=None):

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

在目錄「templates/search/indexes/應用名稱/」下建立「模型類名稱_text.txt」文件

#goodsinfo_text.txt,這裏列出了要對哪些列的內容進行檢索
{{object.hname}}

在目錄「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.hname }}</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>
search.html

創建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()
ChinesaAnalyzer.py

 8.複製whoosh_backend.py文件,更名爲whoosh_cn_backend.py

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

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

 

生成索引

初始化索引數據

python manage.py rebuild_index

在模板中建立搜索欄

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

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

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

    <input type="submit" value="搜索">

</form>

</body>

</html>
search.html

 

6.4. celery

官方網站

中文文檔

示例一:用戶發起request,並等待response返回。在這些views中,可能須要執行一段耗時的程序,那麼用戶就會等待很長時間,形成很差的用戶體驗

示例二:網站每小時須要同步一次天氣預報信息,可是http是請求觸發的,難道要一小時請求一次嗎?

使用celery後,狀況就不同了

示例一的解決:將耗時的程序放到celery中執行

示例二的解決:使用celery定時執行

名詞

任務task:就是一個Python函數

隊列queue:將須要執行的任務加入到隊列中

工人worker:在一個新進程中,負責執行隊列中的任務

代理人broker:負責調度,在佈置環境中使用redis

使用

安裝包

pip install celery
pip install celery-with-redis
pip install django-celery 

配置settings

INSTALLED_APPS = (
    ...
    'djcelery',
)

...
 
import djcelery


djcelery.setup_loader()

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

CELERY_IMPORTS = ('booktest.task')

 

在應用目錄下建立task.py文件

# -*- coding: utf-8 -*-

import django

django.setup()

import time

from celery import task



@task

def sayhello():

    print('hello...')

    time.sleep(5)

    print('world...')
task.py

遷移,生成celery須要的數據表

python manage.py migrate

啓動Redis

redis-server --service-start

啓動worker

python manage.py celery worker --loglevel=info

調用語法

function.delay(parameters)

使用代碼

from task import *
 
def celeryTest(request):
    #sayhello()
   
sayhello.delay()
    return HttpResponse('OK')

6.5. 部署

從uwsgi、nginx、靜態文件三個方面處理

服務器介紹

服務器:私有服務器、公有服務器

私有服務器:公司本身購買、本身維護,只佈署本身的應用,可供公司內部或外網訪問

公有服務器:集成好運營環境,銷售空間或主機,供其佈署本身的應用

私有服務器成本高,須要專業人員維護,適合大公司使用

公有服務器適合初創公司使用,成本低

經常使用的公有服務器,如阿里雲、青雲等,可根據須要,按流量收費或按時間收費

此處的服務器是物理上的一臺很是高、線路全、運行穩定的機器

服務器環境配置

在本地的虛擬環境中,項目根目錄下,執行命令收集全部包

pip freeze > plist.txt

經過ftp軟件將開發好的項目上傳到此服務器的某個目錄

安裝並建立虛擬環境,若是已有則跳過此步

sudo apt-get install python-virtualenv
sudo easy_install virtualenvwrapper
mkvirtualenv [虛擬環境名稱]

若是出現下面的提示,須要初始配置

 

 

默認virtualenvwrapper安裝在/usr/local/bin下面,實際上須要運行virtualenvwrapper.sh文件才行;因此須要先進行配置一下:

建立虛擬環境管理目錄: mkdir $HOME/.local/virtualenvs

添加環境變量,在~/.bashrc中添加行:

#  老是使用 pip/distribute                            

export VIRTUALENV_USE_DISTRIBUTE=1                                                             

# 全部虛擬環境存儲的目錄

export WORKON_HOME=$HOME/.local/virtualenvs                  

if [ -e $HOME/.local/bin/virtualenvwrapper.sh ];then                                                                                                       

source $HOME/.local/bin/virtualenvwrapper.sh                                                                                                         

else if [ -e /usr/local/bin/virtualenvwrapper.sh ];then                                                                                                    

source /usr/local/bin/virtualenvwrapper.sh                                                                                                       

fi                                                                                                                                                     

fi                                                                                                                                                         

export PIP_VIRTUALENV_BASE=$WORKON_HOME                                                                                                                     

export PIP_RESPECT_VIRTUALENV=true   

啓動 virtualenvwrapper: source ~/.bashrc

在虛擬環境上工做,安裝全部須要的包

workon [虛擬環境名稱]
pip install -r plist.txt
當:linux EnvironmentError: mysql_config not found

 

 
 

更改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= 192.168.0.103:9000(使用nginx鏈接時,使用socket)
http= 192.168.0.103:8080(直接作web服務器,使用http)
chdir=項目根目錄
wsgi-file=項目中wsgi.py文件的目錄,相對於項目根目錄
processes=4
threads=2
master=True
pidfile=uwsgi.pid
daemonize=uwsgi.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 install nginx

這裏如下載壓縮文件爲例演示

解壓縮:
tar zxvf nginx-1.6.3.tar.gz
 
進入nginx-1.6.3目錄依次執行以下命令進行安裝:
./configure
make
sudo make install

查看版本:nginx -v

啓動:/etc/init.d/nginx start

中止:/etc/init.d/nginx stop

重啓:/etc/init.d/nginx restart

經過瀏覽器查看nginx運行結果

指向uwsgi項目:編輯/etc/nginx/nginx.conf 文件

sudo vim /etc/nginx/nginx.conf
 
server {
listen       80;
server_name  192.168.0.118;
location / {
include uwsgi_params; #將全部的參數轉到uwsgi下
uwsgi_pass 192.168.0.118:9000; #uwsgi.ini裏面socket對應的ip和端口
}      
}

修改uwsgi.ini文件,啓動socket,禁用http

重啓nginx、uwsgi

在瀏覽器中查看項目,發現靜態文件加載不正常,接下來解決靜態文件的問題

靜態文件

靜態文件一直都找不到,如今終於能夠解決了

全部的靜態文件都會由nginx處理,不會將請求轉到uwsgi

配置nginx的靜態項,打開/etc/nginx/nginx.conf文件,找到server,添加新location

location /static {
alias /home/zsl/test6/static/;
}

建立static目錄

mkdir static

最終目錄結構以下圖:

 

 

修改settings.py文件

STATIC_ROOT='/home/zsl/test6/static/'
STATIC_URL='/static/'

收集全部靜態文件到static_root指定目錄:python manage.py collectstatic

重啓nginx、uwsgi

6.6. 總結與做業

總結

富文本編輯器

緩存

全文檢索

celery

佈署

相關文章
相關標籤/搜索