A simple Flask server that displays a unicode playing card. I made this as part of a little card trick for a friend's birthday.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

116 lines
2.6 KiB

from flask import *
import re
# cards in unicode
card_back = "🂠"
cards = {
"s": "🂡🂢🂣🂤🂥🂦🂧🂨🂩🂪🂫🂭🂮",
"h": "🂱🂲🂳🂴🂵🂶🂷🂸🂹🂺🂻🂽🂾",
"d": "🃁🃂🃃🃄🃅🃆🃇🃈🃉🃊🃋🃍🃎",
"c": "🃑🃒🃓🃔🃕🃖🃗🃘🃙🃚🃛🃝🃞"
# init
app = Flask(__name__)
cards_index = "a234567890jqk"
card = card_back
color = "black"
fadein_seconds = 13
# functions
def card_is_valid(card):
Checks if a card matches the expected format by regular expression.
if re.match("[a02-9jqk][shdc]", card): # 10 is represented as 0.
return True
return False
def get_color_of_card(card):
Returns the color of a card as a string ("red" or "black").
if card[1] in "hd":
return "red"
return "black"
def lookup_card_char(card):
Tries to return the unicode character for a given card, otherwise returns a blank card character.
i = cards_index.index(card[0])
suit = card[1]
card_char = cards[suit][i]
except ValueError:
card_char = card_back
return card_char
# routes
def index():
Renders the index page using the global variables `card` and `color`.
card_char = lookup_card_char(card)
if card_char == card_back:
_fadein_seconds = 0
_fadein_seconds = fadein_seconds
return render_template("index.html", card=card_char, color=color, fadein_seconds=_fadein_seconds)
def update_card(new_card):
On receiving a valid card, updates the global variables `card` and `color`, then redirects to the index route.
new_card = new_card.lower().replace("10", "0") # 10 is represented as 0.
if card_is_valid(new_card):
global card
global color
card = new_card
color = get_color_of_card(new_card)
app.logger.debug(f"Updated card to '{new_card}' and color to '{color}'")
return redirect(url_for(".index"))
def reset_card():
Resets the global variables `card` and `color`, then redirects to the index route.
global card
global color
card = card_back
color = "black"
app.logger.debug(f"Reset card")
return redirect(url_for(".index"))
def after_request(response):
Appends response headers for preventing the client from caching responses.
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, public, max-age=0"
response.headers["Expires"] = "0"
response.headers["Pragma"] = "no-cache"
return response
# main
if __name__ == "__main__":
app.run(debug=True, host="")