[英]How to stop memory memory leak from Flask and NLTK
我正在使用NLTK和Flask構建一個Web應用程序。 這只是一個簡單的RESTful應用程序,我將其部署在heroku上一切都進行得很好。 但是,當服務器開始收到更多請求時,我從heroku達到了1.5GB的內存限制。 因此,我猜測是因為每次請求到來時我都會加載nltk.RegexpParser
。
這是非常簡單的代碼。
@app.route('/get_keywords', methods=['POST'])
def get_keywords():
data_json = json.loads(request.data)
text = urllib.unquote(data_json["sentence"])
keywords = KeywordExtraction().extract(text)
return ','.join(keywords)
這是關鍵字提取位。
import re
import nltk
nltk.data.path.append('./nltk_data/')
from nltk.corpus import stopwords
class KeywordExtraction:
def extract(self, text):
sentences = nltk.sent_tokenize(text)
sentences = [nltk.word_tokenize(sent) for sent in sentences]
sentences = [nltk.pos_tag(sent) for sent in sentences]
grammar = "NP: {}"
cp = nltk.RegexpParser(grammar)
tree = cp.parse(sentences[0])
keywords = [subtree.leaves()[0][0] for subtree in tree.subtrees(filter=lambda t: t.node == 'NP')]
keywords_without_stopwords = [w for w in keywords if not w in stopwords.words('english')]
return list(set(keywords_without_stopwords + tags))
我不確定我的代碼,Flask或NLTK是否有問題。 我是Python的新手。 任何建議將不勝感激。
我通過blitz.io進行了測試,僅在250個請求之后服務器就爆了並開始拋出R15。
首先緩存內容:
# Move these outside of the class declaration or make them class variables
stopwords = set(stopwords.words('english'))
grammar = "NP: {}"
cp = nltk.RegexpParser(grammar)
這也可以加快一點:
from itertools import ifilterfalse
...
keywords_without_stopwords = ifilterfalse(stopwords.__contains__, keywords)
return list(keywords_without_stopwords + set(tags)) # Can you cache `set(tags`)?
我還將看一看Flask-Cache,以便盡可能地記憶和緩存功能和視圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.