Exemplo n.º 1
0
def ad_content_edit(request):
    """
    数据管理添加,编辑
    :param request:
    :return:
    """
    action = getattr(request, request.method).get('action', None)
    if action is None:
        return HttpResponseRedirect(reverse("404"))
    if request.method == 'GET':
        if action == 'add':
            title = "添加"
            return render(request, 'table/ad-content-edit.html', locals())
        if action == 'edit':
            title = "编辑"
            _id = ObjectId(request.GET.get('_id'))

            db = get_db()
            content = db.ebf_qq.find_one({'_id': _id})
            system_time = utc2local(
                content['system_time']).strftime("%Y-%m-%d %H:%M:%S")
            content = {
                key.strip('_'): str(value)
                for key, value in content.items()
            }
            return render(request, 'table/ad-content-edit.html', locals())

    elif request.method == 'POST':
        try:
            if action == 'add':
                system_time = request.POST.get('system_time', None)
                online_number = request.POST.get('online_number', None)
                content = {
                    'online_number': online_number,
                    'system_time': system_time
                }
                db = get_db()
                posts = db.ebf_qq
                posts.insert(content)
                return HttpResponse(json.dumps({"status": 0}))
            elif action == 'edit':
                _id = request.POST.get('_id', None)
                online_number = request.POST.get('online_number', None)
                content = {
                    'online_number': online_number,
                    'system_time': datetime.datetime.utcnow()
                }
                db = get_db()
                posts = db.ebf_qq
                _id = ObjectId(_id)
                posts.update({"_id": _id}, content)
                return HttpResponse(json.dumps({"status": 0}))
        except Exception as e:
            print(e)
            return HttpResponse(json.dumps({"status": -1}))
    else:
        return HttpResponseRedirect(reverse("404"))
Exemplo n.º 2
0
def ajax_run(request):
    try:
        # 从mongodb数据库中获取数据
        db = get_db()
        system_time = []
        run_time = []
        weight = []
        for u in db.ebf_weight.find().sort([("system_time", -1)])[:31]:
            system_time.append(
                utc2local(u['system_time']).strftime("%Y-%m-%d %H:%M:%S"))
            run_time.append(float(u['run_time']))
            weight.append(float(u['weight']))
        time = json.dumps(system_time[::-1])
        number_run = json.dumps(run_time[::-1])
        number_wei = json.dumps(weight[::-1])

        if not isinstance(time, str) or not isinstance(
                number_run, str) or not isinstance(number_wei, str):
            time = time.decode("utf-8")
            number_run = number_run.decode("utf-8")
            number_wei = number_wei.decode("utf-8")
        name_dict = {
            'system_time': time,
            'number_run': number_run,
            'number_wei': number_wei
        }
        return JsonResponse(name_dict)
    except Exception as e:
        logging.error(e)
        return HttpResponse(
            '<html><script type="text/javascript">alert("从mongodb获取数据失败"); '
            'window.location="/main"</script></html>')
Exemplo n.º 3
0
def pc_qq():
    """实时查询qq在线人数
    """
    # 系统时间
    system_time = get_now_time()
    # 时间戳
    timestamp = str(
        int(time.mktime(time.strptime(system_time, '%Y-%m-%d %H:%M:%S'))))
    temporary = "http://mma.qq.com/cgi-bin/im/online&callback=jQuery19105562977448571473_" + timestamp + "?_=" + timestamp
    url = [temporary]
    print('QQ在线人数网页', temporary)
    cur_re = re.compile(r'"c":(.+?),"ec"', re.DOTALL)
    for ul in url:
        """
        html=urllib.request.urlopen(ul).read()
        codec =urllib.request.urlopen(ul).info().get_param('charset', 'utf8')
        html = html.decode(codec)
        """
        html = requests.get(ul)
        for online_number in cur_re.findall(html.text):
            print("QQ当前在线人数:" + online_number)

    db = get_db()
    post = {
        "online_number": online_number,
        "system_time": datetime.datetime.utcnow()
    }
    posts = db.ebf_qq
    posts.insert(post)
