summaryrefslogtreecommitdiff
path: root/talerblog/blog/blog.py
diff options
context:
space:
mode:
authorFlorian Dold <florian.dold@gmail.com>2019-08-29 18:57:31 +0200
committerFlorian Dold <florian.dold@gmail.com>2019-08-29 18:57:31 +0200
commit948f8b2af6d092862bec93ba3c987654db4f799e (patch)
tree87b831006ba54b3b5b1dd4a0f0739aefa7fb3309 /talerblog/blog/blog.py
parent30c97118a6c7ec918cb9a4114a7c9d2470662342 (diff)
downloadblog-948f8b2af6d092862bec93ba3c987654db4f799e.tar.gz
blog-948f8b2af6d092862bec93ba3c987654db4f799e.tar.bz2
blog-948f8b2af6d092862bec93ba3c987654db4f799e.zip
make pretty
Diffstat (limited to 'talerblog/blog/blog.py')
-rw-r--r--talerblog/blog/blog.py165
1 files changed, 106 insertions, 59 deletions
diff --git a/talerblog/blog/blog.py b/talerblog/blog/blog.py
index ba10453..0b56027 100644
--- a/talerblog/blog/blog.py
+++ b/talerblog/blog/blog.py
@@ -33,7 +33,6 @@ from cachelib import UWSGICache, SimpleCache
from talerblog.talerconfig import TalerConfig
from ..blog.content import ARTICLES, get_article_file, get_image_file
-
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
app = flask.Flask(__name__, template_folder=BASE_DIR)
app.secret_key = base64.b64encode(os.urandom(64)).decode('utf-8')
@@ -59,6 +58,7 @@ def utility_processor():
# These helpers will be available in templates
def env(name, default=None):
return os.environ.get(name, default)
+
return dict(env=env)
@@ -71,6 +71,7 @@ def err_abort(abort_status_code, **params):
t = flask.render_template("templates/error.html", **params)
flask.abort(flask.make_response(t, abort_status_code))
+
##
# Issue a GET request to the backend.
#
@@ -81,7 +82,9 @@ def err_abort(abort_status_code, **params):
def backend_get(endpoint, params):
headers = {"Authorization": "ApiKey " + APIKEY}
try:
- resp = requests.get(urljoin(BACKEND_URL, endpoint), params=params, headers=headers)
+ resp = requests.get(
+ urljoin(BACKEND_URL, endpoint), params=params, headers=headers
+ )
except requests.ConnectionError:
err_abort(500, message="Could not establish connection to backend")
try:
@@ -89,10 +92,15 @@ def backend_get(endpoint, params):
except ValueError:
err_abort(500, message="Could not parse response from backend")
if resp.status_code != 200:
- err_abort(500, message="Backend returned error status",
- json=response_json, status_code=resp.status_code)
+ err_abort(
+ 500,
+ message="Backend returned error status",
+ json=response_json,
+ status_code=resp.status_code
+ )
return response_json
+
##
# POST a request to the backend, and return a error
# response if any error occurs.
@@ -104,21 +112,29 @@ def backend_get(endpoint, params):
def backend_post(endpoint, json):
headers = {"Authorization": "ApiKey " + APIKEY}
try:
- resp = requests.post(urljoin(BACKEND_URL, endpoint), json=json, headers=headers)
+ resp = requests.post(
+ urljoin(BACKEND_URL, endpoint), json=json, headers=headers
+ )
except requests.ConnectionError:
err_abort(500, message="Could not establish connection to backend")
try:
response_json = resp.json()
except ValueError:
- err_abort(500, message="Could not parse response from backend",
- status_code=resp.status_code)
+ err_abort(
+ 500,
+ message="Could not parse response from backend",
+ status_code=resp.status_code
+ )
if resp.status_code != 200:
- err_abort(500, message="Backend returned error status",
- json=response_json, status_code=resp.status_code)
+ err_abort(
+ 500,
+ message="Backend returned error status",
+ json=response_json,
+ status_code=resp.status_code
+ )
return response_json
-
##
# "Fallback" exception handler to capture all the unmanaged errors.
#
@@ -127,9 +143,12 @@ def backend_post(endpoint, json):
# (and execution stack!).
@app.errorhandler(Exception)
def internal_error(e):
- return flask.render_template("templates/error.html",
- message="Internal error",
- stack=traceback.format_exc())
+ return flask.render_template(
+ "templates/error.html",
+ message="Internal error",
+ stack=traceback.format_exc()
+ )
+
##
# Serve the main index page.
@@ -137,9 +156,12 @@ def internal_error(e):
# @return response object of the index page.
@app.route("/")
def index():
- return flask.render_template("templates/index.html",
- merchant_currency=CURRENCY,
- articles=ARTICLES.values())
+ return flask.render_template(
+ "templates/index.html",
+ merchant_currency=CURRENCY,
+ articles=ARTICLES.values()
+ )
+
##
# Serve the "/javascript" page.
@@ -167,7 +189,7 @@ except ImportError:
#
# @param order_id the order ID of the transaction to refund.
# @return the following errors (named by HTTP response code):
-# - 400: no article was asked to be refunded!
+# - 400: no article was asked to be refunded!
# - 401: the refund was asked on a non-payed article.
# - 500: the backend was unable to give response.
# Or, in the successful case, a redirection to the
@@ -180,11 +202,15 @@ def refund(order_id):
return flask.jsonify(dict(error="No article_name found in form")), 400
LOGGER.info("Looking for %s to refund" % article_name)
if not order_id:
- return flask.jsonify(dict(error="Aborting refund: article not payed")), 401
- refund_spec = dict(instance=INSTANCE,
- order_id=order_id,
- reason="Demo reimbursement",
- refund=ARTICLE_AMOUNT)
+ return flask.jsonify(
+ dict(error="Aborting refund: article not payed")
+ ), 401
+ refund_spec = dict(
+ instance=INSTANCE,
+ order_id=order_id,
+ reason="Demo reimbursement",
+ refund=ARTICLE_AMOUNT
+ )
resp = backend_post("refund", refund_spec)
try:
# delete from paid article cache
@@ -193,9 +219,12 @@ def refund(order_id):
paid_articles_cache.delete(session_id + "-" + article_name)
return flask.redirect(resp["refund_redirect_url"])
except KeyError:
- err_abort(500, message="Response from backend incomplete",
- json=resp, stack=traceback.format_exc())
-
+ err_abort(
+ 500,
+ message="Response from backend incomplete",
+ json=resp,
+ stack=traceback.format_exc()
+ )
##
@@ -214,19 +243,25 @@ def refund(order_id):
def render_article(article_name, data, order_id):
article_info = ARTICLES.get(article_name)
if article_info is None:
- m = "Internal error: Files for article ({}) not found.".format(article_name)
+ m = "Internal error: Files for article ({}) not found.".format(
+ article_name
+ )
err_abort(500, message=m)
if data is not None:
if data in article_info.extra_files:
return flask.send_file(get_image_file(data))
m = "Supplemental file ({}) for article ({}) not found.".format(
- data, article_name)
+ data, article_name
+ )
err_abort(404, message=m)
# the order_id is needed for refunds
- return flask.render_template("templates/article_frame.html",
- article_file=get_article_file(article_info),
- article_name=article_name,
- order_id=order_id)
+ return flask.render_template(
+ "templates/article_frame.html",
+ article_file=get_article_file(article_info),
+ article_name=article_name,
+ order_id=order_id
+ )
+
def get_qrcode_svg(data):
factory = qrcode.image.svg.SvgImage
@@ -239,12 +274,13 @@ def get_qrcode_svg(data):
# to check if the payment has been completed via the QR code.
@app.route("/check-status/<order_id>/<session_id>")
def check_status(order_id, session_id):
- pay_params = dict(instance=INSTANCE,
- order_id=order_id,
- session_id=session_id)
+ pay_params = dict(
+ instance=INSTANCE, order_id=order_id, session_id=session_id
+ )
pay_status = backend_get("check-payment", pay_params)
return flask.jsonify(paid=pay_status["paid"])
+
##
# Trigger a article purchase. The logic follows the main steps:
#
@@ -289,19 +325,21 @@ def article(article_name, data=None):
extra=dict(article_name=article_name),
fulfillment_url=flask.request.base_url,
instance=INSTANCE,
- summary="Essay: " + article_name.replace("_", " "))
+ summary="Essay: " + article_name.replace("_", " ")
+ )
order_resp = backend_post("order", dict(order=order))
order_id = order_resp["order_id"]
return flask.redirect(
- flask.url_for("article",
- article_name=article_name,
- order_id=order_id))
+ flask.url_for(
+ "article", article_name=article_name, order_id=order_id
+ )
+ )
##
# Prepare data for the upcoming payment check.
- pay_params = dict(instance=INSTANCE,
- order_id=order_id,
- session_id=session_id)
+ pay_params = dict(
+ instance=INSTANCE, order_id=order_id, session_id=session_id
+ )
pay_status = backend_get("check-payment", pay_params)
@@ -311,13 +349,18 @@ def article(article_name, data=None):
# Somehow, a session with a payed article which _differs_ from
# the article requested in the URL existed; trigger the pay protocol!
if pay_status["contract_terms"]["extra"]["article_name"] != article_name:
- err_abort(402, message="You did not pay for this article (nice try!)", json=pay_status)
-
+ err_abort(
+ 402,
+ message="You did not pay for this article (nice try!)",
+ json=pay_status
+ )
+
##
# Show a "article refunded" page, in that case.
if pay_status.get("refunded"):
- return flask.render_template("templates/article_refunded.html",
- article_name=article_name)
+ return flask.render_template(
+ "templates/article_refunded.html", article_name=article_name
+ )
##
# Put the article in the cache.
paid_articles_cache.set(session_id + "-" + article_name, order_id)
@@ -327,10 +370,12 @@ def article(article_name, data=None):
return render_article(article_name, data, order_id)
elif pay_status.get("already_paid_order_id") is not None:
return flask.redirect(
- flask.url_for(
- "article",
- article_name=article_name,
- order_id=pay_status.get("already_paid_order_id")))
+ flask.url_for(
+ "article",
+ article_name=article_name,
+ order_id=pay_status.get("already_paid_order_id")
+ )
+ )
else:
##
# Redirect the browser to a page where the wallet can
@@ -338,16 +383,18 @@ def article(article_name, data=None):
taler_pay_uri = pay_status["taler_pay_uri"]
qrcode_svg = get_qrcode_svg(taler_pay_uri)
check_status_url_enc = urllib.parse.quote(
- flask.url_for(
- "check_status",
- order_id=order_id,
- session_id=session_id))
- content = flask.render_template("templates/request_payment.html",
- article_name=article_name,
- taler_pay_uri=taler_pay_uri,
- qrcode_svg=qrcode_svg,
- check_status_url_enc=check_status_url_enc)
- headers = { "Taler": taler_pay_uri }
+ flask.url_for(
+ "check_status", order_id=order_id, session_id=session_id
+ )
+ )
+ content = flask.render_template(
+ "templates/request_payment.html",
+ article_name=article_name,
+ taler_pay_uri=taler_pay_uri,
+ qrcode_svg=qrcode_svg,
+ check_status_url_enc=check_status_url_enc
+ )
+ headers = {"Taler": taler_pay_uri}
resp = flask.Response(content, status=402, headers=headers)
return resp