gnunet-svn
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[GNUnet-SVN] [taler-merchant-frontends] branch master updated: Separatin


From: gnunet
Subject: [GNUnet-SVN] [taler-merchant-frontends] branch master updated: Separating helpers and error handlers.
Date: Mon, 27 Feb 2017 15:43:57 +0100

This is an automated email from the git hooks/post-receive script.

marcello pushed a commit to branch master
in repository merchant-frontends.

The following commit(s) were added to refs/heads/master by this push:
     new 51a95ed  Separating helpers and error handlers.
51a95ed is described below

commit 51a95ed292310ecea97ec81b7fea72bfd7a28542
Author: Marcello Stanisci <address@hidden>
AuthorDate: Mon Feb 27 15:43:26 2017 +0100

    Separating helpers and error handlers.
---
 talerfrontends/blog/blog.py     |  12 +-
 talerfrontends/common_routes.py |  89 ---------------
 talerfrontends/errors.py        | 178 +++++++++++++++++++++++++++++
 talerfrontends/helpers.py       | 246 ++++------------------------------------
 4 files changed, 205 insertions(+), 320 deletions(-)

diff --git a/talerfrontends/blog/blog.py b/talerfrontends/blog/blog.py
index cfd0ae3..979cf41 100644
--- a/talerfrontends/blog/blog.py
+++ b/talerfrontends/blog/blog.py
@@ -30,20 +30,20 @@ import random
 import time
 import json
 import datetime
-from talerfrontends.common_routes import tracking
 from pprint import pprint
 from talerfrontends.talerconfig import TalerConfig
-from talerfrontends.helpers import (make_url, frontend_common,
-        expect_parameter, expect_parameter_int, BackendError,
-        MalformedParameterError, join_urlparts, TrackNotReadyError)
-from talerfrontends.blog.content import articles, get_article_file, 
get_image_file
+from talerfrontends.helpers import (make_url,
+expect_parameter, expect_parameter_int, join_urlparts)
+from talerfrontends.errors import (TrackNotReadyError,
+MalformedParameterError, BackendError)
+from talerfrontends.blog.content import (articles,
+get_article_file, get_image_file)
 
 logger = logging.getLogger(__name__)
 
 base_dir = os.path.dirname(os.path.abspath(__file__))
 
 app = flask.Flask(__name__, template_folder=base_dir)
-app.register_blueprint(frontend_common)
 app.debug = True
 app.secret_key = base64.b64encode(os.urandom(64)).decode('utf-8')
 