Exemplo n.º 4
0
def card_add(request):
    """
    发说说
    :param request:
    :return:
    """
    if request.method == 'GET':
        result = qq_face_path()
        return render(request, 'news/card-add.html', locals())
    elif request.method == 'POST':
        username = request.session["username"]
        result = sql_my_profile(username)
        new_content = request.POST.get("new_content", None)
        new_img = request.FILES.get('new_img', '')
        try:
            if new_img:
                handle_uploaded_file(request.FILES['new_img'], str(request.FILES['new_img']))
                new_img = "static/img/news/" + str(new_img)
            db = get_db()
            args = {
                # "new_id": str(get_now_time_stamp()) + str(uuid.uuid4()),  # 说说id
                "new_id": str(uuid.uuid4()),  # 说说id
                "username": result['username'],  # 用户名
                "nickname": result['nickname'],  # 用户昵称
                "upload_head": result['upload_head'],  # 用户头像
                "content": new_content,  # 说说内容
                "img": new_img,  # 说说图片
                "create_date": datetime.datetime.now().strftime('%Y-%m-%d %w %H:%M:%S')  # 发表时间
            }
            db.ebf_news.insert(args)
        except Exception as e:
            logging.error(e)
        return HttpResponseRedirect('/main')
Exemplo n.º 5
0
def mongodb_add(request):
    if request.method == 'GET':
        now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        return render(request, 'weight/mongodb-add.html', locals())
    elif request.method == 'POST':
        weight = request.POST.get('weight')
        run_time = request.POST.get('run_time')
        remark = request.POST.get('remark')
        if re.match(r"^[\d]*(\.{0,1})[\d]+$", weight) and re.match(
                r"^[\d]*(\.{0,1})[\d]+$",
                run_time) and not re.match(r"^\s*$/", remark):
            j_date_time = request.POST.get('system_time')
            # 把字符串转成datetime类型
            time = datetime.datetime.strptime(j_date_time, "%Y-%m-%d %H:%M:%S")
            system_time = local2utc(time)
            db = get_db()
            post = {
                "weight": weight,  # 体重
                "run_time": run_time,  # 跑步时长
                "system_time": system_time,  # 当前时间
                "remark": remark  # 备注
            }
            posts = db.ebf_weight
            posts.insert(post)
            return HttpResponseRedirect("/main")
        else:
            message = "数据格式错误"
            return render(request, 'weight/mongodb-add.html', locals())
Exemplo n.º 6
0
def card_thing(request):
    """
    赞
    :param request:
    :return:
    """
    if request.method == 'POST':
        new_id = request.POST.get('new_id', '')
        user = request.POST.get('user', '')
        db = get_db()
        result = db.ebf_news.find_one({"new_id": new_id})
        if new_id and user:
            if result.get('thing'):
                thing = json.loads(result['thing'])
                if user in thing:
                    thing.remove(user)
                else:
                    thing.append(user)
            else:
                thing = []
                thing.append(user)
            db.ebf_news.update({"new_id": new_id}, {"$set": {'thing': json.dumps(thing)}})
            ret = {"status": 0, "data": "赞成功"}
        else:
            ret = {"status": -1, "data": "缺少必要参数"}
        return HttpResponse(json.dumps(ret))
Exemplo n.º 7
0
def main(request):
    """
    说说列表
    :param request:
    :return:
    """
    username = request.session["username"]
    content = mongodb_username_card()
    new_id_content = []
    content_id_content = []
    week = {
        '1': '周一',
        '2': '周二',
        '3': '周三',
        '4': '周四',
        '5': '周五',
        '6': '周六',
        '0': '周日',
    }
    db = get_db()
    for i in content:
        i.pop('_id')
        item = i.get('content', '')
        time = i.get('create_date', '')
        if i.get('thing'):
            i['thing'] = json.loads(i['thing'])
        if time:
            before = time[:10]
            now = time[11]
            up = week[now]
            after = time[-8:]
            i['create_date'] = before + '/' + up + '/' + after
        item = font_to_img(item)
        temp = dict()
        temp['new_id'] = i.get('new_id')
        temp['content'] = item
        new_id_content.append(temp)
        thing_content = db.ebf_news_content.find({
            "new_id": i.get('new_id')
        }).sort('create_date', -1)
        thing_content = wrap_model(thing_content)
        for k in thing_content:
            k.pop('_id')
            k['content'] = font_to_img(k.get('content'))
            info = dict()
            info['content_id'] = k.get('content_id')
            info['content'] = font_to_img(k.get('content'))
            content_id_content.append(info)
        i['thing_content'] = thing_content
    result = qq_face_path()
    return render(request, 'news/card.html', locals())
Exemplo n.º 8
0
def mongodb_delete(request):
    id = getattr(request, request.method).get("id", None)
    u = query_query(request, id)
    db = get_db()
    try:
        _id = ObjectId(u[0]['id'])
        pos = db.ebf_weight.find_one({'_id': _id})
        db.ebf_weight.remove({"_id": pos["_id"]})
        return HttpResponse(
            '<html><script type="text/javascript">alert("删除成功"); '
            'window.location="/mongodb_query"</script></html>')
    except Exception as e:
        print('删除异常:', e)
        return HttpResponse(
            '<html><script type="text/javascript">alert("删除失败"); '
            'window.location="/mongodb_query"</script></html>')
Exemplo n.º 9
0
def messages_detail(request, num_id):
    """
    数据详情
    :param request:
    :param num_id:
    :return:
    """
    try:
        db = get_db()
        results = db.ebf_messages.find_one({'_id': ObjectId(num_id)})
        if results:
            message = None
        else:
            message = '没有数据'
    except Exception as e:
        logging.error(e)
    return render(request, 'messages/messages-detail.html', locals())
Exemplo n.º 10
0
def card_del(request):
    """
    删除说说
    :param request:
    :return:
    """
    new_id = request.GET.get('new_id', '')
    if new_id:
        try:
            db = get_db()
            db.ebf_news.remove({"new_id": new_id})
            ret = {"status": 0, "data": "删除成功"}
        except Exception as e:
            logging.exception(e)
            ret = {"status": -1, "data": "删除失败"}
    else:
        ret = {"status": -1, "data": "说说id为空"}
    return HttpResponse(json.dumps(ret))
Exemplo n.º 11
0
def content_detail(request, num_id):
    """
    数据详情
    :param request:
    :param num_id:
    :return:
    """
    try:
        db = get_db()
        results = db.ebf_qq.find_one({'_id': ObjectId(num_id)})
        if results:
            results['system_time'] = utc2local(
                results['system_time']).strftime("%Y-%m-%d %H:%M:%S")
            message = None
        else:
            message = '没有数据'
    except Exception as e:
        logging.error(e)
    return render(request, 'table/ad-content-detail.html', locals())
Exemplo n.º 12
0
def index_main(request):
    """
    首页
    :param request:
    :return:
    """
    db = get_db()
    objects = db.ebf_content.find()
    result = {}
    jinyan = []
    gonggao = []
    tongzhi = []
    wenjian = []
    xueshu = []
    for x in objects:
        # 把'_id'改为'id'
        r = {key.strip('_'): value for key, value in x.items()}
        type_type = r["type_type"]
        if type_type == "1":
            gonggao.append(r)
        elif type_type == "2":
            wenjian.append(r)
        elif type_type == "3":
            jinyan.append(r)
        elif type_type == "4":
            tongzhi.append(r)
        elif type_type == "5":
            xueshu.append(r)
    users_info = select_all_users(username="",
                                  user_type=2,
                                  status=1,
                                  min_date="",
                                  max_date="",
                                  field="create_time",
                                  order=1,
                                  skip=0,
                                  limit=5)
    fudaoyaun = [{
        "nickname": i["nickname"],
        "upload_head": i["upload_head"]
    } for i in users_info["items"]]
    return render(request, 'index1.html', locals())
Exemplo n.º 13
0
def ajax_dict(request):
    try:
        # 缓存
        import redis

        r = redis.Redis(host='localhost', port=6379, db=0)
        h = r.dbsize()
        try:
            number = r.get('online_number')
            time = r.get('system_time')
        except:
            number = ''
            time = ''
        if not number or not time:
            # 缓存中没有数据,从mongodb数据库中获取
            db = get_db()
            system_time = []
            online_number = []
            for u in db.ebf_qq.find().sort([("system_time", -1)])[:51]:
                system_time.append(
                    utc2local(u['system_time']).strftime("%Y-%m-%d %H:%M:%S"))
                online_number.append(int(u['online_number']))
            system_time = system_time[::-1]
            online_number = online_number[::-1]
            time = json.dumps(system_time)
            number = json.dumps(online_number)
            r.set('online_number', number)
            r.set('system_time', time)
            # 缓存中数据30秒过期
            r.expire('online_number', 30)
            r.expire('system_time', 30)
        if not isinstance(time, str) or not isinstance(number, str):
            time = time.decode("utf-8")
            number = number.decode("utf-8")
        name_dict = {'system_time': time, 'online_number': number}
        return JsonResponse(name_dict)
    except Exception as e:
        logging.getLogger('').info("读取缓存出错:" + str(e))
        return HttpResponse(
            '<html><script type="text/javascript">alert("redis服务未开启"); '
            'window.location="/main"</script></html>')
Exemplo n.º 14
0
def messages_delete(request):
    """
    删除数据
    :param request:
    :return:
    """
    if request.method == 'POST':
        # 数据id
        _id = ObjectId(request.POST.get('id'))
        if _id:
            try:
                db = get_db()
                pos = db.ebf_messages.find_one({'_id': _id})
                if pos is None:
                    return HttpResponse(json.dumps({"status": -1}))
                else:
                    db.ebf_messages.remove({"_id": pos["_id"]})
                return HttpResponse(json.dumps({"status": 0}))
            except Exception as e:
                print(e)
    return HttpResponse(json.dumps({"status": -1}))
Exemplo n.º 15
0
def mongodb_update(request):
    if request.method == 'GET':
        try:
            id = request.GET.get("id", None)
            res = query_query(request, id)
            rc = res[0]
            rc['system_time'] = datetime.datetime.now().strftime(
                '%Y-%m-%d %H:%M:%S')
            return render_to_response('weight/mongodb-update.html', {'d': rc})
        except Exception as e:
            print('修改异常:', e)
            return HttpResponse(
                '<html><script type="text/javascript">alert("修改异常"); '
                'window.location="/mongodb_query"</script></html>')
    elif request.method == 'POST':
        db = get_db()
        o_id = request.POST.get('id')
        try:
            _id = ObjectId(o_id)
        except Exception as e:
            print('查询异常:', e)
            return HttpResponse(
                '<html><script type="text/javascript">alert("_id错误"); '
                'window.location="/first"</script></html>')
        pos = db.ebf_weight.find_one({'_id': _id})
        weight = request.POST.get('weight')
        run_time = request.POST.get('run_time')
        remark = request.POST.get('remark')
        t = request.POST.get('system_time')
        # 把字符串转成datetime类型
        time = datetime.datetime.strptime(t, "%Y-%m-%d %H:%M:%S")
        system_time = local2utc(time)
        pos['weight'] = weight
        pos['run_time'] = run_time
        pos['remark'] = remark
        pos['system_time'] = system_time
        db.ebf_weight.update({"_id": pos['_id']}, pos)
        return HttpResponseRedirect('/main')
Exemplo n.º 16
0
def comment_thing(request):
    """
    评论
    :param request:
    :return:
    """
    if request.method == 'POST':
        new_id = request.POST.get('new_id', '')
        now_content = request.POST.get('now_content', '')
        user = request.session.get('username')
        if new_id and now_content and user:
            db = get_db()
            result = db.ebf_news.find_one({"new_id": new_id})
            content = {
                "content_id": str(uuid.uuid4()),  # 评论id
                "new_id": new_id,  # 说说id
                "now_user": user,  # 当前评论说说的用户
                "new_user": result.get('username'),  # 发表说说的用户
                "content": now_content,  # 评论内容
                "level": 1,  # 几级评论
                "create_date": datetime.datetime.now().strftime('%Y-%m-%d %w %H:%M:%S')  # 评论时间
            }
            repeat = {
                "new_id": new_id,  # 说说id
                "now_user": user,  # 当前评论说说的用户
                "new_user": result.get('username'),  # 发表说说的用户
                "content": now_content,  # 评论内容
                "level": 1,  # 几级评论
            }
            check_repeat = db.ebf_news_content.find_one(repeat)
            if not check_repeat:
                db.ebf_news_content.insert(content)
            ret = {"status": 0, "data": "评论成功"}
        else:
            ret = {"status": -1, "data": "缺少必要参数"}
        return HttpResponse(json.dumps(ret))
Exemplo n.º 17
0
def query_query(request, o_id):
    db = get_db()
    if not o_id:
        m = db.ebf_weight.find()
        u = []
        for x in m:
            # 把'_id'改为'id'
            x = {key.strip('_'): value for key, value in x.items()}
            x['system_time'] = utc2local(
                x['system_time']).strftime("%Y-%m-%d %H:%M:%S")
            u.append(x)
    else:
        try:
            _id = ObjectId(o_id)
            l = db.ebf_weight.find_one({'_id': _id})
            u = []
            l = {key.strip('_'): value for key, value in l.items()}
            l['system_time'] = utc2local(
                l['system_time']).strftime("%Y-%m-%d %H:%M:%S")
            u.append(l)
        except Exception as e:
            print('查询异常:', e)
            u = None
    return u
Exemplo n.º 18
0
def show_info(request, type_type):
    """
    分页数据
    :param request:
    :param type_type:
    :return:
    """
    if type_type == "1":
        head_tile = "公告"
    elif type_type == "2":
        head_tile = "教学文件"
    elif type_type == "3":
        head_tile = "经验交流"
    elif type_type == "4":
        head_tile = "通知"
    elif type_type == "5":
        head_tile = "学术期刊"
    elif type_type == "6":
        head_tile = "留言板"
    nav_mule = [
        {
            "url": "/",
            "class": "",
            "name": "首 页",
            "type_type": "/"
        },
        {
            "url": "show_info/1",
            "class": "",
            "name": "公 告",
            "type_type": "1"
        },
        {
            "url": "/show_info/2",
            "class": "",
            "name": "教学文件",
            "type_type": "2"
        },
        {
            "url": "/show_info/3",
            "class": "",
            "name": "经验交流",
            "type_type": "3"
        },
        {
            "url": "/show_counsellor",
            "class": "",
            "name": "辅导员风采",
            "type_type": "show_counsellor"
        },
        {
            "url": "/show_info/6",
            "class": "",
            "name": "留言板",
            "type_type": "6"
        },
        {
            "url": "/login",
            "class": "",
            "name": "登 录",
            "type_type": "login"
        },
    ]
    for i in nav_mule:
        if i["type_type"] == type_type:
            i["class"] = "active"
            break
    db = get_db()
    page_type = request.REQUEST.get('page_type', "")
    now_page = int(request.REQUEST.get('now_page', 1))
    title = request.REQUEST.get("title", "")
    if page_type == 'page_up':
        now_page -= 1
    elif page_type == 'page_down':
        now_page += 1
    elif page_type == 'jump':
        pass
    else:
        now_page = 1
    param = {}
    if title:
        param["title_title"] = title
    if type_type == '6':
        param["type_type"] = "2"
        objects = db.ebf_messages.find(param)
    else:
        param["type_type"] = type_type
        objects = db.ebf_content.find(param)
    number = 10
    if objects:
        new_objects = []
        for x in objects:
            # 把'_id'改为'id'
            r = {key.strip('_'): value for key, value in x.items()}
            new_objects.append(r)
        p = Paginator(new_objects, number)  # 每页10条数据的一个分页器
        count = p.count
        if now_page != 1 and now_page > count:
            if count == 0:
                now_page = 1
            else:
                now_page = count
        page_info = p.page(now_page)  # 第?页
        results = page_info.object_list  # 第?页的数据
    else:
        page_info = None
        results = None
    return render(request, 'show/show.html', locals())
