Daimon Blog

山在那里

Django Cheatsheet

django的常用程序片断。

FileResponse / FileField 的相关处理

  • 把一个文件存入FileField

    下面的result_fileFieldField类型

    def do_unique(self, req, qs):
        """文件去重"""
        if qs.count() != 1:
            self.message_user(req, '必须且仅可选择一个文件进行比较。', ERROR)
        else:
            obj: m.Upload = qs.first()
            result_file, total, result, diff = yd.biz.do_it_all(obj.db_file.path)
            from django.core.files import File
    
            result_file_name = os.path.basename(result_file)
            obj.result_file.save(result_file_name, File(open(result_file)), save=False)
            obj.status = '完成'
            obj.msg = f'原 {total} 条,去重后 {result} 条,删除 {diff} 条'
            obj.save()
            self.message_user(req, obj.msg, messages.SUCCESS)
  • media_root目录下的某个文件存入FileField

    def do_unique(self, req, qs):
        """文件去重"""
        if qs.count() != 1:
            self.message_user(req, '必须且仅可选择一个文件进行比较。', ERROR)
        else:
            obj: m.Upload = qs.first()
            result_file, total, result, diff = yd.biz.do_it_all(obj.db_file.path)
            relative_path = os.path.relpath(result_file, settings.MEDIA_ROOT)
            obj.result_file.name = relative_path
            obj.status = '完成'
            obj.msg = f'原 {total} 条,去重后 {result} 条,删除 {diff} 条'
            obj.save()
            self.message_user(req, obj.msg, messages.SUCCESS)
  • 把一个字符串存入FileField

    result_file_name = os.path.basename(obj.compare_file.name + '.compare.csv')
    from django.core.files.base import ContentFile
    obj.result_file.save(result_file_name, ContentFile(result), save=False)
    obj.status = '完成'
    obj.save()
    self.message_user(req, '处理完成', messages.SUCCESS)

django admin action 请用户提供信息

http://tech.willandskill.se/custom-django-admin-2/

把celery worker作成服务

http://docs.celeryproject.org/en/latest/userguide/daemonizing.html

  • celery配置文件

    mkdir /etc/conf.d
    vi /etc/conf.d/celery
    # Name of nodes to start
    # here we have a single node
    CELERYD_NODES="w1"
    # or we could have three nodes:
    #CELERYD_NODES="w1 w2 w3"
    
    # Absolute or relative path to the 'celery' command:
    CELERY_BIN="/home/pi/.local/share/virtualenvs/iot1-Ffl3idFE/bin/celery"
    #CELERY_BIN="/virtualenvs/def/bin/celery"
    
    # App instance to use
    # comment out this line if you don't use an app
    # config.celery包应该存在
    CELERY_APP="config"
    # or fully qualified:
    #CELERY_APP="proj.tasks:app"
    
    # How to call manage.py
    CELERYD_MULTI="multi"
    
    # Extra command-line arguments to the worker
    CELERYD_OPTS="--time-limit=300 --concurrency=4"
    
    # - %n will be replaced with the first part of the nodename.
    # - %I will be replaced with the current child process index
    #   and is important when using the prefork pool to avoid race conditions.
    CELERYD_PID_FILE="/home/pi/src/iot1/logs/celery-worker-%n.pid"
    CELERYD_LOG_FILE="/home/pi/src/iot1/logs/celery-worker-%n%I.log"
    CELERYD_LOG_LEVEL="INFO"
  • celery 启动脚本

    vi /etc/systemd/system/celery.service

这个地方没有要修改的。

[Unit]
Description=Celery Service
After=network.target

[Service]
Type=forking
User=celery
Group=celery
EnvironmentFile=/etc/conf.d/celery
WorkingDirectory=/opt/celery
ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} \
  -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \
  --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}'
ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} \
  --pidfile=${CELERYD_PID_FILE}'
ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} \
  -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \
  --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}'

[Install]
WantedBy=multi-user.target
  • 最后再启动下,就ok了

    systemctl enable celery
    systemctl start celery

独立使用django

# 独立使用django
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'config.settings'
import django
django.setup()

django中混用vue/jquery

直接上代码。

  • admin.py

    @admin.register(m.Light)
    class LightAdmin(admin.ModelAdmin):
    class Media:
        css = {
            "all": (
                # "//cdn.bootcss.com/pure/1.0.0/pure-min.css",
                "iot1/lightadmin.css",
            )
        }
        js = (
            "//cdn.bootcss.com/vue/2.5.17-beta.0/vue.min.js",
            "//cdn.bootcss.com/jquery/1.12.4/jquery.js",
            "iot1/lightadmin.js",
            "//cdn.bootcss.com/layer/2.3/layer.js",
            # 这个require要放在最后。要不会卡住,其它js不运行了
            "//cdn.bootcss.com/require.js/2.3.6/require.min.js",
        )
    list_display = ('id', 'code', 'counter', 'status', 'power', 'voltage', 'last_measure_on', 'field_operation')
    
    def field_operation(self, obj):
        # return '播放'
        html = """        
           <button class="button-xsmall pure-button" @click="viewLocations({obj.id})" type="button">位置</button>
           """.format(obj=obj)
        return mark_safe(html)
  • iot1/lightadmin.js

    window.onload = function () {
    var app = new Vue({
    el: '#container',
    data: {
      msg: 'Hello Vue!'
    },
    created: function () {
      // 再运行一次actions,因为vue会把一些dom结构破坏掉。再运行一次,以便django的功能恢复
      require(["/static/admin/js/actions.js"])
    },
    methods: {
      viewLocations(id) {
        alert(id)
      }
    }
    })
    }
    

文章分类目录