diff --git a/talerfrontends/common_routes.py b/talerfrontends/common_routes.py
deleted file mode 100644
index ee1b930..0000000
--- a/talerfrontends/common_routes.py
+++ /dev/null
@@ -1,89 +0,0 @@
-# This file is part of GNU TALER.
-# Copyright (C) 2014-2016 INRIA
-#
-# TALER is free software; you can redistribute it and/or modify it under the
-# terms of the GNU Lesser General Public License as published by the Free 
Software
-# Foundation; either version 2.1, or (at your option) any later version.
-#
-# TALER is distributed in the hope that it will be useful, but WITHOUT ANY
-# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-# A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more 
details.
-#
-# You should have received a copy of the GNU Lesser General Public License 
along with
-# GNU TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
-#
-# @author Marcello Stanisci
-
-
-from flask import render_template, abort, session, request
-from talerfrontends.helpers import expect_parameter, track_transaction, \
-track_transfer, TrackNotReadyError, talerdate_to_obj, get_history, \
-expect_parameter_int, amount_to_string, frontend_common, CustomError, \
-amount_get_zero, amount_sum, amount_sub, map_out
-import logging
-import base64
-import json
-
-logger = logging.getLogger(__name__)
-
address@hidden('/error')
-def custom_error():
-    error_enc = expect_parameter("enc")
-    error = base64.b64decode(error_enc)
-    body = json.loads(error.decode("utf-8"))
-    raise CustomError(body['code'], body['hint'], body['status'])
-
address@hidden('/map')
-def map_contract():
-    h_contract = expect_parameter("h_contract")
-    ret = map_out(h_contract)
-    return ret
-
address@hidden('/track')
address@hidden('/track/<track_type>')
-def tracking(track_type=None):
-    if not track_type:
-        return render_template('tracking.html')
-    if track_type not in {"transaction", "transfer"}:
-        abort(404)
-    instance = expect_parameter("instance", "default")
-    if "transaction" == track_type:
-        transaction = expect_parameter("tid")
-        logger.info("serving /track/transaction, %s/%s" % (transaction, 
instance))
-        try:
-            track = track_transaction(transaction, instance)
-        except TrackNotReadyError:
-            return render_template('tracking.html', msg="Wire transfer still 
undone")
-        logger.info(track)
-        track_fmt = []
-        for obj in track:
-            date = talerdate_to_obj(obj['execution_time'])
-            # Compute total amount
-            tmp = amount_get_zero()
-            tmp_fee = amount_get_zero()
-            for el in obj["coins"]:
-                tmp = amount_sum(tmp, el["amount_with_fee"])
-                tmp_fee = amount_sum(tmp_fee, el["deposit_fee"])
-            amount = amount_sub(tmp, tmp_fee)
-            track_fmt.append(dict(wtid=obj["wtid"],
-                                  exchange=obj["exchange"],
-                                  date=date.strftime("%d/%b/%Y at %H:%M:%S"),
-                                  amount=amount_to_string(amount)))
-        return render_template('tracking.html',
-                               transaction=True,
-                               tracks=track_fmt,
-                               original=dict(transaction=transaction, 
instance=instance))
-    else:
-        wtid = expect_parameter("wtid")
-        exchange = expect_parameter("exchange-uri")
-        logger.info("serving /track/transfer, %s/%s/%s" % (wtid, exchange, 
instance))
-        track = track_transfer(wtid, exchange, instance)
-        logger.info(track)
-        track["total"] = amount_to_string(track["total"])
-        for obj in track["deposits"]:
-            obj["deposit_value"] = amount_to_string(obj["deposit_value"])
-        return render_template('tracking.html',
-                               transfer=True,
-                               tracks=track,
-                               original=dict(wtid=wtid, instance=instance))
- 
diff --git a/talerfrontends/errors.py b/talerfrontends/errors.py
new file mode 100644
index 0000000..36f42fa
--- /dev/null
+++ b/talerfrontends/errors.py
@@ -0,0 +1,178 @@
+#  This file is part of TALER
+#  (C) 2016 INRIA
+#
+#  TALER is free software; you can redistribute it and/or modify it under the
+#  terms of the GNU Affero General Public License as published by the Free 
Software
+#  Foundation; either version 3, or (at your option) any later version.
+#
+#  TALER is distributed in the hope that it will be useful, but WITHOUT ANY
+#  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 
FOR
+#  A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+#  You should have received a copy of the GNU General Public License along with
+#  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
+#
+#  @author Florian Dold
+#  @author Marcello Stanisci
+
+from flask import make_response, Blueprint
+from . import helpers
+
+# This class is used when the wallet detects any error
+# and it calls the onError handler installed by the merchant
+class CustomError(Exception):
+    def __init__(self, code, hint, status):
+        self.code = code
+        self.hint = hint
+        self.status = status
+        super().__init__(code)
+
+
+class MissingParameterError(Exception):
+    def __init__(self, name):
+        self.name = name
+        super().__init__(name)
+
+
+class MalformedDateError(Exception):
+    def __init__(self, date):
+        self.date = date
+        super().__init__()
+
+
+class NoSessionActiveError(Exception):
+    def __init__(self):
+        super().__init__()
+
+
+class MalformedParameterError(Exception):
+    def __init__(self, name):
+        self.name = name
+        super().__init__(name)
+
+
+class BackendError(Exception):
+    def __init__(self, status, response):
+        self.status = status
+        self.response = response
+        super().__init__(status, response)
+
+
+class TrackNotReadyError(Exception):
+    def __init__(self, status, error_code, order_id):
+        self.status = status
+        self.order_id = order_id
+        self.error_code = error_code
+        super().__init__(status, 'Track not ready')
+
+
+class TrackTransactionConflictError(Exception):
+    def __init__(self, status, transaction_id, response):
+        self.status = status
+        self.response = response
+        self.transaction_id = transaction_id
+        super().__init__(status, response)
+
+
+class TrackTransferConflictError(Exception):
+    def __init__(self, status, wtid, response):
+        self.status = status
+        self.response = response
+        self.wtid = wtid
+        super().__init__(status, response)
+
+
+def make_400(ret):
+    return make_response(ret, 400)
+
+
+frontend_common = Blueprint("talerfrontends-common",
+                             __name__,
+                            template_folder="templates",
+                            static_folder="static",
+                            static_url_path="/static-common")
+
+
address@hidden(MissingParameterError)
+def handle_missing_parameter_error(error):
+    logger.warn("Missing parameter '%s' in request from client '%s'",
+                error.name,
+                request.remote_addr)
+    return make_400(render_template("error.html",
+                                         error="missing parameter",
+                                         details=error.name))
+
+
address@hidden(NoSessionActiveError)
+def handle_no_session_active_error(error):
+    logger.warn("No session active")
+    return make_400(render_template("error.html",
+                                   error="no session active",
+                                   details="purchase was not initiated 
correctly"))
+
+
address@hidden(MalformedParameterError)
+def handle_malformed_parameter_error(error):
+    logger.warn("Malformed parameter '%s' in request from client '%s'",
+                error.name,
+                request.remote_addr)
+    return make_400(render_template("error.html",
+                                    error="malformed parameter",
+                                    details=error.name))
+
+
address@hidden(MalformedDateError)
+def handle_malformed_parameter_error(error):
+    logger.warn("Malformed date gotten")
+    return make_400(render_template("error.html",
+                                    error="malformed date",
+                                    details="got '%s'" % error.date))
+
+
address@hidden(BackendError)
+def handle_backend_error(error):
+    logger.warn("Backend error, status %s, body %s", error.status, 
repr(error.response))
+    return make_response(render_template("error.html",
+                                         error="backend error",
+                                         details=error.response),
+                         error.status)
+
address@hidden(CustomError)
+def handle_custom_error(error):
+    logger.warn("Triggering custom error: %s, hint: %s, status code: %d" % 
(error.code, error.hint, error.status))
+    return make_response(render_template("error.html",
+                                         error=error.code,
+                                         details=error.hint),
+                                         error.status)                        
+
address@hidden(TrackNotReadyError)
+def handle_track_not_ready_error(error):
+    logger.warn("Order %s has not been transferred yet" % error.order_id)
+    return make_response(render_template("error.html",
+                                         error = error.error_code,
+                                         details = "Order %s is still waiting 
for being paid back" % error.order_id))
+
address@hidden(TrackTransactionConflictError)
+def handle_track_transaction_conflict_error(error):
+    logger.warn("Transaction %s is conflicting" % error.transaction_id)
+    return make_response(render_template("transaction_conflict.html",
+                                        transaction_id = error.transaction_id,
+                                         details = json.loads(error.response)),
+                                        error.status)
+
+
address@hidden(TrackTransferConflictError)
+def handle_track_transfer_conflict_error(error):
+    logger.info(error)
+    logger.warn("Transfer %s is conflicting" % error.wtid)
+    error_object = json.loads(error.response)
+    offset = error_object["conflict_offset"]
+    conflicting_coin = 
error_object["exchange_transfer_proof"]["deposits"][offset]
+    transferred_amount_with_fee = 
amount_sum(conflicting_coin["deposit_value"], conflicting_coin["deposit_fee"])
+    return make_response(render_template("transfer_conflict.html",
+                                        wtid = error.wtid,
+                                         transferred_amount = 
helpers.amount_to_string(transferred_amount_with_fee),
+                                        expected_amount = 
helpers.amount_to_string(error_object["amount_with_fee"]),
+                                         details = error.response,
+                                         
transaction_id=conflicting_coin["transaction_id"]),
+                                        error.status)
diff --git a/talerfrontends/helpers.py b/talerfrontends/helpers.py
index 9d3dc14..9ed79bd 100644
--- a/talerfrontends/helpers.py
+++ b/talerfrontends/helpers.py
@@ -13,8 +13,9 @@
 #  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 #
 #  @author Florian Dold
+#  @author Marcello Stanisci
 
-from flask import Blueprint, request, jsonify, make_response, current_app, 
render_template
+from flask import request, jsonify, make_response, current_app, render_template
 from urllib.parse import urljoin, urlencode
 import logging
 import requests
@@ -22,12 +23,11 @@ import re
 import datetime
 import json
 from talerfrontends.talerconfig import TalerConfig
+from .errors import (MalformedDateError,
+MissingParameterError, MalformedParameterError)
 
 logger = logging.getLogger(__name__)
 
-TRACK_TRANSFER_CONFLICT = 2408
-TRACK_TRANSACTION_CONFLICT = 2308
-
 tc = TalerConfig.from_env()
 BACKEND_URL = tc["frontends"]["backend"].value_string(required=True)
 NDIGITS = tc["frontends"]["NDIGITS"].value_int()
@@ -136,74 +136,6 @@ def talerdate_to_obj(talerdate):
 def talerdate(t):
     return "/Date(" + str(t) + ")/"
 
-frontend_common = Blueprint("talerfrontends-common",
-                            __name__,
-                template_folder="templates",
-                static_folder="static",
-                static_url_path="/static-common")
-
-
-# This class is used when the wallet detects any error
-# and it calls the onError handler installed by the merchant
-class CustomError(Exception):
-    def __init__(self, code, hint, status):
-        self.code = code
-        self.hint = hint
-        self.status = status
-        super().__init__(code)
-
-
-class MissingParameterError(Exception):
-    def __init__(self, name):
-        self.name = name
-        super().__init__(name)
-
-
-class MalformedDateError(Exception):
-    def __init__(self, date):
-        self.date = date
-        super().__init__()
-
-
-class NoSessionActiveError(Exception):
-    def __init__(self):
-        super().__init__()
-
-
-class MalformedParameterError(Exception):
-    def __init__(self, name):
-        self.name = name
-        super().__init__(name)
-
-
-class BackendError(Exception):
-    def __init__(self, status, response):
-        self.status = status
-        self.response = response
-        super().__init__(status, response)
-
-class TrackNotReadyError(Exception):
-    def __init__(self, status, error_code, order_id):
-        self.status = status
-        self.order_id = order_id
-        self.error_code = error_code
-        super().__init__(status, 'Track not ready')
-
-class TrackTransactionConflictError(Exception):
-    def __init__(self, status, transaction_id, response):
-        self.status = status
-        self.response = response
-        self.transaction_id = transaction_id
-        super().__init__(status, response)
-
-class TrackTransferConflictError(Exception):
-    def __init__(self, status, wtid, response):
-        self.status = status
-        self.response = response
-        self.wtid = wtid
-        super().__init__(status, response)
-
-
 def expect_parameter(name, alt=None):
     value = request.args.get(name, None)
     if value is None and alt is None:
@@ -225,156 +157,20 @@ def expect_form(name):
         raise MissingParameterError(name)
     return value
 
-# days must be a number
-def get_history(days):
-    if type(days) != int:
-        raise ValueError
-    date = datetime.datetime.fromtimestamp(0)
-    if 0 != days:
-        now = datetime.date.today()
-        d = datetime.timedelta(days=days)
-        date = now - d
-    url = urljoin(current_app.config["BACKEND_URL"], "history")
-    r = requests.get(url, params=dict(date=date.strftime("%s")))
-    if r.status_code != 200:
-        logger.error("failed to GET to '%s'", url)
-        raise BackendError(r.status_code, r.text)
-    return r.text
-
-
-# Issue a /map/out call to the backend
-def map_out(h_contract):
-    url = urljoin(current_app.config["BACKEND_URL"], "map/out")
-    r = requests.get(url, dict(h_contract=h_contract))
-    if r.status_code != 200:
-        logger.error("failed to GET to '%s'", url)
-        raise BackendError(r.status_code, r.text)
-    return r.text
-
-def track_transfer(wtid, exchange_uri, instance):
-    url = urljoin(current_app.config["BACKEND_URL"], 'track/transfer')
-    r = requests.get(url, dict(wtid=wtid, exchange=exchange_uri, 
instance=instance))
-    if r.status_code not in [200, 424, 404]:
-        logger.error("failed to GET to '%s'", url)
-        logger.info(r.text)
-        raise BackendError(r.status_code, r.text if r.text else "{\"hard 
error\": \"No error given by backend\"}")
-    if 424 == r.status_code:
-        error_code = json.loads(r.text)['code']
-        if TRACK_TRANSFER_CONFLICT == error_code:
-            raise TrackTransferConflictError(r.status_code, wtid, r.text)
-        else:
-            raise CustomError(error_code, r.details, r.status_code)
-    if 404 == r.status_code:
-        raise CustomError(error_code, "Unknown wtid supplied", r.status_code)
-    track = r.json()
-    return track
-
-
-def track_transaction(tid, instance):
-    url = urljoin(current_app.config["BACKEND_URL"], 'track/transaction')
-    params = {'id': tid, 'instance': instance}
-    r = requests.get(url, params)
-    logger.info(r.text)
-    if r.status_code not in [200, 202, 424]:
-        logger.error("failed to GET to '%s'", url)
-        raise BackendError(r.status_code, r.text)
-    if 202 == r.status_code:
-        raise TrackNotReadyError(r.status_code, tid)
-    if 404 == r.status_code:
-        raise CustomError(r.code, "Unknown transaction supplied", 
s.status_code)
-    if 424 == r.status_code:
-        raise TrackTransactionConflictError(r.status_code, tid, r.text)
-    else:
-        raise BackendError(r.status_code, r.text)
-    track = r.json()
-    return track
-
-
-def make_400(ret):
-    return make_response(ret, 400)
-
-
address@hidden(MissingParameterError)
-def handle_missing_parameter_error(error):
-    logger.warn("Missing parameter '%s' in request from client '%s'",
-                error.name,
-                request.remote_addr)
-    return make_400(render_template("error.html",
-                                         error="missing parameter",
-                                         details=error.name))
-
-
address@hidden(NoSessionActiveError)
-def handle_no_session_active_error(error):
-    logger.warn("No session active")
-    return make_400(render_template("error.html",
-                                   error="no session active",
-                                   details="purchase was not initiated 
correctly"))
-
-
address@hidden(MalformedParameterError)
-def handle_malformed_parameter_error(error):
-    logger.warn("Malformed parameter '%s' in request from client '%s'",
-                error.name,
-                request.remote_addr)
-    return make_400(render_template("error.html",
-                                    error="malformed parameter",
-                                    details=error.name))
-
-
address@hidden(MalformedDateError)
-def handle_malformed_parameter_error(error):
-    logger.warn("Malformed date gotten")
-    return make_400(render_template("error.html",
-                                    error="malformed date",
-                                    details="got '%s'" % error.date))
-
-
address@hidden(BackendError)
-def handle_backend_error(error):
-    logger.warn("Backend error, status %s, body %s", error.status, 
repr(error.response))
-    return make_response(render_template("error.html",
-                                         error="backend error",
-                                         details=error.response),
-                         error.status)
-
address@hidden(CustomError)
-def handle_custom_error(error):
-    logger.warn("Triggering custom error: %s, hint: %s, status code: %d" % 
(error.code, error.hint, error.status))
-    return make_response(render_template("error.html",
-                                         error=error.code,
-                                         details=error.hint),
-                                         error.status)                        
-
address@hidden(TrackNotReadyError)
-def handle_track_not_ready_error(error):
-    logger.warn("Order %s has not been transferred yet" % error.order_id)
-    return make_response(render_template("error.html",
-                                         error = error.error_code,
-                                         details = "Order %s is still waiting 
for being paid back" % error.order_id))
-
address@hidden(TrackTransactionConflictError)
-def handle_track_transaction_conflict_error(error):
-    logger.warn("Transaction %s is conflicting" % error.transaction_id)
-    return make_response(render_template("transaction_conflict.html",
-                                        transaction_id = error.transaction_id,
-                                         details = json.loads(error.response)),
-                                        error.status)
-
-
address@hidden(TrackTransferConflictError)
-def handle_track_transfer_conflict_error(error):
-    logger.info(error)
-    logger.warn("Transfer %s is conflicting" % error.wtid)
-    error_object = json.loads(error.response)
-    offset = error_object["conflict_offset"]
-    conflicting_coin = 
error_object["exchange_transfer_proof"]["deposits"][offset]
-    transferred_amount_with_fee = 
amount_sum(conflicting_coin["deposit_value"], conflicting_coin["deposit_fee"])
-
-    return make_response(render_template("transfer_conflict.html",
-                                        wtid = error.wtid,
-                                         transferred_amount = 
amount_to_string(transferred_amount_with_fee),
-                                        expected_amount = 
amount_to_string(error_object["amount_with_fee"]),
-                                         details = error.response,
-                                         
transaction_id=conflicting_coin["transaction_id"]),
-                                        error.status)
+#def track_transfer(wtid, exchange_uri, instance):
+#    url = urljoin(current_app.config["BACKEND_URL"], 'track/transfer')
+#    r = requests.get(url, dict(wtid=wtid, exchange=exchange_uri, 
instance=instance))
+#    if r.status_code not in [200, 424, 404]:
+#        logger.error("failed to GET to '%s'", url)
+#        logger.info(r.text)
+#        raise BackendError(r.status_code, r.text if r.text else "{\"hard 
error\": \"No error given by backend\"}")
+#    if 424 == r.status_code:
+#        error_code = json.loads(r.text)['code']
+#        if TRACK_TRANSFER_CONFLICT == error_code:
+#            raise TrackTransferConflictError(r.status_code, wtid, r.text)
+#        else:
+#            raise CustomError(error_code, r.details, r.status_code)
+#    if 404 == r.status_code:
+#        raise CustomError(error_code, "Unknown wtid supplied", r.status_code)
+#    track = r.json()
+#    return track

-- 
To stop receiving notification emails like this one, please contact
address@hidden



reply via email to

[Prev in Thread] Current Thread [Next in Thread]