将数据返回到表python中或将其发送到ajax请求

时间:2019-02-18 01:18:29

标签: javascript python html

from flask import Flask, render_template, request
from flask import jsonify
import io ,os
import numpy as np
import json
import ast
import sys
app = Flask(__name__)
from flask import Flask, render_template, request ,session
from werkzeug import secure_filename
app = Flask(__name__ , template_folder=os.getcwd())
import search_new
global w2v_model
import threading
import logging

@app.before_first_request
def activate_job():
    def run_job():
        global w2v_model
        logging.warning('loading model')
        print("Run recurring task")
        print ("loading model")
        from gensim.models.keyedvectors import KeyedVectors
        model_path = 'GoogleNews-vectors-negative300.bin'
        w2v_model= KeyedVectors.load_word2vec_format(model_path, binary=True) 
        #with app.app_context():
            #session['w2v_model'] =  KeyedVectors.load_word2vec_format(model_path, binary=True) 
        print ("model_loaded")
        logging.warning('model_loaded')
    thread = threading.Thread(target=run_job)
    thread.start()
@app.route('/')
def upload_file():
    try :
        return render_template('upload.html')
    except Exception as e :
        logging.warning(str(e))
        result_dict={"error":str(e)}
        return jsonify(result_dict)

@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file1():
    global w2v_model
    try:
    #w2v_model = session.get('w2v_model', None)
        if request.method == 'POST':
            file_id = '1-jLh3Zdi-gwIFEnrw0VKQnoLH8mof2hN'
            destination = os.getcwd()+"//search_strings.docx"
            download_file_from_google_drive(file_id, destination)
            f1 = request.files['file1']
            f1.save(secure_filename(f1.filename.replace(" ", "_")))
            #f2 = request.files['file2']
            #f2.save(secure_filename(f2.filename.replace(" ", "_")))
            logging.warning (f1.filename.replace(" ", "_"),w2v_model)
            questions,answers,results,flag=search_new.main(f1.filename.replace(" ", "_"),"search_strings.docx",w2v_model)
            if (flag):
                return jsonify({'error':"Documents with .doc extensions are not supported"})
            result_dict={}
            i=1
            for item1 , item2,item3 in zip (questions,answers,results):
                result_dict['{0}_question'.format(i)]=str(item1)
                result_dict['{0}_answer'.format(i)]=str(item2)
                j=1
                for item in item3 :
                    result_dict['{0}_{1}_coinfidence'.format(i,j)]=str(item[1])
                    result_dict['{0}_{1}_paragraph'.format(i,j)]=str(item[0])
                    j+=1
                i+=1
    except Exception as e :
        result_dict={"error":str(e)}
    return jsonify(result_dict)


import requests

def download_file_from_google_drive(id, destination):
    URL = "https://docs.google.com/uc?export=download"

    session = requests.Session()

    response = session.get(URL, params = { 'id' : id }, stream = True)
    token = get_confirm_token(response)

    if token:
        params = { 'id' : id, 'confirm' : token }
        response = session.get(URL, params = params, stream = True)

    save_response_content(response, destination)    

def get_confirm_token(response):
    for key, value in response.cookies.items():
        if key.startswith('download_warning'):
            return value

    return None

def save_response_content(response, destination):
    CHUNK_SIZE = 32768

    with open(destination, "wb") as f:
        for chunk in response.iter_content(CHUNK_SIZE):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)

if __name__ == '__main__':
    logging.warning('main')
    app.run(debug=True,host='0.0.0.0',port=8000)

我有这个python文件,其中html文件:upload.html,它具有上传完成后的表单上传文件python文件返回json数据返回jsonify(result_dict)我想在表中而不是json格式显示数据,或者发送给请求并通过ajax获取它,而无需重定向到功能文件

0 个答案:

没有答案