gnunet-svn
[Top][All Lists]
Advanced

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

[GNUnet-SVN] [taler-bank] branch master updated: linting


From: gnunet
Subject: [GNUnet-SVN] [taler-bank] branch master updated: linting
Date: Fri, 03 Nov 2017 18:20:18 +0100

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

marcello pushed a commit to branch master
in repository bank.

The following commit(s) were added to refs/heads/master by this push:
     new baa520a  linting
baa520a is described below

commit baa520a09ecd9a07079bd0666e8a533d7b2e2aad
Author: Marcello Stanisci <address@hidden>
AuthorDate: Fri Nov 3 18:20:06 2017 +0100

    linting
---
 talerbank/app/views.py | 136 +++++++++++++++++++++++++++----------------------
 1 file changed, 75 insertions(+), 61 deletions(-)

diff --git a/talerbank/app/views.py b/talerbank/app/views.py
index c74a348..439f394 100644
--- a/talerbank/app/views.py
+++ b/talerbank/app/views.py
@@ -15,7 +15,13 @@
 #  @author Marcello Stanisci
 #  @author Florian Dold
 
+import json
+import logging
+import time
+import hashlib
 import re
+from urllib.parse import urljoin
+import requests
 import django.contrib.auth
 import django.contrib.auth.views
 import django.contrib.auth.forms
@@ -31,17 +37,11 @@ from simplemathcaptcha.fields import MathCaptchaField, 
MathCaptchaWidget
 from django.core.urlresolvers import reverse
 from django.contrib.auth.models import User
 from django.db.models import Q
-import json
-import logging
-import time
-import hashlib
-import requests
-from urllib.parse import urljoin
 from . import schemas
 from .models import BankAccount, BankTransaction
 from .amount import Amount, CurrencyMismatch, BadFormatAmount
 
-logger = logging.getLogger(__name__)
+LOGGER = logging.getLogger(__name__)
 
 class DebtLimitExceededException(Exception):
     pass
@@ -55,20 +55,20 @@ class 
MyAuthenticationForm(django.contrib.auth.forms.AuthenticationForm):
         self.fields["username"].widget.attrs["placeholder"] = "Username"
         self.fields["password"].widget.attrs["placeholder"] = "Password"
 
-
 def ignore(request):
     return HttpResponse()
 
+
 def javascript_licensing(request):
     return render(request, "javascript.html")
 
 def login_view(request):
     just_logged_out = get_session_flag(request, "just_logged_out")
     response = django.contrib.auth.views.login(
-            request,
-            authentication_form=MyAuthenticationForm,
-            template_name="login.html",
-            extra_context={"user": request.user})
+        request,
+        authentication_form=MyAuthenticationForm,
+        template_name="login.html",
+        extra_context={"user": request.user})
     # sometimes the response is a redirect and not a template response
     if hasattr(response, "context_data"):
         response.context_data["just_logged_out"] = just_logged_out
@@ -99,7 +99,7 @@ def profile_page(request):
     context = dict(
         name=user_account.user.username,
         balance=user_account.amount.stringify(settings.TALER_DIGITS),
-        sign = "-" if user_account.debit else "",
+        sign="-" if user_account.debit else "",
         precision=settings.TALER_DIGITS,
         currency=user_account.amount.currency,
         account_no=user_account.account_no,
@@ -113,9 +113,9 @@ def profile_page(request):
 
     response = render(request, "profile_page.html", context)
     if just_withdrawn:
-       response["X-Taler-Operation"] = "confirm-reserve"
-       response["X-Taler-Reserve-Pub"] = reserve_pub
-       response.status_code = 202
+        response["X-Taler-Operation"] = "confirm-reserve"
+        response["X-Taler-Reserve-Pub"] = reserve_pub
+        response.status_code = 202
     return response
 
 
@@ -156,8 +156,8 @@ def pin_tan_question(request):
     wiredetails = json.loads(request.GET["wire_details"])
     if not isinstance(wiredetails, dict) or "test" not in wiredetails:
         return HttpResponseBadRequest(
-                "This bank only supports the test wire transfer method. "
-                "The exchange does not seem to support it.")
+            "This bank only supports the test wire transfer method. "
+            "The exchange does not seem to support it.")
     try:
         schemas.validate_wiredetails(wiredetails)
     except ValueError as error:
@@ -214,39 +214,43 @@ def pin_tan_verify(request):
     try:
         BankAccount.objects.get(account_no=exchange_account_number)
     except BankAccount.DoesNotExist:
-        raise HttpResponseBadRequest("The bank account #{} of exchange {} does 
not exist".format(exchange_account_no, exchange_url))
+        raise HttpResponseBadRequest("The bank account #{} \
+                                     of exchange {} does not \
+                                     exist".format(exchange_account_number,
+                                                   exchange_url))
     logging.info("asking exchange {} to create reserve 
{}".format(exchange_url, reserve_pub))
     json_body = dict(
-            reserve_pub=reserve_pub,
-            execution_date="/Date(" + str(int(time.time())) + ")/",
-            sender_account_details=sender_wiredetails,
-             # just something unique
-            transfer_details=dict(timestamp=int(time.time() * 1000)),
-            amount=amount.dump(),
+        reserve_pub=reserve_pub,
+        execution_date="/Date(" + str(int(time.time())) + ")/",
+        sender_account_details=sender_wiredetails,
+        # just something unique
+        transfer_details=dict(timestamp=int(time.time() * 1000)),
+        amount=amount.dump(),
     )
     user_account = BankAccount.objects.get(user=request.user)
     exchange_account = 
BankAccount.objects.get(account_no=exchange_account_number)
     try:
         wire_transfer(amount, user_account, exchange_account, reserve_pub)
     except DebtLimitExceededException:
-        logger.warning("Withdrawal impossible due to debt limit exceeded")
+        LOGGER.warning("Withdrawal impossible due to debt limit exceeded")
         request.session["debt_limit"] = True
         return redirect("profile")
     except SameAccountException:
-        logger.error("Odd situation: SameAccountException should NOT occur in 
this function")
+        LOGGER.error("Odd situation: SameAccountException should NOT occur in 
this function")
         return JsonResponse(dict(error="Internal server error", status=500))
     except BadFormatAmount:
-        logger.error("parsing MAX_DEBT or MAX_BANK_DEBT failed")
+        LOGGER.error("parsing MAX_DEBT or MAX_BANK_DEBT failed")
         return JsonResponse(dict(error="Internal server error", status=500))
     except CurrencyMismatch:
-        logger.error("currency mismatch internal to the bank, should never 
happen here")
+        LOGGER.error("currency mismatch internal to the bank, should never 
happen here")
         return JsonResponse(dict(error="Internal server error", status=500))
 
     request_url = urljoin(exchange_url, "admin/add/incoming")
     res = requests.post(request_url, json=json_body)
     if res.status_code != 200:
         return render(request, "error_exchange.html", dict(
-            message="Could not transfer funds to the exchange.  The exchange 
({}) gave a bad response.".format(exchange_url),
+            message="Could not transfer funds to the exchange.  \
+                    The exchange ({}) gave a bad 
response.".format(exchange_url),
             response_text=res.text,
             response_status=res.status_code,
         ))
@@ -278,21 +282,23 @@ def register(request):
         user_account.save()
     bank_internal_account = BankAccount.objects.get(account_no=1)
     try:
-        wire_transfer(Amount(settings.TALER_CURRENCY, 100, 0), 
bank_internal_account, user_account, "Joining bonus")
+        wire_transfer(Amount(settings.TALER_CURRENCY, 100, 0),
+                      bank_internal_account, user_account,
+                      "Joining bonus")
     except DebtLimitExceededException:
-        logger.info("Debt situation encountered")
+        LOGGER.info("Debt situation encountered")
         request.session["no_initial_bonus"] = True
         return HttpResponseServerError()
     except CurrencyMismatch:
-        logger.error("Currency mismatch internal to the bank")
+        LOGGER.error("Currency mismatch internal to the bank")
         return HttpResponseServerError()
     except BadFormatAmount:
-        logger.error("Could not parse MAX_DEBT|MAX_BANK_DEBT")
+        LOGGER.error("Could not parse MAX_DEBT|MAX_BANK_DEBT")
         return HttpResponseServerError()
     except SameAccountException:
-        logger.error("Odd situation: SameAccountException should NOT occur in 
this function")
+        LOGGER.error("Odd situation: SameAccountException should NOT occur in 
this function")
         return HttpResponseServerError()
-        
+
     request.session["just_registered"] = True
     user = django.contrib.auth.authenticate(username=username, 
password=password)
     django.contrib.auth.login(request, user)
@@ -311,7 +317,7 @@ def logout_view(request):
 def extract_history(account):
     history = []
     related_transactions = BankTransaction.objects.filter(
-            Q(debit_account=account) | Q(credit_account=account))
+        Q(debit_account=account) | Q(credit_account=account))
     for item in related_transactions:
         if item.credit_account == account:
             counterpart = item.debit_account
@@ -320,8 +326,8 @@ def extract_history(account):
             counterpart = item.credit_account
             sign = "-"
         entry = dict(
-            sign = sign,
-            amount = item.amount.stringify(settings.TALER_DIGITS),
+            sign=sign,
+            amount=item.amount.stringify(settings.TALER_DIGITS),
             counterpart=counterpart.account_no,
             counterpart_username=counterpart.user.username,
             subject=item.subject,
@@ -368,7 +374,7 @@ def history(request):
     if not delta:
         return HttpResponseBadRequest()
     #FIXME: make the '+' sign optional
-    parsed_delta = re.search("([\+-])?([0-9]+)", delta)
+    parsed_delta = re.search(r"([\+-])?([0-9]+)", delta)
     try:
         parsed_delta.group(0)
     except AttributeError:
@@ -400,7 +406,7 @@ def history(request):
         try:
             target_account = BankAccount.objects.get(account_no=target_account)
         except BankAccount.DoesNotExist:
-            logger.error("Attempted /history about non existent account")
+            LOGGER.error("Attempted /history about non existent account")
             return JsonResponse(dict(error="Queried account does not exist"), 
status=404)
 
     if target_account != user_account.bankaccount:
@@ -444,14 +450,14 @@ def auth_and_login(request):
         auth_type = request.GET.get("auth")
 
     if "basic" != auth_type:
-        logger.error("auth method not supported")
+        LOGGER.error("auth method not supported")
         return False
 
     username = request.META.get("HTTP_X_TALER_BANK_USERNAME")
     password = request.META.get("HTTP_X_TALER_BANK_PASSWORD")
-    logger.info("Trying to log '%s/%s' in" % (username, password))
+    LOGGER.info("Trying to log '%s/%s' in" % (username, password))
     if not username or not password:
-        logger.error("user or password not given")
+        LOGGER.error("user or password not given")
         return False
     return django.contrib.auth.authenticate(username=username,
                                             password=password)
@@ -472,13 +478,13 @@ def add_incoming(request):
     try:
         schemas.validate_incoming_request(data)
     except ValueError as error:
-        logger.error("Bad data POSTed: %s" % error)
+        LOGGER.error("Bad data POSTed: %s" % error)
         return JsonResponse(dict(error="invalid data POSTed: %s" % error), 
status=400)
 
     user_account = auth_and_login(request)
 
     if not user_account:
-        logger.error("authentication failed")
+        LOGGER.error("authentication failed")
         return JsonResponse(dict(error="authentication failed"),
                             status=401)
 
@@ -489,28 +495,34 @@ def add_incoming(request):
     try:
         schemas.validate_amount(data["amount"])
         if settings.TALER_CURRENCY != data["amount"]["currency"]:
-            logger.error("Currency differs from bank's")
+            LOGGER.error("Currency differs from bank's")
             return JsonResponse(dict(error="Currency differs from bank's"), 
status=406)
         transaction = wire_transfer(Amount(**data["amount"]),
                                     user_account.bankaccount,
                                     credit_account,
                                     subject)
-        return JsonResponse(dict(serial_id=transaction.id, 
timestamp="/Date(%s)/" % int(transaction.date.timestamp())))
+        return JsonResponse(dict(serial_id=transaction.id,
+                                 timestamp="/Date(%s)/" %
+                                 int(transaction.date.timestamp())))
     except ValueError as e:
         return JsonResponse(dict(error=e), status=400)
 
     except BadFormatAmount:
-        logger.error("Bad MAX_DEBT|MAX_BANK_DEBT format")
-        return JsonResponse(dict(error="Internal server error"), status=500)
+        LOGGER.error("Bad MAX_DEBT|MAX_BANK_DEBT format")
+        return JsonResponse(dict(error="Internal server error"),
+                            status=500)
     except CurrencyMismatch:
-        logger.error("Internal currency inconsistency")
-        return JsonResponse(dict(error="Internal server error"), status=500)
+        LOGGER.error("Internal currency inconsistency")
+        return JsonResponse(dict(error="Internal server error"),
+                            status=500)
     except SameAccountException:
-        return JsonResponse(dict(error="debit and credit account are the 
same"), status=422)
+        return JsonResponse(dict(error="debit and credit account are the 
same"),
+                            status=422)
     except DebtLimitExceededException:
-        logger.info("Prevenetd transfer, debit account would go beyond debt 
threshold")
-        return JsonResponse(dict(error="debit count has reached its debt 
limit", status=403 ),
-                             status=403)
+        LOGGER.info("Prevenetd transfer, debit account would go beyond debt 
threshold")
+        return JsonResponse(dict(error="debit count has reached its debt 
limit",
+                                 status=403),
+                            status=403)
 
 @login_required
 @require_POST
@@ -519,7 +531,7 @@ def withdraw_nojs(request):
     try:
         amount = Amount.parse(request.POST.get("kudos_amount", ""))
     except BadFormatAmount:
-        logger.error("Amount did not pass parsing")
+        LOGGER.error("Amount did not pass parsing")
         return HttpResponseBadRequest()
 
     user_account = BankAccount.objects.get(user=request.user)
@@ -541,7 +553,7 @@ def withdraw_nojs(request):
 
 def wire_transfer(amount, debit_account, credit_account, subject):
     if debit_account.pk == credit_account.pk:
-        logger.error("Debit and credit account are the same!")
+        LOGGER.error("Debit and credit account are the same!")
         raise SameAccountException()
 
     transaction_item = BankTransaction(amount=amount,
@@ -550,7 +562,7 @@ def wire_transfer(amount, debit_account, credit_account, 
subject):
                                        subject=subject)
     if debit_account.debit:
         debit_account.amount.add(amount)
-   
+
     elif -1 == Amount.cmp(debit_account.amount, amount):
         debit_account.debit = True
         tmp = Amount(**amount.dump())
@@ -578,8 +590,10 @@ def wire_transfer(amount, debit_account, credit_account, 
subject):
     if 1 == Amount.cmp(debit_account.amount, threshold) \
         and 0 != Amount.cmp(Amount(settings.TALER_CURRENCY), threshold) \
         and debit_account.debit:
-        logger.info("Negative balance '%s' not allowed." % 
json.dumps(debit_account.amount.dump()))
-        logger.info("%s's threshold is: '%s'." % (debit_account.user.username, 
json.dumps(threshold.dump())))
+        LOGGER.info("Negative balance '%s' not allowed." % 
json.dumps(debit_account.amount.dump()))
+        LOGGER.info("%s's threshold is: '%s'." %
+                    (debit_account.user.username,
+                     json.dumps(threshold.dump())))
         raise DebtLimitExceededException()
 
     with transaction.atomic():

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



reply via email to

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