天天看点

二维码生成,热点推荐,获取表的所有字段名

def qr_code_img(request):
    '''办税指南二维码'''
    face_id = request.session.get("userfaceid")
    print(face_id)
    user_to = request.POST.get('id')
    abs_url = request.build_absolute_uri()
    url_root = abs_url.split('/con')[0]
    qrcode_url = os.path.join(url_root, f'media/answer/{id}.html')
    print(qrcode_url)
    img = qrcode.make(qrcode_url)
    buf = BytesIO()  # 创建一个BytesIO临时保存生成图片数据
    img.save(buf)  # 将图片字节数据放到BytesIO临时保存
    image_stream = buf.getvalue()  # 在BytesIO临时保存拿出数据
    response = HttpResponse(image_stream, content_type="image/jpg")  # 将二维码数据返回到页面
    return response      

-----

def news(request):
    ''' 税务资讯接口 '''
    if request.method == 'POST':
        sql = "SELECT * FROM news"
        txt = pd.read_sql(sql, connection)
        txt["date0"] = pd.to_datetime(txt['date']).apply(lambda x: str(x)[:10])
        txt = txt.sort_values(by="date0", ascending=False)[:6]
        news_id = txt["id"].tolist()
        # news_time = txt["date0"].tolist()
        news_title = txt["title"].tolist()
        news_content = txt["content"].tolist()
        news_img = txt["img_url"].tolist()
        news_data = zip(news_id, news_title, news_content, news_img)
        news_data = list(news_data)
        abs_url = request.build_absolute_uri()
        url_root = abs_url.split('/con')[0]
        img_root = os.path.join(url_root, 'media/')
        result = {'code': 200, 'message': '热门搜索', 'data': {'news': []}}
        for new in news_data:
            if new[-1]:
                img_path = os.path.join(img_root, new[-1])
            else:
                img_path = None
            result['data']['news'].append(
                {'id': new[0], 'title': new[1], 'content': new[2], 'img': img_path}
            )
        return HttpResponse(json.dumps(result))      

-------

all

def recommends(request):
    ''' 返回热门关键字,热门搜索问答 '''
    # username = request.session.get("username")
    # userfaceid = request.session.get("userfaceid")
    # tourist_bool = False
    #流量+1
    visit_time = datetime.now()
    visit_count = VisitCount.objects.all()
    if visit_count:
        print('not first')
        visit_count[0].visit_count += 1
        visit_count[0].add_time = visit_time
        visit_count[0].save()
    else:
        print('first')
        VisitCount.objects.create(visit_count=1, add_time=visit_time)
    # add_one_sql = "UPDATE consult_visitcount SET visit_count=visit_count+1,add_time='%s'"%visit_time
    # add_one_cursor = connection.cursor()
    # add_one_cursor.execute(add_one_sql)
    # hot search key
    start_time = time.time()
    select_sql = 'select * from recommend_key'
    datas = pd.read_sql(select_sql, connection)  # <pandas.core.frame.DataFrame'>
    temp = datas.iloc[:, 1:-1]  # 取出所有数据的 除了前两个字段
    tp = temp.sum(axis=0)  # 所有字段纵向相加
    top_sorts = tp.sort_values(ascending=False)  # 降序排序
    top3 = top_sorts.index[:4]
    top_recommends = top3.values.tolist()
    result = {'code': 200, 'message': '热门搜索', 'data': {'hot': top_recommends}}
    # news
    # sql = "SELECT * FROM news"
    # txt = pd.read_sql(sql, connection)
    # txt["date0"] = pd.to_datetime(txt['date']).apply(lambda x: str(x)[:10])
    # txt = txt.sort_values(by="date0", ascending=False)
    # news_id = txt["id"].tolist()
    # # news_time = txt["date0"].tolist()
    # news_title = txt["title"].tolist()
    # # news_content = txt["content"].tolist()
    # news_img = txt["img_url"].tolist()
    # news_data = zip(news_id, news_title, news_img)
    # news_data = list(news_data)
    # result['data'].update({'news': []})
    # abs_url = request.build_absolute_uri()
    # url_root = abs_url.split('/con')[0]
    # img_root = os.path.join(url_root, 'media/news/source/')
    # for new in news_data:
    #     if new[-1]:
    #         img_path = os.path.join(img_root, new[-1])
    #     else:
    #         img_path = None
    #     result['data']['news'].append(
    #         {'id': new[0], 'title': new[1], 'img': img_path}
    #     )
    # 热搜榜
    hot_part = AsksAnswer.objects.values("id", "part", "class4", "answer", "clicked_num").order_by('-clicked_num')[:5]
    result['data'].update({'hot_part': []})
    for hot in hot_part:
        # result['data']['hot_part'].append(
        #     {'id': hot['id'], 'part': hot['part'], 'title': hot['class4'], 'answer': hot['answer']}
        # )
        result['data']['hot_part'].append(
            {'title': hot['class4']}
        )
    print(f'end time: {time.time()-start_time}')
    return HttpResponse(json.dumps(result))      

 --字段名--

from django.apps import apps      
modelobj = apps.get_model('consult', 'RecommendKey')
        
fileds = modelobj._meta.fields
        
fileds_name = [f.name for f in fileds if f.name == search_key]