python flask restful 服务器中生成的数据如何存到内存中

from __future__ import unicode_literals

from flask_restful import Api

from flask import Flask,request

import time

import datetime

#########product==========

import json

#####放在11.46库

import TextDropRepeat as tdr

import numpy as np

from numpy import array

app = Flask(__name__)

app.debug = True

app.config.update(RESTFUL_JSON=dict(ensure_ascii=False))

api = Api(app)

@app.route('/drop_TextRepeat/', methods=['POST'])

def add_task():

time_start=time.time()

nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

pastTime = (datetime.datetime.now()-datetime.timedelta(days=5)).strftime('%Y-%m-%d %H:%M:%S')

####获取数据

data1 = request.form.get('data')

for line in data1.split('\n'):

if 'DRETITLE' in line:

title = line.split('#DRETITLE')[1].strip()

if 'PUBLISHDATE' in line:

publishdate = line.replace('=','').replace('"','').split('PUBLISHDATE')[1].strip().replace("'","")

print (publishdate)

###转换64位hash

ConHash = tdr.simhash(title)

####切割4*16hash

ConHashA = str(ConHash)[0:16]

ConHashB = str(ConHash)[16:32]

ConHashC = str(ConHash)[32:48]

ConHashD = str(ConHash)[48:]

if ConHashA in conhashGroupA:

conhashGroup.append(ConHash)

publishtime.append(publishdate)

conhashGroupA.append(ConHashA)

conhashGroupB.append(ConHashB)

conhashGroupC.append(ConHashC)

conhashGroupD.append(ConHashD)

time_end=time.time()

print ('totally cost',time_end-time_start)

return 'ok'

if __name__ == '__main__':

app.run(host = '0.0.0.0')

global conhashGroup

global publishtime

global conhashGroupA

global conhashGroupB

global conhashGroupC

global conhashGroupD

conhashGroup = []

publishtime = []

conhashGroupA = []

conhashGroupB = []

conhashGroupC = []

conhashGroupD = []

如上,我想把每次生成的conhash储存在内存里,但总是报错如下,请问这个该如何修改,我已经定义了全局变量,但是错误显示还是说我的这个是局部变量,求大佬帮忙解答
图片描述

回答:

你似乎并不太会使用global关键字。global 关键字告诉程序这个变量不在块作用域,也不在函数作用域, 你要找直接到全局作用域中找。什么时候用? 局部作用域中有变量名和全局域的变量名相同,而这种情况下,你又需要使用全局的那个变量,那么你需要在使用这个变量之前用global声明一下。

因此在你的这个例子中,即便要使用global也应该在add_task中使用。其次,在这里根本就没有必要使用global关键字,只需要将你用global声明的变量放到全局域中(不是if name == "__main__")的条件块中。最后@Leo黎诗霆 说的也是正确的,程序被阻塞了,你后面的代码压根不会执行。当然,通过把这些代码放到app.run之前是没有用的。

回答:

试一下把app.run(host = '0.0.0.0')放到最后一句。因为程序运行到这里会阻塞,后面的声明和初始化都没有执行。

回答:

from __future__ import unicode_literals

from flask_restful import Api

from flask import Flask,request

import time

import datetime

#########product==========

import json

#####放在11.46库

import TextDropRepeat as tdr

import pymongo

import numpy as np

from numpy import array

app = Flask(__name__)

app.debug = True

app.config.update(RESTFUL_JSON=dict(ensure_ascii=False))

api = Api(app)

TODOS = {

'conhashGroup': {'task': []},

'publishtime': {'task':[]},

'conhashGroupA': {'task': []},

'conhashGroupB': {'task': []},

'conhashGroupC': {'task': []},

'conhashGroupD': {'task': []},

}

from flask_restful import reqparse

parser = reqparse.RequestParser()

parser.add_argument('task')

@app.route('/drop_TextRepeat/', methods=['POST'])

def add_task():

print (TODOS)

nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

pastTime = (datetime.datetime.now()-datetime.timedelta(days=5)).strftime('%Y-%m-%d %H:%M:%S')

time_start=time.time()

print ('开始获取数据')

####获取数据

try:

data1 = request.form.get('data')

print (1)

except:

data1 = request.data

print (2)

#print (data1)

print ('获取数据成功')

for line in data1.split('\n'):

if 'DRETITLE' in line:

title = line.split('#DRETITLE')[1].strip()

if 'PUBLISHDATE' in line:

publishdate = line.replace('=','').replace('"','').split('PUBLISHDATE')[1].strip().replace("'","")

print (publishdate)

print (title)

###转换64位hash

ConHash = tdr.simhash(title)

####切割4*16hash

ConHashA = str(ConHash)[0:16]

ConHashB = str(ConHash)[16:32]

ConHashC = str(ConHash)[32:48]

ConHashD = str(ConHash)[48:]

if ConHashA in TODOS['conhashGroupA']['task']:

print (3)

TODOS['conhashGroup']['task'].append(ConHash)

TODOS['publishtime']['task'].append(publishdate)

TODOS['conhashGroupA']['task'].append(ConHashA)

TODOS['conhashGroupB']['task'].append(ConHashB)

TODOS['conhashGroupC']['task'].append(ConHashC)

TODOS['conhashGroupD']['task'].append(ConHashD)

index = np.where((pastTime<=array(TODOS['publishtime']['task'])) & (array(TODOS['publishtime']['task'])<nowTime ))[0].tolist()

TODOS['publishtime']['task'] = np.array(TODOS['publishtime']['task'])[index].tolist()

TODOS['conhashGroup']['task'] = np.array(TODOS['conhashGroup']['task'])[index].tolist()

TODOS['conhashGroupA']['task'] = np.array(TODOS['conhashGroupA']['task'])[index].tolist()

TODOS['conhashGroupB']['task'] = np.array(TODOS['conhashGroupB']['task'])[index].tolist()

TODOS['conhashGroupC']['task'] = np.array(TODOS['conhashGroupC']['task'])[index].tolist()

TODOS['conhashGroupD']['task'] = np.array(TODOS['conhashGroupD']['task'])[index].tolist()

time_end=time.time()

print ('totally cost',time_end-time_start)

return 'ok'

if __name__ == '__main__':

app.run(host = '0.0.0.0')

用以上代码可以实现,另楼上的建议非常好

以上是 python flask restful 服务器中生成的数据如何存到内存中 的全部内容, 来源链接: utcz.com/a/164209.html

回到顶部