Ваши дополнительные потоки должны быть инициированы из того же приложения, которое вызывается сервером WSGI.
В приведенном ниже примере создается фоновый поток, который выполняется каждые 5 секунд и управляет структурами данных, которые также доступны для Flask маршрутизируемые функции.
import threading
import atexit
from flask import Flask
POOL_TIME = 5 #Seconds
# variables that are accessible from anywhere
commonDataStruct = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
yourThread = threading.Thread()
def create_app():
app = Flask(__name__)
def interrupt():
global yourThread
yourThread.cancel()
def doStuff():
global commonDataStruct
global yourThread
with dataLock:
# Do your stuff with commonDataStruct Here
# Set the next thread to happen
yourThread = threading.Timer(POOL_TIME, doStuff, ())
yourThread.start()
def doStuffStart():
# Do initialisation stuff here
global yourThread
# Create your thread
yourThread = threading.Timer(POOL_TIME, doStuff, ())
yourThread.start()
# Initiate
doStuffStart()
# When you kill Flask (SIGTERM), clear the trigger for the next thread
atexit.register(interrupt)
return app
app = create_app()
Вызовите его из Gunicorn с чем-то вроде этого:
gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app
После чтения, какого @dimo414 и @Brian сказанного Roach, если Вы все еще хотите вытащить карту из своей json структуры, можно достигнуть путем выполнения этого:
Type type = new TypeToken<HashMap<String, String>>() {}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(type, new JsonDeserializer<HashMap<String, String>>() {
@Override
public HashMap<String, String> deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
HashMap<String, String> map = new HashMap<>();
for (JsonElement element : jsonElement.getAsJsonArray()) {
JsonObject jsonObject = element.getAsJsonObject();
signals.put(jsonObject.get("countryId").getAsString(), jsonObject.get("countryName").getAsString());
}
return map;
}
}).create();
HashMap<String, String> countries = gson.fromJson(jsonArray, type);
, Но в той точке Вы могли просто проанализировать свой json в JsonArray и цикл через него делающий Вашу карту.