How the data generated in the python flask restful server is stored in memory

from __future__ import unicode_literals
from flask_restful import Api
from flask import Flask,request
import time
import datetime
-sharp-sharp-sharp-sharp-sharp-sharp-sharp-sharp-sharpproduct==========
import json
-sharp-sharp-sharp-sharp-sharp11.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")
        -sharp-sharp-sharp-sharp
    data1 = request.form.get("data")
    for line in data1.split("\n"):
        if "DRETITLE" in line:
            title = line.split("-sharpDRETITLE")[1].strip()
        if "PUBLISHDATE" in line:
            publishdate = line.replace("=","").replace(""","").split("PUBLISHDATE")[1].strip().replace(""","")
    print (publishdate)
    -sharp-sharp-sharp64hash
    ConHash = tdr.simhash(title)
    -sharp-sharp-sharp-sharp4*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 = []

as above, I want to store the conhash generated each time in memory, but always report an error as follows. How to modify this? I have defined a global variable, but the error display still means that mine is a local variable. Ask the boss for help

Apr.01,2021

you don't seem to know how to use the global keyword. The global keyword tells the program that the variable is not in block scope or function scope, and that you need to find it directly in the global scope. When do you use it? There is a variable name in the local scope that is the same as the variable name in the global domain, and in this case, you need to use the global variable, so you need to declare it with global before using this variable.

so in your case, even if you want to use global, you should use it in add_task. Second, there is no need to use the global keyword here, just put the variables you declare with global into the conditional block in the global domain (not if name = "_ _ main__"). Finally, @ Leo Li Shiting is also correct. The program is blocked and the code behind you will not be executed at all. Of course, it's useless to put this code before app.run.


try putting app.run (host = '0.0.0.0') in the last sentence. Because the program runs here will block, the subsequent declaration and initialization are not performed.


from __future__ import unicode_literals
from flask_restful import Api
from flask import Flask,request
import time
import datetime
-sharp-sharp-sharp-sharp-sharp-sharp-sharp-sharp-sharpproduct==========
import json
-sharp-sharp-sharp-sharp-sharp11.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 ('')
    -sharp-sharp-sharp-sharp
    try:
        
        data1 = request.form.get('data')
        print (1)
    except:
        data1 = request.data
        print (2)
    -sharpprint (data1)
    print ('')
    for line in data1.split('\n'):
        if 'DRETITLE' in line:
            title = line.split('-sharpDRETITLE')[1].strip()
        if 'PUBLISHDATE' in line:
            publishdate = line.replace('=','').replace('"','').split('PUBLISHDATE')[1].strip().replace("'","")
    print (publishdate)
    print (title)
    -sharp-sharp-sharp64hash
    ConHash = tdr.simhash(title)
    -sharp-sharp-sharp-sharp4*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')

can be implemented with the above code, and the suggestion upstairs is very good

Menu