Skip to content

Instantly share code, notes, and snippets.

@dangsonbk
Created February 21, 2018 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dangsonbk/204d97e6e3ce27bd0090e3b98cbe8131 to your computer and use it in GitHub Desktop.
Save dangsonbk/204d97e6e3ce27bd0090e3b98cbe8131 to your computer and use it in GitHub Desktop.
Simple plantUML call
import shutil
import requests
# some pieces from: https://github.com/SamuelMarks/python-plantuml
from zlib import compress
def deflate_and_encode(plantuml_text):
"""zlib compress the plantuml text and encode it for the plantuml server.
"""
zlibbed_str = compress(plantuml_text)
compressed_string = zlibbed_str[2:-4]
return encode(compressed_string)
def encode(data):
"""encode the plantuml data which may be compresses in the proper
encoding for the plantuml server
"""
res = ""
for i in xrange(0, len(data), 3):
if i + 2 == len(data):
res += _encode3bytes(ord(data[i]), ord(data[i + 1]), 0)
elif i + 1 == len(data):
res += _encode3bytes(ord(data[i]), 0, 0)
else:
res += _encode3bytes(ord(data[i]), ord(data[i + 1]), ord(data[i + 2]))
return res
def _encode3bytes(b1, b2, b3):
c1 = b1 >> 2
c2 = ((b1 & 0x3) << 4) | (b2 >> 4)
c3 = ((b2 & 0xF) << 2) | (b3 >> 6)
c4 = b3 & 0x3F
res = ""
res += _encode6bit(c1 & 0x3F)
res += _encode6bit(c2 & 0x3F)
res += _encode6bit(c3 & 0x3F)
res += _encode6bit(c4 & 0x3F)
return res
def _encode6bit(b):
if b < 10:
return chr(48 + b)
b -= 10
if b < 26:
return chr(65 + b)
b -= 26
if b < 26:
return chr(97 + b)
b -= 26
if b == 0:
return '-'
if b == 1:
return '_'
return '?'
def get_url(plantuml_url, plantuml_text):
"""Return the server URL for the image.
You can use this URL in an IMG HTML tag.
:param str plantuml_text: The plantuml markup to render
:returns: the plantuml server image URL
"""
return plantuml_url + deflate_and_encode(plantuml_text)
umlText = """
@startuml
title "Messages - Sequence Diagram"
actor User
boundary "Web GUI" as GUI
control "Shopping Cart" as SC
entity Widget
database Widgets
User -> GUI : To boundary
GUI -> SC : To control
SC -> Widget : To entity
Widget -> Widgets : To database
@enduml
"""
url = get_url('http://www.plantuml.com/plantuml/img/', str.encode(umlText))
print(url)
response = requests.get(url, stream=True, params=umlText)
with open('img.png', 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment