博客园 错误笔记 时间格式转换,图片,orm,发消息缓存

1、url 参数都是不带引号的

2、时间格式需要转换才能json  look_result.date_joined.strftime("%Y-%m-%d %H:%M:%S")

3、json转换时间格式

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import datetime
class CJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if  isinstance(type(obj),type(datetime.datetime)):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        # elif isinstance(obj, date):
        #     return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj) 
json转换时间格式
body =json.dumps(data,cls=CJsonEncoder)
 4、ajax取数据时字典通过.来实现
5、rabbitmq队列的深入了解
#_*_coding:utf-8_*_
__author__ = 'Alex Li'


from  Weibo import settings
import pika
import json,time
class QueueMan(object):
    '''负责消息的发送, 接收'''
    def __init__(self):
        self.channel = None

    def make_conn(self):
        self.connection =  pika.BlockingConnection(pika.ConnectionParameters(
               '192.168.11.44'))
        self.channel = self.connection.channel()

    def publish_new_wb(self,wb_data):
        '''发新wb'''
        #声明queue
        self.channel.queue_declare(queue='wb_create_queue')

        #n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
        self.channel.basic_publish(exchange='',
                              routing_key='wb_create_queue',
                              body=json.dumps(wb_data) )
        print(" [x] Sent ",wb_data)

    # 回调函数
    def on_response(self, ch, method, props, body):
        print("new wb is comming ...",ch, method, props, body)
        self.new_wb_list.append(json.loads(body.decode()))
        self.response = True

    def get_new_wbs(self,queue_name):
        '''返回此用户队列里新微博条数'''
        self.response = None
        self.new_wb_list = []
        status = self.channel.queue_declare(queue=queue_name)
        print("[%s] message count "%queue_name,status.method.message_count)

        return status.method.message_count
        # consume_obj = self.channel.basic_consume(self.on_response, no_ack=True,
        #                    queue=queue_name)
        #
        # timer = time.time()
        # while self.response is None:
        #     self.connection.process_data_events()
        #     if time.time() - timer >10:
        #         print("\033[41;1mno new msg for 10secs , break...\033[0m")
        #         self.connection._flush_output()
        #         self.connection.close()
        #         break
        # return self.new_wb_list

    def load_new_wbs(self,queue_name):
        '''
        返回此用户的新wb列表
        :param queue_name:
        :return:
        '''
        self.response = None
        self.new_wb_list = []
        status = self.channel.queue_declare(queue=queue_name)
        print("[%s] message count "%queue_name,status.method.message_count)

        consume_obj = self.channel.basic_consume(self.on_response, no_ack=True,
                           queue=queue_name)

        self.connection.process_data_events()
        print(" self.connection.process_data_events()")
        self.connection._flush_output()
        print("self.connection._flush_output()")
        self.connection.close()
        print("self.connection.close()")
        # timer = time.time()
        # while self.response is None:
        #     self.connection.process_data_events()
        #     if time.time() - timer >10:
        #         print("\033[41;1mno new msg for 10secs , break...\033[0m")
        #         self.connection._flush_output()
        #         self.connection.close()
        #         break
        return self.new_wb_list
rabbitmq

 6、图片上传:

文件夹下的所有的文件名

import os
print(os.listdir(r"C:\Users\Administrator\Desktop\weibo_all\Weibo5\Static\images"))

本地展示:

<input type="file" id="files" multiple />
<output id="list"></output>
function handleFileSelect(evt) {
    var files = evt.target.files;

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = 
          [
            '<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', 
            e.target.result,
            '" title="', escape(theFile.name), 
            '"/>'
          ].join('');
          
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
js

本地展示完,图片上传:

路径需要通过os.path 连接

    files = request.FILES.getlist('files')
    a = 1
    print('1', files)
    for i in files:
        print(111,i.name)
        path = r"C:\Users\Administrator\Desktop\weibo_all\Weibo2\Static\images"
        b= str(a)+".png"
        path2 = os.path.join(path,b)
        a+=1
        print(path2)
        bb = open(path2,"wb+")
        for k in i:
           bb.write(k)
        bb.close()
python
function handleFileSelect(evt) {
    var files = evt.target.files;
        console.log(files);
    var form = new FormData();


    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }
         form.append('files', f);
      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML =
          [
            '<img style="height:75px;width:75px;border: 1px solid #000; margin: 5px" src="',
            e.target.result,
            '" title="', escape(theFile.name),
            '"/>'
          ].join('');

          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
        $.ajax({
        'url':'/image',
        'type':'POST',
        'data':form,
        'dataType': "json",
        processData: false,  // tell jQuery not to process the data
        contentType: false,  // tell jQuery not to set contentType
        success: function(arg){
            $(arg).each(function () {
                var input='<input type="hidden" value='+this+'>';
                $('#img_list').append(input);
            })
        }
    });
  }

    document.getElementById('files').addEventListener('change', handleFileSelect, false);
js

 东大神代码

/**
 * Created by Administrator on 2016/9/23.
 */
$(function () {
    $('.emotion').qqFace({
        id: 'facebox',
        assign: 'saytext',
        path: '/static/plugins/emoji/arclist/'    //表情存放的路径
    });
    $(".sub_btn").click(function () {
        var str = $("#saytext").val();
        $("#show").html(replace_em(str));
    });


    $("#UploadImg").click(function () {
        $("#index_img").removeClass("hide");
    });

    $(".W_layer_close").click(function () {
        $("#index_img").addClass("hide");
    })


});

$(function () {
    form_data = new FormData();
    $('.drag_pic_list ').delegate('li', 'dblclick', function () {
        $(this).remove();
    })
});
// 得到浏览器版本
function getOs() {
    var OsObject = "";
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        return "MSIE";
    }
    if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) {
        return "Firefox";
    }
    if (isSafari = navigator.userAgent.indexOf("Safari") > 0) {
        return "Safari";
    }
    if (isCamino = navigator.userAgent.indexOf("Camino") > 0) {
        return "Camino";
    }
    if (isMozilla = navigator.userAgent.indexOf("Gecko/") > 0) {
        return "Gecko";
    }
}
// 上传图片本地预览
function localShowImage() {
    // IE浏览器获取图片路径
    this.getImgUrlByMSIE = function (fileid) {
        return document.getElementById(fileid).value;
    };
    // 非IE浏览器获取图片路径
    this.getImgUrlByUnMSIE = function (fileid) {
        var f = document.getElementById(fileid).files;
        var file_list = new Array();
        $(f).each(function () {
            file_list.push(window.URL.createObjectURL(this))
        });
        var fileobj = $('#upload')[0].files;
        $.each(fileobj,function (k,v) {
            form_data.append('img', v);
        });
        
        return file_list;
    };

    var imgsrc = "";
    var fid = "upload";
    if ("MSIE" == getOs()) {
        imgsrc = this.getImgUrlByMSIE(fid);
    } else {
        imgsrc = this.getImgUrlByUnMSIE(fid);
    }
    var prePosition = $('.drag_pic_list');
    if ($(imgsrc).children().length > 3) {
        alert('最多上传3张照片');
        return
    }

    // 将本地的图片放到form_data中去,ajax发送到后端

    $(imgsrc).each(function () {
        var li = document.createElement('li');
        var img = document.createElement('img');
        $(img).css({'width': '80px', 'height': '80px'});
        $(img).attr('src', this);
        $(li).append(img);
        prePosition.append(li);
    });

}

// 双击删除图片
// $(function () {
//     $('.drag_pic_list ').delegate('li', 'dblclick', function () {
//         $(this).remove();
//     })
// });

function Publish() {

    var weibo_content = $.trim($("#weibo-content").val());
    console.log(weibo_content, form_data);
    if (weibo_content.length == 0) {
        alert('请输入内容11111111111111');
        return;
    }
    form_data.append('weibo_content', weibo_content);
    form_data.append('user_id', 1);
    $.ajax({
        type: 'POST',
        url: '/publish_weibo/',
        data: form_data,
        processData: false,     // 这两行需要加上,不然jquery会自动对传输的数据进行转换
        contentType: false,
        dataType: 'json',
        success: function (callback) {

            console.log(callback);
            // var img_box = document.createElement('div')
            // if (callback.status) {
            //     var content = callback.content;
            //     for (path in callback.img_path_list) {
            //         var imgobj = document.createElement('img');
            //         imgobj.src = '/static/' + callback.img_path_list[path];
            //         $(img_box).append(imgobj)
            //     }
            // }
            // $("#weibo-img").append(img_box);
            // $("#content").text(content);
            // $("#detail_pre_img").empty();
            // $("#weibo-content").val('');
        }
    })

}
图片长传多少张

 7、django orm

(1) 自带的后台操作 ,
    wb_type_choices = (
        (0,'new'),
        (1,'forward'),
        (2,'collect'),
    )
    wb_type = models.IntegerField(choices=wb_type_choices,default=0)
只有在后台的orm才行

(2)forward_or_collect_from = models.ForeignKey('self',related_name="forward_or_collects",blank=True,null=True)

外键自己管理自己,必须用关联对象反向描述
related_name 关联对象反向引用描述符。   blank admin 可以为空  null 数据库可以为空

8、消息队列

 

#_*_coding:utf-8_*_
__author__ = 'Alex Li'


from  Weibo import settings
import pika
import json,time
class QueueMan(object):
    '''负责消息的发送, 接收'''
    def __init__(self):
        self.channel = None

    def make_conn(self):
        self.connection =  pika.BlockingConnection(pika.ConnectionParameters(
               '192.168.11.44'))
        self.channel = self.connection.channel()

    def publish_new_wb(self,wb_data):
        '''发新wb'''
        #声明queue
        self.channel.queue_declare(queue='wb_create_queue')

        #n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
        self.channel.basic_publish(exchange='',
                              routing_key='wb_create_queue',
                              body=json.dumps(wb_data) )
        print(" [x] Sent ",wb_data)

    # 回调函数
    def on_response(self, ch, method, props, body):
        print("new wb is comming ...",ch, method, props, body)
        self.new_wb_list.append(json.loads(body.decode()))
        self.response = True

    def get_new_wbs(self,queue_name):
        '''返回此用户队列里新微博条数'''
        self.response = None
        self.new_wb_list = []
        status = self.channel.queue_declare(queue=queue_name)
        print("[%s] message count "%queue_name,status.method.message_count)

        return status.method.message_count
        # consume_obj = self.channel.basic_consume(self.on_response, no_ack=True,
        #                    queue=queue_name)
        #
        # timer = time.time()
        # while self.response is None:
        #     self.connection.process_data_events()
        #     if time.time() - timer >10:
        #         print("\033[41;1mno new msg for 10secs , break...\033[0m")
        #         self.connection._flush_output()
        #         self.connection.close()
        #         break
        # return self.new_wb_list

    def load_new_wbs(self,queue_name):
        '''
        返回此用户的新wb列表
        :param queue_name:
        :return:
        '''
        self.response = None
        self.new_wb_list = []
        status = self.channel.queue_declare(queue=queue_name)
        print("[%s] message count "%queue_name,status.method.message_count)

        consume_obj = self.channel.basic_consume(self.on_response, no_ack=True,
                           queue=queue_name)

        self.connection.process_data_events()
        print(" self.connection.process_data_events()")
        self.connection._flush_output()
        print("self.connection._flush_output()")
        self.connection.close()
        print("self.connection.close()")
        # timer = time.time()
        # while self.response is None:
        #     self.connection.process_data_events()
        #     if time.time() - timer >10:
        #         print("\033[41;1mno new msg for 10secs , break...\033[0m")
        #         self.connection._flush_output()
        #         self.connection.close()
        #         break
        return self.new_wb_list
View Code

 

9、请求头加上CSRF

$.ajaxSetup({headers: {"X-CSRFToken": '{{ csrf_token }}'}});

 

 

posted @ 2016-09-22 14:46  若时光搁浅  阅读(275)  评论(0)    收藏  举报