sen-den / django-model2puml

Generator of project models structure in PlantUML class notation
MIT License
22 stars 4 forks source link

Allow PlantUML URLs generation from a command #5

Closed ddahan closed 1 year ago

ddahan commented 2 years ago

If you go to this URL, you can see that plantuml allows users to generate diagrams from a URL (or generate URLs from the schemas). To do this, the whole diagram is encoded in a specific format that can be injected in the URL, as explained here.

After having generated the file using django-model2puml extension, here is the working code (from a custom Django command) I wrote to do this:

import zlib
import base64
import string
from django.core.management import call_command

OUTPUT_NAME = "diagram.puml"
# 1- Generate puml file wrapping the original extension
call_command("generate_puml", "--file", OUTPUT_NAME)
self.stdout.write(self.style.SUCCESS("Diagram has been generated."))

# 2- Get utf-8 text from file
with open(OUTPUT_NAME, "r") as file:
    plantuml_text = file.read().rstrip()

# 3- Compress with deflate custom algorithm
# 🔗 https://github.com/dougn/python-plantuml/blob/master/plantuml.py
plantuml_alphabet = (
    string.digits + string.ascii_uppercase + string.ascii_lowercase + "-_"
)
base64_alphabet = (
    string.ascii_uppercase + string.ascii_lowercase + string.digits + "+/"
)
b64_to_plantuml = bytes.maketrans(
    base64_alphabet.encode("utf-8"), plantuml_alphabet.encode("utf-8")
)

zlibbed_str = zlib.compress(plantuml_text.encode("utf-8"))
compressed_string = zlibbed_str[2:-4]

# 4- re-encode in ASCII
final = (
    base64.b64encode(compressed_string).translate(b64_to_plantuml).decode("utf-8")
)

# 5- Give URL to user
URL = "https://www.plantuml.com/plantuml/svg/" # could be /uml/ or /png too/
self.stdout.write(f"See your diagram at {URL}{final}")

This generates full usable URLs like this one.

This is very useful as I just need to click to the generated URL to see the schema in my browser. And I was thinking this could be added directly to the extension. For example, running :

manage.py generate_puml --url svg

would generate and return this url to the user . puml file creation would become an option, as you may need the URL only, the file only, or both the URL and file.

What do you think?

sen-den commented 1 year ago

Sorry I wasn't answering to this issue for so long. Thank you so much for sharing with me plantuml URL feature and this code sample. I released 0.3.0 version with this feature.

ddahan commented 1 year ago

Hi @sen-den, I tried to use the new url option but I get this error:

manage.py generate_puml: error: unrecognized arguments: --url

I'm using the last PyPI version (0.41). Did I miss something? Thanks.