I am carrying out a project that requires a json file, which is automatically downloaded when Blender starts. This json file contains a list of internet sites, and I wish I could populate a series of buttons in the menu.
The fundamental problem is that I would only like to load the json file once I find it, but I don't know where to store it. The script works like this (approx.):
File my_json.json:
{
"site_list":{"Stackexchange":"https://blender.stackexchange.com/",
"Google":"https://google.com/"}
}
Code:
import bpy,json,os,webbrowser
from bpy.props import StringProperty
def open_json():
json_file = "G:\\my_json.json"
f = open(json_file)
data = json.load(f)
f.close()
return data
class HelloWorldPanel(bpy.types.Panel):
"""Creates a Panel in the Object properties window"""
bl_label = "Hello World Panel"
bl_idname = "OBJECT_PT_hello"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "object"
def draw(self, context):
layout = self.layout
col=layout.column()
data = open_json()
for site , adress in data['site_list'].items():
col.operator("object.simple_operator",text = site).options = adress #I pass a string to the operator (Web address)
class SimpleOperator(bpy.types.Operator):
"""Tooltip"""
bl_idname = "object.simple_operator"
bl_label = "Simple Object Operator"
options: StringProperty()
def execute(self, context):
webbrowser.open(self.options) #Open web adress in the default browser
return {'FINISHED'}
def register():
bpy.utils.register_class(SimpleOperator)
bpy.utils.register_class(HelloWorldPanel)
def unregister():
bpy.utils.unregister_class(SimpleOperator)
bpy.utils.unregister_class(HelloWorldPanel)
if __name__ == "__main__":
register()
Result:
This method works, but the problem is that it iterates over and over to the Json file, opens it, reads it, closes it, and returns the data contained in it in the function return.
I was wondering where I could store this data, one time only. Read the file once, not read it again, and store the data somewhere.