Featured post

new redirect for blender.org bpy docs.

http://www.blender.org/api/blender_python_api_current/ As of 10/11 november 2015 we can now link to the current api docs and not be worr...

August 27, 2012

gist id to blender text file

I like to shuttle code between friends and github, this script allows me to download a gist directly into blender. It could be extended to name the blender textfile according to the gist filename, but I don't need that so if you are interested in learning json / py3 / blender that might be an interesting exercise for you.

- adds panel to text editor
- creates area to fill in gist id
- creates button to initiate download
- will create new filename inside blender with gist id
- will write (first) file found at the gist id.

If your gist has multiple filenames and you don't want the first gist, then you will need to add some logic to the filename selector towards the end of the get_raw_url_from_gist_id function.

Direct link to the addon version of this script, here
import json
from urllib.request import urlopen
import bpy
from mathutils import Vector
from bpy.props import StringProperty
def get_raw_url_from_gist_id(gist_id):
gist_id = str(gist_id)
url = 'https://api.github.com/gists/' + gist_id
found_json = urlopen(url).readall().decode()
wfile = json.JSONDecoder()
wjson = wfile.decode(found_json)
# 'files' may contain several - this will mess up gist name.
files_flag = 'files'
file_names = list(wjson[files_flag].keys())
file_name = file_names[0]
return wjson[files_flag][file_name]['raw_url']
def get_file(gist_id):
url = get_raw_url_from_gist_id(gist_id)
conn = urlopen(url).readall().decode()
return conn
class ButtonOne(bpy.types.Operator):
"""Defines a button"""
bl_idname = "scene.dostuff"
bl_label = "Sometype of operator"
def execute(self, context):
gist_id = context.scene.gist_id_property
# could name this filename instead of gist_id for new .blend text.
bpy.data.texts.new(gist_id)
bpy.data.texts[gist_id].write(get_file(gist_id))
return{'FINISHED'}
class OperatorPanel(bpy.types.Panel):
"""Creates a Panel in the Object properties window"""
bl_label = "Some Utility"
bl_idname = "OBJECT_PT_somefunction"
bl_space_type = "TEXT_EDITOR"
bl_region_type = "UI"
bl_context = "object"
def draw(self, context):
layout = self.layout
row = layout.row()
scn = bpy.context.scene
# display stringbox and download button
self.layout.prop(scn, "gist_id_property")
self.layout.operator("scene.dostuff", text='Download to .blend')
def initSceneProperties(scn):
bpy.types.Scene.gist_id_property = StringProperty(
name = "Gist ID",
description = "Github Gist ID to download as new internal file",
default = ""
)
initSceneProperties(bpy.context.scene)
classes = [OperatorPanel, ButtonOne]
def register():
for i in classes:
bpy.utils.register_class(i)
def unregister():
for i in classes:
bpy.utils.unregister_class(i)
if __name__ == "__main__":
register()