Skip to content

Instantly share code, notes, and snippets.

@mzfr
Created September 23, 2018 13:23
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 mzfr/6413fba670d7fdbb420ac0c65755e3ab to your computer and use it in GitHub Desktop.
Save mzfr/6413fba670d7fdbb420ac0c65755e3ab to your computer and use it in GitHub Desktop.
"""
A simple webserver that sends colors to curl & HTML to browsers.
Inspired by @chubin's work on curl compatible webservices.
"""
from flask import Flask
from flask import request
app = Flask(__name__)
# List of UAs to serve colorful content to
# https://github.com/chubin/wttr.in/blob/master/bin/srv.py#L46
PLAIN_TEXT_AGENTS = [
"curl",
"httpie",
"lwp-request",
"wget",
"python-requests"
]
@app.route("/")
@app.route("/<string:location>")
def index():
# https://github.com/chubin/wttr.in/blob/master/bin/srv.py#L232
UA = request.headers.get('User-Agent').lower()
if any(agent in UA for agent in PLAIN_TEXT_AGENTS):
html_output = False
else:
html_output = True
if html_output:
# Return HTML
resp = "<b>Hello</b>" + "<i>World</i>"
# resp = render_template()
else:
# return whatever you would want to print on terminal
# keep appending to resp
resp = color("Hello", 31) + " " + color("World", 32)
return resp
def color(string, c):
"""
Colorize some text.
This function currently only knows about ANSI colors.
Teach it learn HTML colors. Another argument could be added:
fmt = ansi | html
Could use ansi2html here
"""
return("\033[%sm%s\033[0m" % (c, string))
if __name__ == '__main__':
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment