python django -6 常用的第三方包或工具

时间:2017-07-25 10:13:28   收藏:0   阅读:1387

常用的第三方包或工具

富文本编辑器

下载安装

tar zxvf django-tinymce-2.4.0.tar.gz
python setup.py install

应用到项目中

INSTALLED_APPS = (
    ...
    ‘tinymce‘,
)
TINYMCE_DEFAULT_CONFIG = {
    ‘theme‘: ‘advanced‘,
    ‘width‘: 600,
    ‘height‘: 400,
}
urlpatterns = [
    ...
    url(r‘^tinymce/‘, include(‘tinymce.urls‘)),
]
from django.db import models
from tinymce.models import HTMLField

class HeroInfo(models.Model):
    ...
    hcontent = HTMLField()

自定义使用

def editor(request):
    return render(request, ‘other/editor.html‘)
urlpatterns = [
    ...
    url(r‘^editor/$‘, views.editor, name=‘editor‘),
]
<!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>
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})
urlpatterns = [
    ...
    url(r‘^content/$‘, views.content, name=‘content‘),
]
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
姓名:{{hero.hname}}
<hr>
{%autoescape off%}
{{hero.hcontent}}
{%endautoescape%}
</body>
</html>

缓存

设置缓存

CACHES={
    ‘default‘: {
        ‘BACKEND‘: ‘django.core.cache.backends.locmem.LocMemCache‘,
        ‘TIMEOUT‘: 60,
    }
}
安装包:pip install django-redis-cache

CACHES = {
    "default": {
        "BACKEND": "redis_cache.cache.RedisCache",
        "LOCATION": "localhost:6379",
        ‘TIMEOUT‘: 60,
    },
}
连接:redis-cli
切换数据库:select 1
查看键:keys *
查看值:get 键

单个view缓存

from django.views.decorators.cache import cache_page

@cache_page(60 * 15)
def index(request):
    return HttpResponse(‘hello1‘)
    #return HttpResponse(‘hello2‘)

模板片断缓存

{% load cache %}
{% cache 500 hello %}
hello1
<!--hello2-->
{% endcache %}

底层的缓存API

from django.core.cache import cache

设置:cache.set(键,值,有效时间)
获取:cache.get(键)
删除:cache.delete(键)
清空:cache.clear()

全文检索

操作

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

pip install django-haystack
pip install whoosh
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文件

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>

celery

名词

使用

celery==3.1.25
celery-with-redis==3.0
django-celery==3.1.17
INSTALLED_APPS = (
  ...
  ‘djcelery‘,
}

...

import djcelery
djcelery.setup_loader()
BROKER_URL = ‘redis://127.0.0.1:6379/0‘
CELERY_IMPORTS = (‘应用名称.task‘)
import time
from celery import task

@task
def sayhello():
    print(‘hello ...‘)
    time.sleep(2)
    print(‘world ...‘)
python manage.py migrate
sudo redis-server /etc/redis/redis.conf
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")

布署

服务器介绍

服务器环境配置

pip freeze > plist.txt
sudo apt-get install python-virtualenv
sudo easy_install virtualenvwrapper
mkvirtualenv [虚拟环境名称]
workon [虚拟环境名称]
pip install -r plist.txt
DEBUG = False
ALLOW_HOSTS=[‘*‘,]表示可以访问服务器的ip

WSGI

uWSGI

pip install uwsgi
[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

nginx

sudo apt-get nginx
解压缩:
tar zxvf nginx-1.6.3.tar.gz

进入nginx-1.6.3目录依次执行如下命令进行安装:
./configure
make
sudo make install
sudo conf/nginx.conf

在server下添加新的location项,指向uwsgi的ip与端口
location / {
    include uwsgi_params;将所有的参数转到uwsgi下
    uwsgi_pass uwsgi的ip与端口;
}

静态文件

location /static {
    alias /var/www/test5/static/;
}
sudo chmod 777 /var/www/test5
mkdir static

技术分享

 

STATIC_ROOT=‘/var/www/test5/static/‘
STATIC_URL=‘/static/‘
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!