Exemplo n.º 19
0
def ad_content_edit(request):
    """
    数据管理添加,编辑
    :param request:
    :return:
    """
    action = request.REQUEST.get('action', None)
    if action is None:
        return HttpResponseRedirect(reverse("404"))
    if request.method == 'GET':
        if action == 'add':
            title = "添加"
            return render(request, 'news/ad-content-edit.html', locals())
        if action == 'edit':
            title = "编辑"
            _id = ObjectId(request.GET.get('_id'))

            db = get_db()
            content = db.ebf_content.find_one({'_id': _id})
            content = {
                key.strip('_'): str(value)
                for key, value in content.items()
            }
            return render(request, 'news/ad-content-edit.html', locals())

    elif request.method == 'POST':
        try:
            if action == 'add':
                content_content = request.POST.get('content_content', None)
                type_type = request.POST.get('type_type', None)
                title_title = request.POST.get('title_title', None)
                content = {
                    'title_title':
                    title_title,
                    'content_content':
                    content_content,
                    'type_type':
                    type_type,
                    'create_time':
                    datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                }
                db = get_db()
                posts = db.ebf_content
                posts.insert(content)
                return HttpResponse(json.dumps({"status": 0}))
            elif action == 'edit':
                _id = request.POST.get('_id', None)
                title_title = request.POST.get('title_title', None)
                content_content = request.POST.get('content_content', None)
                type_type = request.POST.get('type_type', None)
                create_time = request.POST.get(
                    'create_time',
                    datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                content = {
                    'title_title': title_title,
                    'content_content': content_content,
                    'type_type': type_type,
                    'create_time': create_time
                }
                db = get_db()
                posts = db.ebf_content
                _id = ObjectId(_id)
                posts.update({"_id": _id}, content)
                return HttpResponse(json.dumps({"status": 0}))
        except Exception as e:
            print(e)
            return HttpResponse(json.dumps({"status": -1}))
    else:
        return HttpResponseRedirect(reverse("404"))
Exemplo n.º 20
0
def messages_edit(request):
    """
    数据管理添加,编辑
    :param request:
    :return:
    """
    action = request.REQUEST.get('action', None)
    message_name = request.session["username"]
    res = sql_my_profile(message_name)
    user_type = res['user_type']
    if action is None:
        return HttpResponseRedirect(reverse("404"))
    if request.method == 'GET':
        if action == 'add':
            title = "添加"
            return render(request, 'messages/messages-edit.html', locals())
        if action == 'edit':
            title = "编辑"
            _id = ObjectId(request.GET.get('_id'))

            db = get_db()
            content = db.ebf_messages.find_one({'_id': _id})
            content = {
                key.strip('_'): str(value)
                for key, value in content.items()
            }
            return render(request, 'messages/messages-edit.html', locals())

    elif request.method == 'POST':
        try:
            if action == 'add':
                content_content = request.POST.get('content_content', None)
                type_type = request.POST.get('type_type', None)
                title_title = request.POST.get('title_title', None)
                content = {
                    'title_title':
                    title_title,
                    'content_content':
                    content_content,
                    'reply_content':
                    "",
                    'type_type':
                    type_type,
                    'message_name':
                    message_name,
                    'create_time':
                    datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                }
                db = get_db()
                posts = db.ebf_messages
                posts.insert(content)
                return HttpResponse(json.dumps({"status": 0}))
            elif action == 'edit':
                _id = request.POST.get('_id', None)
                title_title = request.POST.get('title_title', None)
                content_content = request.POST.get('content_content', None)
                content = {
                    'title_title': title_title,
                    'content_content': content_content,
                }
                if user_type != 3:
                    reply_content = request.POST.get('reply_content', None)
                    content["reply_content"] = reply_content
                db = get_db()
                posts = db.ebf_messages
                _id = ObjectId(_id)
                old_content = posts.find_one({'_id': _id})
                old_content.update(content)
                posts.update({"_id": _id}, old_content)
                return HttpResponse(json.dumps({"status": 0}))
        except Exception as e:
            print(e)
            return HttpResponse(json.dumps({"status": -1}))
    else:
        return HttpResponseRedirect(reverse("404"))
Exemplo n.º 21
0
def get_now_time_stamp():
    # 亚洲上海时区
    tz = pytz.timezone('Asia/Shanghai')
    # 系统当前时间
    system_time = datetime.datetime.now(tz)
    # 时间戳
    timestamp = int(time.mktime(system_time.timetuple()))
    return timestamp


if __name__ == '__main__':
    a = get_now_time_stamp()
    print('a:', a)

    db = get_db()
    stamp_time = []
    system_time = []
    online_number = []
    other_time = []
    for u in db.posts.find().sort([("system_time", -1)])[:51]:
        # 时间戳
        timestamp = str(
            int(
                time.mktime(
                    time.strptime(str(u['system_time']),
                                  '%Y-%m-%d %H:%M:%S'))))
        # 时间数组
        time_array = time.localtime(
            time.mktime(
                time.strptime(str(u['system_time']), '%Y-%m-%d %H:%M:%S')))
Exemplo n.º 22
0
def rest_api(request):
    # 查询数据
    if request.method == "GET":
        _id = request.GET.get("_id", None)
        if _id:
            db = get_db()
            _id = ObjectId(_id)
            m = db.ebf_qq.find_one({'_id': _id})
            if m is None:
                data = {'data': 'QUERY Fail!'}
            else:
                data = {
                    "online_number": m["online_number"],
                    'system_time': m["system_time"]
                }
            return JsonResponse(data)
        return JsonResponse({"data": "data is null"})
    # 插入数据
    elif request.method == "POST":
        online_number = request.GET.get("online_number", None)
        system_time = request.GET.get("system_time", None)
        db = get_db()
        post = {"online_number": online_number, "system_time": system_time}
        posts = db.ebf_qq
        posts.insert(post)
        data = {'data': 'Insert Success!'}
        return JsonResponse(data)
    # 修改数据
    elif request.method == "PUT":
        _id = request.GET.get("_id", None)
        if _id:
            online_number = request.GET.get("online_number", None)
            system_time = request.GET.get("system_time", None)
            db = get_db()
            _id = ObjectId(_id)
            pos = db.ebf_qq.find_one({'_id': _id})
            if pos is None:
                data = {'data': 'Update Fail!'}
            else:
                pos['online_number'] = online_number
                pos['system_time'] = system_time
                db.ebf_qq.update({"_id": pos['_id']}, pos)
                data = {'data': 'Update Success!'}
            return JsonResponse(data)
    # 删除数据
    elif request.method == "DELETE":
        _id = request.GET.get("_id", None)
        if _id:
            db = get_db()
            _id = ObjectId(_id)
            pos = db.ebf_qq.find_one({'_id': _id})
            if pos is None:
                data = {'data': 'DELETE Fail!'}
            else:
                db.ebf_qq.remove({"_id": pos["_id"]})
                data = {'data': 'DELETE Success!'}
            return JsonResponse(data)
    # 其他情况
    else:
        data = {'data': 'There is no corresponding operation'}
        return JsonResponse(data)