简体   繁体   English

在烧瓶中缓存功能

[英]Caching a function in flask

I have this code that executes for around 9.2 secs locally on my machine. 我的这段代码在我的机器上本地执行大约9.2秒。 After deploying it to an AWS ec2 box the execution time raised up to 20secs. 将其部署到AWS ec2盒后,执行时间最多可提高20秒。

Since I haven't implemented any caching before, I am wondering am I able to cache the response of a specific function or I need to cache every POST I get externally. 由于之前没有实现任何缓存,所以我想知道是否可以缓存特定功能的响应,或者我需要缓存从外部获取的每个POST。

Essentially what I am asking for is how to cache the result of a POST, so whenever I ran it again, with the same arguments it uses the cache to faster response. 本质上,我要问的是如何缓存POST的结果,因此每当我再次运行它时,都使用相同的参数使用缓存来加快响应速度。

#!flask/bin/python
from flask import Flask, jsonify
from flask import request
import json
import nltk, string
import operator
from sklearn.feature_extraction.text import TfidfVectorizer
import re
from flask import make_response
import time
import access_json

app = Flask(__name__)

def output(word_list):
    start = time.time()
    #RUNNING ALGORITHM *****************
    comparison_words = get_synonyms(word_list) + word_list
    print(comparison_words)
    dict_sim = {}
    for i in json_list:
        dict_sim[i['jobId']] = cosine_sim(str(comparison_words), i['jobDescription'])
    sorted_sim = sorted(dict_sim.items(), key=operator.itemgetter(1), reverse = True)
    toplist = sorted_sim[:10]
    sort_toplist = list(map(operator.itemgetter(0), toplist))
    filter_toplist = (list(filter(lambda job: job['jobId'] in sort_toplist, json_list)))
    #print('Our top ten suggestion from SkillzMiner are those:\n')
    end = time.time()
    print (end-start)
    # for j in filter_toplist:
    #       print ('JobTitle: ' + j['jobTitle'] +
    #             '\nEmployer Name: ' + j['employerName'] +
    #             '\nLocation: ' + j['locationName'] +
    #             '\nReed Job URL ' + j['jobUrl'] +
    #             '\nJob Description: ' + cleanhtml(j["jobDescription"]))
    return filter_toplist

@app.route('/postjson', methods=['POST'])
def json_handler():
     content = request.get_json(force=True)
     word_list = access_json.read_parsed_JSON(content)
     return jsonify ({'jobs': output(word_list)})

   if __name__ == '__main__':
    app.run(debug=True)
    app.run(host='0.0.0.0', port=80)

PS I have ommited some non-related functions, this is not the full code. PS我省略了一些不相关的功能,这不是完整的代码。 Apologise for the terminology, I am new to this web services. 抱歉,我是这个Web服务的新手。

Does the caching need to be local and user specific? 缓存是否需要是本地的和特定于用户的?

Have you tried caching in session variables like session['my_variable'] = my_response 您是否尝试过在会话变量(例如session ['my_variable'] = my_response)中进行缓存

That should work for a users local sessions as long as they don't, for example, visit in incognito mode. 只要用户本地会话(例如,以隐身模式访问),它们就应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM