Skip to main content

Featured

Learning To Work With Python Frameworks: FLASK vs DJANGO

                 Image:  https://www.bitcot.com/flask-vs-django/ Breakdown I had experience building with Python and other APIs, but I’d never worked with a web framework. I wanted to learn how a full-stack web application fits together, so I learned two of the most popular Python ones: Flask first, as the small and simple option, then Django, as the larger one with more built in. This post breaks down what I learned from each, and how they compare. Tools Python 3.14 VS Code Virtual Environments Flask Django The Use Cases For Each Flask Built for simple projects, with a small core and a minimal set of features. Easy to install and quick to get started with. Fast and lightweight, but not designed for high-workload projects. Built on a synchronous model, so each worker handles one request at a time. Handling several requests at once means running multiple workers or threads. Best for quick projects and prototyping, like getting a ...

Embracing Automation with Blender & Python


The Breakdown

This project started as one simple script with a UI panel that was meant to help me & the art team. The thing about embracing automations while modeling is that's you start noticing minor inefficiencies, and think "maybe I can reduce the steps here with a click". Next thing you know, you are are get a few requests & the lines of code grow at an exponential rate. What now? Well, as a solo developer considering sanity & time, building an entire plugin systematically would save me a lot of scrolling & brain power.


The Process

Clean architecture first. The entire plugin should be approached as Legos. I should be able to add or remove an action without breaking anything, focusing the ideas & no longer the system. If the script itself works when executed in Blender, a Class & UI Button for it can be built, followed by adding it into the plugin folder.

import bpy
from bpy.utils import register_class, unregister_class


##############################DEFINING PANEL##############################
#Define panel for the SuperModel UI
class VIEW3D_PT_SuperModel(bpy.types.Panel):
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_category = "SuperModel"
    bl_label = "SuperModel"
    bl_idname = "VIEW3D_PT_SuperModel"

   
    def draw(self, context):
        layout = self.layout
##############################DEFINING PANEL##############################


##############################UVs##############################
        layout.label (text="UVs:", icon="SHADING_WIRE")

        row = layout.row()
        row.operator("object.n_pole_loop", text="N-Pole Loop")
        row.operator("object.n_pole_seam_loop", text="N-Pole Seam Loop")

        row = layout.row()
        row.operator("object.select_and_clear_seam", text="Clear Seam Loop")
##############################UVs##############################

##############################REGISTER/UNREGISTER PANEL##############################
def register():
    bpy.utils.register_class(VIEW3D_PT_SuperModel)

def unregister():
    bpy.utils.unregister_class(VIEW3D_PT_SuperModel)
   

if __name__ == "__main__":
    register()
##############################REGISTER/UNREGISTER PANEL##############################

Scope, Modularity & Scalability

For me to break down the scope, we need to understand modularity & scalability, which covers the intent moving forward. What is modularity? Modularity in programming is a concept where developers separate program functions into independent pieces. These pieces then act like building blocks, with each block containing all the necessary parts to execute one aspect of functionality. This directly leads into scalability, which refers to the capability of a system, network, or process to handle a growing amount of work or its potential to accommodate growth.

Automated Actions

The entire project is divide into a free and paid version. The paid version builds of the free version, making working with one VS Code workspace, one branch (not recommended), and modules divided into two folders(that plugin folder with the __init__ packaging the entire thing & the experimental/idea folder) easier. If the experimental ideas work as a singular script ran by Blender, they make it into the plugin folder with their respective UI button. The scope focuses on an infinite amount of additions, while still being able to consistently deliver a minimum viable product. A flow free from a house of cards.

Some automated actions include:

N-Pole Loops - Let's you find N-Pole all over the model then selects all the loops for them

N-Pole Bevel - Builds on "N-Pole Loops" then bevels them at a fixed value. 

class OBJECT_OT_NPoleSeamLoop(bpy.types.Operator):
    bl_idname = "object.n_pole_seam_loop"
    bl_label = "Seam Loops From N-Poles"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        #Make sure we are in Object Mode and have the correct object selected
        obj = bpy.context.active_object
        if obj is None or obj.type != 'MESH':
            print("No active mesh object selected.")
        else:
            #Switch to Edit Mode to work with mesh data
            bpy.ops.object.mode_set(mode='EDIT')

            #Get the BMesh representation of the mesh
            bm = bmesh.from_edit_mesh(obj.data)

            #Deselect all edges first
            bpy.ops.mesh.select_all(action='DESELECT')

            #Iterate through all vertices in the mesh
            for vertex in bm.verts:
                #Check if the vertex has exactly 3 edges connected (a 3-sided pole)
                if len(vertex.link_edges) == 3:
                    #Select the edges connected to the vertex
                    for edge in vertex.link_edges:
                        edge.select = True

            #Update the mesh with the selected edges
            bmesh.update_edit_mesh(obj.data)

            #Select edge loop
            bpy.ops.mesh.loop_multi_select(ring=False)
            #Mark selected edges as seam
            bpy.ops.mesh.mark_seam()

            print("Edges connected to 3-sided poles have been selected and
            marked as a UV seam.")

        return {'FINISHED'}

Smooth Verts - This let's you completely remove the smooth brush step for more control. You can select the specific vertices you want to smooth, then interpolates all vertices around relative to the smoothed vertex.

Batch Export - This one is a bit self-explanatory, but it let's you export all meshes as individual FBXs to your selected folder. There is an alternative operation that just exports everything into one FBX. Great option for when you want to texture models in bulk.


Understanding the Blender API

Consuming the Blender API was the easiest part, as everything felt very self-explanatory are years of modeling. The challenge was picking the versions of Blender I wanted to develop by casting a wide net with the little to no amount of deprecated functions between the Blender versions. Additionally considering dependencies was also another key factor, although having to enable "Loop Tools" for a particular function had to be an exception, it is a plugin that comes with Blender & can be enabled at any time.
import bpy
import bmesh
from bpy_extras.io_utils import ExportHelper
from bpy.utils import register_class, unregister_class

bpy: This is Blender’s main Python module, and it gives your script access to nearly everything in Blender. bpy.data holds the scene’s objects, meshes and materials, bpy.context describes what’s currently selected or active, bpy.ops runs the same operators as the UI buttons, and bpy.types has the base classes for building add-ons. It only exists inside Blender’s own Python, so scripts that import it can’t run in a normal Python install.

bmesh: This module edits mesh geometry directly at the vertex, edge and face level. Instead of working through the mesh data Blender stores, you load the mesh into a BMesh, create or delete geometry, then write the result back. It’s the tool for procedural modelling, such as extruding faces, merging vertices or building a mesh from scratch, and it’s faster and more flexible than the equivalent operators. If you create a BMesh outside edit mode, remember to free it when you’re done.

ExportHelper: This is a helper class from bpy_extras.io_utils that you add to your own export operator. It supplies the file path property and opens Blender’s file browser, so users get a normal “Save As” dialog when they use your exporter. You set the file extension and a filter, and the rest is handled for you. This is what you’d use to make a custom export option appear under File > Export.

register_class and unregister_class: These are functions from bpy.utils that add your own classes (operators, panels, property groups, preferences) to Blender, and remove them again. A class only appears in the interface or does anything once it’s registered, which is why add-ons call register_class in their register() function and unregister_class in unregister(). Unregistering matters, because it lets users disable your add-on cleanly.


Seperation of Concerns & Unit/System Testing

Arguably the most important part during this process. I lightly touched on the process, but hammering the practice of SoC & Unit/System Testing was very vital in the tech check verification process. "Divide the entire operation, by ensuring the code works as intended, wrap it in a class then assign the class its button in the UI module, load it in the __init__ file, refresh the plugin in Blender, check if it works as intended with the button & make sure nothing is broken or UI rearranged.


Code Examples:

Setting up the __init__ file:

#Blender module imports
import bpy



##############################UI MODULES##############################
from .SuperModelPanel import VIEW3D_PT_SuperModel
##############################UI MODULES##############################


##############################MODELING MODULES##############################
from .SmoothWeights import OBJECT_OT_SmoothWeights
from .SmoothVerts import OBJECT_OT_SMOOTH_VERTS
from .EnableFaceNormals import OBJECT_OT_FaceNormals
from .AddMaterialSlot import OBJECT_OT_AddMaterialSlot
from .ToggleWireframe import OBJECT_OT_ToggleWireframe
from .InsetAndPoke import OBJECT_OT_InsetAndPoke
from .CircularizeInset import OBJECT_OT_CircularizeInset
from .InsetAndTriangulate import OBJECT_OT_InsetAndTriangulate
from .NPoleLoop import OBJECT_OT_NPoleLoop
from .NPoleSeamLoop import OBJECT_OT_NPoleSeamLoop
from .SeamBevels import OBJECT_OT_SelectAndBevelLoopOperator
from .NPoleLoopBevel import OBJECT_OT_NPoleLoopBevel
##############################MODELING MODULES##############################

#Addon/Plugin infomation
bl_info = {
    "name": "SuperModel",
    "description": "A versitile modeling tool to help you speed up your modeling &
    UV unwrapping with the added bonus of cleaning up your assets.",
    "author": "Londa Hlatshwayo",
    "version": (0,0,0,2),
    "blender": (2, 93, 0),
    "category": "3D View"
}


classes = (VIEW3D_PT_SuperModel, OBJECT_OT_SmoothWeights, OBJECT_OT_SMOOTH_VERTS,
           OBJECT_OT_FaceNormals, OBJECT_OT_AddMaterialSlot, OBJECT_OT_ToggleWireframe,
           OBJECT_OT_InsetAndPoke, OBJECT_OT_InsetAndTriangulate,
           OBJECT_OT_CircularizeInset, OBJECT_OT_NPoleLoop, OBJECT_OT_NPoleSeamLoop,
           OBJECT_OT_SelectAndBevelLoopOperator, OBJECT_OT_NPoleLoopBevel,
           OBJECT_OT_SelectAndMarkSeamOperator, OBJECT_OT_SelectAndClearSeamOperator,
           OBJECT_OT_Find_Ngons, OBJECT_OT_RenameSelected, OBJECT_OT_DeleteMaterials,
           OBJECT_OT_triangulate_faces, OBJECT_OT_QuickPivot, OBJECT_OT_DeleteNGONS,
           OBJECT_OT_ResetTransforms, OBJECT_OT_FreezeTransforms,
           OBJECT_OT_BatchExportFBX)


def register():
    from bpy.utils import register_class
    for cls in classes:
         bpy.utils.register_class(cls)


def unregister():
     from bpy.utils import unregister_class
     for cls in reversed(classes):
          bpy.utils.unregister_class(cls)


if __name__ == "__main__":
     register()


What I Learned

The biggest overall lesson for this exercise was the reinforcement of software engineering principles over the more technical concepts I have a working understanding of the language, syntax & general programming principles, but things like modularity, scalability & continuous development were more valuable by strengthening systematic thinking. 

Conclusion

Having started from one script that turned into one giant .py caught up with me fast, as it became difficult to maintain & build upon. Building from a strong foundation & avoiding incurring as much technical debt as possible certainly made my life a whole lot easier later on & wish I had started with solid architecture. Live & learn, I suppose. 


Learning Resources




DevOps Fundamentals

Blender 2.93 API Documentation

Software Engineering Principles


GitHub

SuperModel-Free Version_

Comments