index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
39,495,705
xdiabetes/xproject_api
refs/heads/master
/xapp/api_v1/modules/payment/common.py
# common payment functions from xapp.api_v1.consts import InvoiceConsts def validate_invoice(invoice): return invoice.fake or invoice.status not in [InvoiceConsts.PAYED, InvoiceConsts.INTERNAL, InvoiceConsts.IN_PAYMENT] and invoice.amount >= 1000
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,706
xdiabetes/xproject_api
refs/heads/master
/xapp/api_v1/consts.py
from django.utils.translation import gettext as _ class InvoiceConsts: # balance types DEPOSIT = '0' WITHDRAW = '1' CLEARING = '2' # states PAYED = '0' CREATED = '1' IN_PAYMENT = '2' REJECTED = '3' INTERNAL = '4' REFUNDED = '5' # tags CHARGE_WALLET = '3' CHARGE_WALLET_FROM_CAFEPAY = '6' REFUND = '0' PAYED_FOR_PRODUCT = '1' PAY_PBR_SESSION = '2' CLEARING_TAG = '5' DELIVERY_FEE = '6' # methods ONLINE = '0' POS = '1' CASH = '2' CARD_TO_CARD = '3' DISCOUNT = '4' GUEST = '5' tags = ((REFUND, _("Refund")), (CHARGE_WALLET, _("Charge Wallet")), (CHARGE_WALLET_FROM_CAFEPAY, _("Charge Wallet From Xproject")), (PAYED_FOR_PRODUCT, _("Payed for product")), (PAY_PBR_SESSION, _("Pay for session")), (DELIVERY_FEE, _("Delivery Fee")), (CLEARING_TAG, _("Clearing"))) balance_types = ( (DEPOSIT, _('Deposit')), (WITHDRAW, _('Withdraw')), (CLEARING, _("Clearing")) ) states = ( (PAYED, _('Payed')), (CREATED, _('Created')), (IN_PAYMENT, _('In Payment')), (REJECTED, _('Rejected')), (REFUNDED, _('Refunded')), (INTERNAL, _("Internal")) ) methods = ( (ONLINE, _("Online")), (POS, _("POS")), (CASH, _("CASH")), (DISCOUNT, _("Discount")), (CARD_TO_CARD, _("CardToCard")), (GUEST, _("Guest")) ) class AccountInfoConsts: VERIFIED = '0' PENDING = '1' REJECTED = '2' _account_verification_states = ((VERIFIED, _('Verified')), (PENDING, _('Pending')), (REJECTED, _('Rejected'))) class CharacterFieldConsts: EMAIL = '0' PHONE = '1' CATEGORY = '2' GROUP = '3' types = ( (EMAIL, "Email"), (PHONE, "Phone"), (GROUP, "Group"), (CATEGORY, "Category") ) class UserProfileConsts: PENDING = '0' VERIFIED = '1' states = ( (PENDING, "Pending"), (VERIFIED, "Verified"), ) class CafeUserProfileRelationConsts: PENDING = '0' VERIFIED = '1' REMOVED = '2' states = ( (PENDING, _("Pending")), (VERIFIED, _("Verified")), (REMOVED, _("Removed")) ) class DateTimeRangeConsts: SATURDAY = '0' SUNDAY = '1' MONDAY = '2' TUESDAY = '3' WEDNESDAY = '4' THURSDAY = '5' FRIDAY = '6' days = ( (SATURDAY, "Saturday"), (SUNDAY, "Sunday"), (MONDAY, "Monday"), (TUESDAY, "Tuesday"), (WEDNESDAY, "Wednesday"), (THURSDAY, "Thursday"), (FRIDAY, "Friday") )
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,707
xdiabetes/xproject_api
refs/heads/master
/xapp/api_v1/consumers/helpers.py
from django.db.models.query import QuerySet from django.http.response import Http404 from django.utils.translation import gettext as _ class SocketException(Exception): pass class SafeNotFoundException(SocketException): status_code = 404 POST = 'POST' PUT = 'PUT' DELETE = 'DELETE' GET = 'GET' WATCH = 'WATCH' MODIFY_METHODS = [POST, PUT, DELETE] GET_METHODS = [GET, WATCH] TABLE_SIMPLE_DATA = 'table_simple_data' TABLE_DETAILED_DATA = 'table_detailed_data' CAFE_TABLES_SIMPLE_DATA = 'cafe_tables_simple_data' def get_object_or_404(Base, **kwargs): try: if type(Base) == QuerySet: return Base.get(**kwargs) return Base.objects.get(**kwargs) except (Base.DoesNotExist, Http404) as e: raise ConsumerException(_("Object not found")) class ConsumerException(SocketException): pass
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,708
xdiabetes/xproject_api
refs/heads/master
/xapp/apps.py
from django.apps import AppConfig class XprojectConfig(AppConfig): name = 'xapp'
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,709
xdiabetes/xproject_api
refs/heads/master
/xapp/api_v1/views/UserProfileViews.py
from django.utils.translation import ugettext as _ from rest_framework import generics, status from rest_framework.authtoken.models import Token from rest_framework.generics import RetrieveUpdateAPIView from rest_framework.response import Response from xapp.api_v1.consts import UserProfileConsts from xapp.api_v1.permissions import IsLoggedIn from xapp.api_v1.serializers.UserProfileSerializrs import UserProfileCRSerializer, UserProfileUpdateSerializer, \ UserProfilePhoneVerificationSerializer, SendXprojectCodeSerializer from xapp.models import UserProfilePhoneVerification, UserProfile from xproject.secret import DEMO class SendXprojectCode(generics.GenericAPIView): """ Send Code. Send verification code. phone must have been registered before. if send failed respond with wait time. """ serializer_class = SendXprojectCodeSerializer @staticmethod def get_user_profile(phone_number): try: return UserProfile.objects.get(phone_number=phone_number) except UserProfile.DoesNotExist: ups = UserProfileCRSerializer(data={'phone_number': phone_number}) ups.is_valid(raise_exception=True) user_profile = ups.save() return user_profile def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) upv = UserProfilePhoneVerification.objects. \ create(user_profile=self.get_user_profile(serializer.data.get('phone_number'))) if upv['status'] != 201: return Response({'detail': _("Code not sent"), 'wait': upv['wait']}, status=upv['status']) if DEMO: return Response({"code": upv['obj'].code}) return Response({'detail': _("Code sent")}) class UserProfileAuthTokenView(generics.GenericAPIView): """ User Profile Auth token. match phone number and verification code. return user token on success. """ serializer_class = UserProfilePhoneVerificationSerializer def post(self, request, *args, **kwargs): phone = request.data.get('phone_number') code = request.data.get('code') user_profile_phone_ = UserProfilePhoneVerification.objects.order_by('create_date'). \ filter( query_times__lt=UserProfilePhoneVerification.MAX_QUERY, used=False, burnt=False, user_profile__phone_number=phone ) user_profile_phone = user_profile_phone_.last() if not user_profile_phone: return Response({'detail': _('Phone number not found')}, status=status.HTTP_404_NOT_FOUND) if code != user_profile_phone.code: user_profile_phone.query_times += 1 user_profile_phone.save() return Response({'detail': _('Invalid verification code'), 'allowed_retry_times': UserProfilePhoneVerification.MAX_QUERY - user_profile_phone.query_times}, status=status.HTTP_403_FORBIDDEN) user_profile_phone.user_profile.verification_status = UserProfileConsts.VERIFIED user_profile_phone.user_profile.save() token, created = Token.objects.get_or_create(user=user_profile_phone.user_profile.django_user) user_profile_phone.used = True user_profile_phone.save() # mark all other codes as burnt user_profile_phone_.update(burnt=True) return Response(self.serializer_class(instance=user_profile_phone.user_profile).data) class UserProfileRUView(RetrieveUpdateAPIView): """ User Profile Retrieve. Currently logged in User can retrieve and update itself. they cannot change their phone number. """ serializer_class = UserProfileUpdateSerializer permission_classes = (IsLoggedIn,) def get_object(self): return self.request.user.user_profile
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,710
xdiabetes/xproject_api
refs/heads/master
/xapp/api_v1/serializers/UserProfileSerializrs.py
from django.contrib.auth.models import User from django.core.validators import RegexValidator from django.db import transaction from django.db.models import Q from rest_framework import serializers from xapp.api_v1.consts import UserProfileConsts from xapp.models import UserProfile from django.utils.translation import gettext as _ class UserProfilePhoneVerificationSerializer(serializers.ModelSerializer): """ Used for verifying phone numbers """ phone_number = serializers.CharField(max_length=12) code = serializers.CharField(max_length=10, write_only=True) class Meta: model = UserProfile fields = [ 'code', 'pk', 'full_name', 'first_name', 'last_name', 'date_joined', 'email', 'phone_number', 'token' ] extra_kwargs = { 'full_name': {'read_only': True}, 'first_name': {'read_only': True}, 'last_name': {'read_only': True}, 'date_joined': {'read_only': True}, 'email': {'read_only': True}, } class UserProfileCRSerializer(serializers.ModelSerializer): """ Create a user profile password is by default not required you can enforce password by passing required_password = True to the serializer """ def __init__(self, *args, **kwargs): require_password = kwargs.pop('require_password', False) super(UserProfileCRSerializer, self).__init__(*args, **kwargs) if require_password: self.fields['password'].required = True password = serializers.CharField(max_length=255, required=False, write_only=True) class Meta: model = UserProfile fields = ['pk', 'full_name', 'first_name', 'last_name', 'email', 'phone_number', 'password'] def create(self, validated_data): with transaction.atomic(): # create a django user for internal usage django_user = User.objects.create_user(username=validated_data.get('phone_number'), password=validated_data.pop('password', None)) user_profile = UserProfile.objects.create(**validated_data, django_user=django_user) return user_profile class UserProfileUpdateSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['pk', 'full_name', 'first_name', 'last_name', 'active_address', 'phone_number', 'verification_status', 'get_verification_status_display'] extra_kwargs = { 'phone_number': {'read_only': True}, 'date_joined': {'read_only': True}, 'verification_status': {'read_only': True} } class UserProfileVerifySerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['pk', 'get_verification_status_display'] class UserProfileCafePrivateSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['pk', 'full_name', 'first_name', 'last_name', 'date_joined', 'email', 'phone_number'] class UserProfileSetPassword(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta: model = UserProfile fields = ['pk', 'password'] # todo: password validation def validate(self, attrs): if self.instance and not self.instance.django_user.has_usable_password(): return attrs raise serializers.ValidationError(_("Password already set")) def update(self, instance, validated_data): instance.django_user.set_password(validated_data.get('password')) instance.django_user.save() return instance class SendXprojectCodeSerializer(serializers.Serializer): """ Used to fetch phone number and send verification code to it if a user profile with the given phone number exists then only a verification code will be sent to it if not, one will be created """ phone_number = serializers.CharField(validators=[ RegexValidator( regex=r"^(\+98|0)?9\d{9}$", message=_("Enter a valid phone number"), code='invalid_phone_number' ), ])
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,711
xdiabetes/xproject_api
refs/heads/master
/xapp/api_v1/modules/payment/vandar.py
import json import math import requests from django.shortcuts import get_object_or_404 from django.urls import reverse from xproject.secret import VANDAR_API_KEY, DEMO from xapp.api_v1.consts import InvoiceConsts from xapp.api_v1.modules.payment.common import validate_invoice from xapp.models import Invoice def vandar_prepare_for_payment(invoice, request): """ :param invoice: invoice to be prepared for payment :param request: django http request object :return: on success: {'redirect_to': 'redirect_address', status: 200} on error : {'status': status_code, 'details': 'Error descriptions' } """ from xapp.api_v1.modules.payment.index import VANDAR # validate invoice if not validate_invoice(invoice): return {'status': 400, 'details': ["Invalid Invoice", ]} # generate callback url callback = request.build_absolute_uri( reverse("payment_verify", kwargs={ 'invoice_uuid': invoice.uuid, 'pg': VANDAR}) ) callback = callback.replace('http', 'https') if DEMO: callback = callback.replace('127.0.0.1:8000', 'xapp.app') result = requests.post( 'https://ipg.vandar.io/api/v3/send', data={ 'api_key': VANDAR_API_KEY, 'amount': math.ceil(invoice.amount) * 10, 'callback_url': callback } ) result_data = json.loads(result.text) if result_data['status'] != 1: return {'details': result_data['errors'], 'status': 503} # todo: change invoice status to in payment invoice.token = result_data['token'] invoice.save() return {'redirect_to': 'https://ipg.vandar.io/v3/%s' % result_data['token'], 'status': 200} def vandar_verify_payment(invoice): """Check payment verification""" result = requests.post( url="https://ipg.vandar.io/api/v3/verify", data={ "api_key": VANDAR_API_KEY, "token": invoice.token } ) result = json.loads(result.text) if result['status'] == 1: invoice.status = InvoiceConsts.PAYED invoice.transId = result['transId'] invoice.card_number = result['cardNumber'] else: invoice.status = InvoiceConsts.REJECTED invoice.save() if invoice.status == InvoiceConsts.PAYED: return True return False
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,712
xdiabetes/xproject_api
refs/heads/master
/xapp/api_v1/urls.py
from django.conf.urls import url from django.http import HttpResponse from django.urls import path from drf_yasg import openapi from drf_yasg.views import get_schema_view from rest_framework import permissions from xapp.api_v1.views.UserProfileViews import UserProfileRUView, UserProfileAuthTokenView, \ SendXprojectCode schema_view = get_schema_view( openapi.Info( title="CafePay API", default_version='development version', description="CafePay API Documentation\n@spsina\n@SadafAsad", contact=openapi.Contact(email="snparvizi75@gmail.com"), ), public=True, permission_classes=(permissions.AllowAny,), ) def error500(request): a = 1 / 0 return HttpResponse() urlpatterns = [ # user profile path('user-profile/', UserProfileRUView.as_view(), name="user_profile_ru"), path('user-profile/send-code/', SendXprojectCode.as_view(), name="user_profile_send_code"), path('user-profile/auth-token/', UserProfileAuthTokenView.as_view(), name="user_profile_auth_token"), path('error500/', error500), # docs url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ]
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,713
xdiabetes/xproject_api
refs/heads/master
/xapp/api_v1/modules/payment/pep.py
import datetime import json import math import requests from django.urls import reverse from django.utils import timezone from xproject.secret import DEMO, PEP_TERMINAL_CODE, PEP_MERCHANT_CODE, PEP_PRIVATE_KEY from xapp.api_v1.consts import InvoiceConsts from xapp.api_v1.helpers import kavenegar_send_sms, datetime_to_asia_tehran from xapp.api_v1.modules.payment.common import validate_invoice import base64 def pep_prepare_for_payment(invoice, request): """ :param invoice: invoice to be prepared for payment :param request: django http request object :return: on success: {'redirect_to': 'redirect_address', status: 200} on error : {'status': status_code, 'details': 'Error descriptions' } """ from xapp.api_v1.modules.payment.index import PEP # validate invoice if not validate_invoice(invoice): return {'status': 400, 'details': ["Invalid Invoice", ]} callback = request.build_absolute_uri( reverse("payment_verify", kwargs={ 'invoice_uuid': invoice.uuid, 'pg': PEP}) ) callback = callback.replace('http', 'https') # set payment timestamp invoice.last_payment_timestamp = datetime.datetime.now() invoice.save() if invoice.fee_payer: # the cafe pays the fee, so don't add it on amount amount = invoice.amount * 10 cafe_amount = math.floor(amount * (1 - invoice.xproject_fee)) else: amount = (invoice.amount * 10) + invoice.amount * 10 * invoice.xproject_fee cafe_amount = math.floor(invoice.amount * 10) # add delivery fee to cafe_amount cafe_amount += invoice.delivery_fee amount += invoice.delivery_fee clear_date = datetime_to_asia_tehran(timezone.now()).date() + datetime.timedelta(days=1) subpayment_data = """ <?xml version="1.0" encoding="utf-8"?> <SubPaymentList> <SubPayments> <SubPayment> <SubPayID>1</SubPayID> <Amount>%d</Amount> <Date>%s</Date> <Account>%s</Account> <Description></Description> </SubPayment> </SubPayments> </SubPaymentList> """ % (cafe_amount, str(clear_date), invoice.sub_payment_target_sheba) subpayment_data = subpayment_data.strip() encoded_subpayment = base64.b64encode(subpayment_data.encode('utf-8')) sending_data = { 'invoiceNumber': invoice.pk, 'invoiceDate': invoice.create_datetime.strftime("%Y/%m/%d %H:%M:%S"), 'amount': amount, 'terminalCode': PEP_TERMINAL_CODE, 'merchantCode': PEP_MERCHANT_CODE, 'redirectAddress': callback, 'timeStamp': invoice.last_payment_timestamp.strftime("%Y/%m/%d %H:%M:%S"), 'action': 1003, } if hasattr(invoice.wallet, 'user_profile'): sending_data['Mobile'] = invoice.wallet.user_profile.phone_number if invoice.auto_clear and invoice.sub_payment_target_sheba: sending_data['SubPaymentList'] = encoded_subpayment.decode('utf-8') sending_data_json = json.dumps(sending_data) headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'Pk': PEP_PRIVATE_KEY.strip() } signed_data = requests.post('https://pep.shaparak.ir/Api/v1/Payment/GetSign', headers=headers, data=sending_data_json) signed_data_dict = json.loads(signed_data.text) if not signed_data_dict.get('IsSuccess'): return {'details': signed_data_dict.get('Message', "خطا در پردازش تراکنش"), 'status': 503} sign = signed_data_dict.get('Sign') headers = { 'Content-Type': 'Application/json', 'Sign': sign } payment_token_data = requests.post("https://pep.shaparak.ir/Api/v1/Payment/GetToken", headers=headers, data=sending_data_json) payment_token_data_dict = json.loads(payment_token_data.text) if not payment_token_data_dict.get('IsSuccess'): return {'details': payment_token_data_dict.get('Message', "خطا در پردازش تراکنش"), 'status': 503} return {'redirect_to': "https://pep.shaparak.ir/payment.aspx?n=%s" % payment_token_data_dict.get('Token'), 'status': 200} def pep_refund_payment(invoice): refund_endpoint = "https://pep.shaparak.ir/Api/v1/Payment/RefundPayment" headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'Pk': PEP_PRIVATE_KEY } invoice.refund_attempt_timestamp = datetime.datetime.now() invoice.save() sending_data = { 'invoiceNumber': invoice.pk, 'invoiceDate': invoice.create_datetime.strftime("%Y/%m/%d %H:%M:%S"), 'terminalCode': PEP_TERMINAL_CODE, 'merchantCode': PEP_MERCHANT_CODE, 'timeStamp': invoice.refund_attempt_timestamp.strftime("%Y/%m/%d %H:%M:%S"), } sending_data_json = json.dumps(sending_data) signed_data = requests.post('https://pep.shaparak.ir/Api/v1/Payment/GetSign', headers=headers, data=sending_data_json) signed_data_dict = json.loads(signed_data.text) if not signed_data_dict.get('IsSuccess'): kavenegar_send_sms("refundException", {'token': signed_data_dict.get('Message', "خطا در پردازش تراکنش").replace(" ", "")}, "09017938091") kavenegar_send_sms("refundException", {'token': signed_data_dict.get('Message', "خطا در پردازش تراکنش").replace(" ", "")}, "09171164364") return False sign = signed_data_dict.get('Sign') headers = { 'Content-Type': 'Application/json', 'Sign': sign } refund_request = requests.post(refund_endpoint, headers=headers, data=sending_data_json) refund_dict = json.loads(refund_request.text) if not refund_dict.get('IsSuccess'): kavenegar_send_sms("refundException", {'token': signed_data_dict.get('Message', "خطا در پردازش تراکنش").replace(" ", "")}, "09017938091") kavenegar_send_sms("refundException", {'token': signed_data_dict.get('Message', "خطا در پردازش تراکنش").replace(" ", "")}, "09171164364") return False return True def pep_verify_payment(invoice): """Check payment verification""" invoice_verification_data_headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'Pk': PEP_PRIVATE_KEY } if invoice.fee_payer: # the cafe pays the fee, so don't add it on amount amount = invoice.amount * 10 else: # the payer should pay the fee amount = (invoice.amount * 10) + invoice.amount * 10 * invoice.xproject_fee amount += invoice.delivery_fee invoice_verification_data = { "InvoiceNumber": invoice.pk, 'invoiceDate': invoice.create_datetime.strftime("%Y/%m/%d %H:%M:%S"), "TerminalCode": PEP_TERMINAL_CODE, "MerchantCode": PEP_MERCHANT_CODE, 'amount': amount, 'Timestamp': datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), } verification_data_json = json.dumps(invoice_verification_data) signed_data = requests.post('https://pep.shaparak.ir/Api/v1/Payment/GetSign', headers=invoice_verification_data_headers, data=verification_data_json) signed_data_dict = json.loads(signed_data.text) if not signed_data_dict.get('IsSuccess'): return False, "Could Not Sign Data" verification_headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Sign': signed_data_dict.get('Sign') } verification_data = requests.post('https://pep.shaparak.ir/Api/v1/Payment/VerifyPayment', headers=verification_headers, data=verification_data_json) verification_data_dict = json.loads(verification_data.text) message = verification_data_dict.get('Message', "") if verification_data_dict.get('IsSuccess'): invoice.status = InvoiceConsts.PAYED invoice.save() return verification_data_dict.get('IsSuccess'), message """ <?xml version="1.0" encoding="utf-8"?> <SubPaymentList> <SubPayments> <SubPayment> <SubPayID>1</SubPayID> <Amount>40000</Amount> <Date>2021/01/27</Date> <Account>IR840120010000005779297807</Account> <Description></Description> </SubPayment> </SubPayments> </SubPaymentList> """
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,714
xdiabetes/xproject_api
refs/heads/master
/xapp/api_v1/routing.py
# chat/routing.py from django.urls import path from xapp.api_v1.consumers import DispatchConsumer websocket_urlpatterns = [ path('ws/v1/', DispatchConsumer.DispatchConsumer), ]
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,715
xdiabetes/xproject_api
refs/heads/master
/xapp/api_v1/consumers/paths.py
from typing import List from .ConsumerView import path from .consumer_views import TableProductManageByToken, TableProductManageByPk, TableSimpleJoinByPkView, \ TableSimpleJoinView, TableAggregateData, CafeTablePrintersJob, TableStatusView, TableSimpleJoinByUUIDView paths = [ path('table/<table_token>/product/<product_id>/', TableProductManageByToken.as_view(), name="table-add/remove-product-by-token"), path('table/<table_id>/product/<product_id>/staff/', TableProductManageByPk.as_view(), name="table-add/remove-product-by-pk"), path('table/<table_token>/join/simple/by-token/', TableSimpleJoinView.as_view(), name="table-join-simple-by-token"), path('table/<table_id>/join/simple/by-id/', TableSimpleJoinByPkView.as_view(), name="table-join-simple-by-id"), path('table/<table_uuid>/join/simple/by-uuid/', TableSimpleJoinByUUIDView.as_view(), name="table-join-simple-by-uuid"), path('table/<table_id>/aggregate/', TableAggregateData.as_view(), name="table-aggregate"), path('cafe/<cafe_id>/printer/jobs/', CafeTablePrintersJob.as_view(), name="cafe-printer-jobs", ), path('cafe/<cafe_id>/tables/join/simple/<type>/', TableStatusView.as_view(), name="cafe-join-simple", ) ]
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,716
xdiabetes/xproject_api
refs/heads/master
/xapp/api_v1/consumers/consumer_views.py
from django.db import transaction from django.db.models import Q from django.utils.translation import gettext as _ from rest_framework import status from .ConsumerView import BaseConsumerView, Path, ConsumerRetrieveAPIView, ConsumerListAPIView from .ConsumerView import ConsumerResponse as Response from .ConsumerView import MethodPathEffect as _Af from .helpers import get_object_or_404 from ..helpers import get_table_by_token, APIBadRequest from ..permissions import IsLoggedIn, IsStaff from ..serializers.CafePrinterSerializer import PrintRawDataSerializer, CafePrinterJobsSerializer from ..serializers.JoinSerializers import JoinSimpleSerializer, JoinAggregateSerializer from ..serializers.TableSerializers import TableCRUDSerializer from ...models import Product, Table, TableToken, Cafe, TableJoin class TableProductManageByToken(BaseConsumerView): """ add/remove product by table token POST to add product to table DELETE to remove product from table an active table token is required actions are done to the active bill of the table """ permission_classes = (IsLoggedIn,) def get_table(self): return get_table_by_token(token=self.kwargs.get('table_token'), user_profile=self.request.user.user_profile) def get_affected_method_paths(self): table_id = self.get_table().pk return [ _Af(Path.reverse(name="table-join-simple-by-token", kwargs={'table_token': self.kwargs.get('table_token')})), _Af(Path.reverse(name="table-join-simple-by-id", kwargs={'table_id': table_id})), _Af(Path.reverse(name="table-aggregate", kwargs={'table_id': table_id})), ] async def post(self, request, *args, **kwargs): """ Add product to table """ with transaction.atomic(): table = self.get_table() product = get_object_or_404(Product, pk=kwargs.get('product_id')) table.add_product(product, request.user.user_profile) return Response() async def delete(self, request, *args, **kwargs): with transaction.atomic(): table = self.get_table() product = get_object_or_404(Product, pk=kwargs.get('product_id')) table.remove_product(product, request.user.user_profile) return Response(status=status.HTTP_204_NO_CONTENT) class TableProductManageByPk(BaseConsumerView): """ add/remove product by table pk POST to add product to table DELETE to remove product from table actions are done to the active bill of the table required permission: is_staff """ permission_classes = (IsStaff,) def get_affected_method_paths(self): # todo: handle token not found exception filters = { 'table__id': self.kwargs.get('table_id'), 'status': TableToken.ACTIVE } if not TableToken.objects.filter().exists(): return [] token = TableToken.objects.get(**filters) # refactor artifact todo: clean up token = { 'token': token.token } return [ _Af(Path.reverse(name="table-join-simple-by-token", kwargs={'table_token': token['token']})), _Af(Path.reverse(name="table-join-simple-by-id", kwargs={'table_id': self.kwargs.get('table_id')})), _Af(Path.reverse(name="table-aggregate", kwargs={'table_id': self.kwargs.get('table_id')})) ] @staticmethod async def post(request, *args, **kwargs): """ Add product to table """ with transaction.atomic(): table = get_object_or_404(Table, pk=kwargs.get('table_id')) product = get_object_or_404(Product, pk=kwargs.get('product_id')) table.add_product(product, request.user.user_profile, True) return Response() @staticmethod async def delete(request, *args, **kwargs): with transaction.atomic(): table = get_object_or_404(Table, pk=kwargs.get('table_id')) product = get_object_or_404(Product, pk=kwargs.get('product_id')) table.remove_product(product, request.user.user_profile, True) return Response(status=status.HTTP_204_NO_CONTENT) class TableSimpleJoinByPkView(ConsumerRetrieveAPIView): """ simple join info of the given table required permission: IsStaff """ permission_classes = (IsLoggedIn,) serializer_class = JoinSimpleSerializer def get_object(self): table = get_object_or_404(Table, pk=self.kwargs.get('table_id')) active_join = table.active_join if not active_join: raise APIBadRequest(detail=_("No active join"), status_code=status.HTTP_404_NOT_FOUND) return active_join class TableSimpleJoinByUUIDView(ConsumerRetrieveAPIView): """ simple join info of the given table """ permission_classes = (IsLoggedIn,) serializer_class = JoinSimpleSerializer def get_object(self): table = get_object_or_404(Table, uuid=self.kwargs.get('table_uuid')) active_join = table.active_join if not active_join: raise APIBadRequest(detail=_("No active join"), status_code=status.HTTP_404_NOT_FOUND) return active_join class TableSimpleJoinView(ConsumerRetrieveAPIView): """ simple join info of the given table an active table token is required required permission: is_logged_in """ permission_classes = (IsLoggedIn,) serializer_class = JoinSimpleSerializer def get_serializer_context(self): return { 'request': self.request, 'view': self, 'has_my_payments': True, 'only_my_pbr': True } def get_object(self): # token and uuid is accepted try: table = TableToken.objects.get(token=self.kwargs.get('table_token'), status=TableToken.ACTIVE).table except TableToken.DoesNotExist: table = get_object_or_404(Table, uuid=self.kwargs.get('table_token')) active_join = table.active_join if not active_join: raise APIBadRequest(detail=_("No active join"), status_code=status.HTTP_404_NOT_FOUND) return active_join class TableAggregateData(ConsumerRetrieveAPIView): """ Aggregate info on a table required permission: IsStaff """ permission_classes = (IsStaff,) serializer_class = JoinAggregateSerializer def get_object(self): table = get_object_or_404(Table, pk=self.kwargs.get('table_id')) active_join = table.active_join if not active_join: raise APIBadRequest(detail=_("No active join"), status_code=status.HTTP_404_NOT_FOUND) return active_join class CafeTablePrintersJob(ConsumerListAPIView): """All cafe printers active jobs""" permission_classes = (IsStaff,) serializer_class = CafePrinterJobsSerializer def get_queryset(self): cafe = get_object_or_404(Cafe, pk=self.kwargs.get('cafe_id')) return cafe.printers.all() class TableStatusView(ConsumerListAPIView): """ join simple view of all the tables of the cafe required permissions: is_staff """ permission_classes = (IsStaff,) serializer_class = JoinSimpleSerializer def get_queryset(self): table_type = self.kwargs.get('type', TableToken.SELF_PICKUP) cafe = get_object_or_404(Cafe, pk=self.kwargs.get('cafe_id')) table_joins = cafe.joins.filter(~Q(bills__bill_pbrs=None), sent=False, force_close=False) if table_type != "any": return table_joins.filter(bills__table__table_type=table_type) return table_joins
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,717
xdiabetes/xproject_api
refs/heads/master
/xapp/migrations/0001_initial.py
# Generated by Django 2.2.4 on 2021-07-10 08:59 from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion import xapp.api_v1.helpers class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserProfile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(default='', max_length=255)), ('last_name', models.CharField(default='', max_length=255)), ('nick_name', models.CharField(default='', max_length=255)), ('phone_number', models.CharField(max_length=12, unique=True, validators=[django.core.validators.RegexValidator(code='invalid_phone_number', message='Enter a valid phone number', regex='^(\\+98|0)?9\\d{9}$')])), ('verification_status', models.CharField(choices=[('0', 'Pending'), ('1', 'Verified')], default='0', max_length=1)), ('django_user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='user_profile', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='UserProfilePhoneVerification', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('code', models.CharField(default=xapp.api_v1.helpers.generate_code, max_length=13)), ('create_date', models.DateTimeField(auto_now_add=True)), ('query_times', models.IntegerField(default=0)), ('used', models.BooleanField(default=False)), ('burnt', models.BooleanField(default=False)), ('user_profile', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='phone_numbers', to='xapp.UserProfile')), ], ), ]
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,718
xdiabetes/xproject_api
refs/heads/master
/xapp/api_v1/modules/payment/index.py
from xapp.api_v1.modules.payment.pep import pep_prepare_for_payment, pep_verify_payment, pep_refund_payment from xapp.api_v1.modules.payment.vandar import vandar_prepare_for_payment, vandar_verify_payment # payment gates VANDAR = 'VANDAR' PEP = 'PEP' PAYPING = 'PAYPING' LOCAL = 'LOCAL' pg_displays = { VANDAR: 'وندار', PEP: 'پاسارگاد', PAYPING: 'پی پینگ', LOCAL: 'LOCAL' } pg_gates = ((VANDAR, 'وندار'), (PEP, 'پاسارگاد'), (LOCAL, 'لوکال'), (PAYPING, 'پی پینگ')) pg_gates_array = [VANDAR, PEP, PAYPING, LOCAL] # payment gate prepare_for_payment and verify_payment functions pg_functions = { VANDAR: { 'prepare_for_payment': vandar_prepare_for_payment, 'verify_payment': vandar_verify_payment, 'refund_payment': None }, PEP: { 'prepare_for_payment': pep_prepare_for_payment, 'verify_payment': pep_verify_payment, 'refund_payment': pep_refund_payment } }
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,719
xdiabetes/xproject_api
refs/heads/master
/sms/migrations/0009_auto_20200305_1318.py
# Generated by Django 2.2.4 on 2020-03-05 13:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sms', '0008_auto_20200305_1317'), ] operations = [ migrations.AlterField( model_name='operator', name='api_key', field=models.CharField(blank=True, help_text='API key given by operator', max_length=255, null=True, verbose_name='API Key'), ), migrations.AlterField( model_name='operator', name='template', field=models.CharField(blank=True, help_text='template given by operator', max_length=255, null=True, verbose_name='Template'), ), ]
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,720
xdiabetes/xproject_api
refs/heads/master
/sms/migrations/0010_auto_20200305_1325.py
# Generated by Django 2.2.4 on 2020-03-05 13:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sms', '0009_auto_20200305_1318'), ] operations = [ migrations.AlterField( model_name='message', name='block_code', field=models.CharField(blank=True, help_text='Block Code', max_length=20, null=True, verbose_name='Block Code'), ), ]
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,721
xdiabetes/xproject_api
refs/heads/master
/sms/migrations/0008_auto_20200305_1317.py
# Generated by Django 2.2.4 on 2020-03-05 13:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sms', '0007_auto_20191010_1300'), ] operations = [ migrations.AddField( model_name='operator', name='api_key', field=models.CharField(blank=True, help_text='API key given by operator', max_length=255, null=True, verbose_name='Token'), ), migrations.AddField( model_name='operator', name='template', field=models.CharField(blank=True, help_text='template given by operator', max_length=255, null=True, verbose_name='Token'), ), migrations.AddField( model_name='operator', name='vendor', field=models.CharField(choices=[('0', 'Faraz SMS'), ('1', 'Kavenegar')], default='0', max_length=1), preserve_default=False, ), migrations.AlterField( model_name='operator', name='password', field=models.CharField(blank=True, help_text='Password given by operator', max_length=255, null=True, verbose_name='Password'), ), migrations.AlterField( model_name='operator', name='sender', field=models.CharField(blank=True, help_text='The operator phone number', max_length=15, null=True, verbose_name='Sender Phone Number'), ), migrations.AlterField( model_name='operator', name='username', field=models.CharField(blank=True, help_text='User name given by operator', max_length=255, null=True, verbose_name='Username'), ), ]
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,722
xdiabetes/xproject_api
refs/heads/master
/xapp/models.py
from django.contrib.auth.models import User from django.core.validators import RegexValidator from django.db import models, transaction from django.db.models.signals import post_save from django.dispatch import receiver from django.utils import timezone from django.utils.translation import gettext as _ from rest_framework.authtoken.models import Token from xapp.api_v1.consts import (UserProfileConsts) from xapp.api_v1.helpers import generate_code, send_verification_code class UserProfile(models.Model): """ User Profile object, one to one with django user additional info about the user """ django_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_profile") first_name = models.CharField(max_length=255, default="") last_name = models.CharField(max_length=255, default="") nick_name = models.CharField(max_length=255, default="") phone_number = models.CharField(max_length=12, validators=[ RegexValidator( regex=r"^(\+98|0)?9\d{9}$", message=_("Enter a valid phone number"), code='invalid_phone_number' ), ], unique=True) email = models.EmailField(max_length=255, blank=True, null=True) verification_status = models.CharField(max_length=1, choices=UserProfileConsts.states, default=UserProfileConsts.PENDING) @property def base_addresses(self): return self.addresses.filter(is_clone=False) @property def balance(self) -> int: return self.wallet.balance @property def has_usable_password(self): return self.django_user.has_usable_password() @property def token(self): token, created = Token.objects.get_or_create(user=self.django_user) return token.key @property def full_name(self): return self.first_name + " " + self.last_name @property def date_joined(self): return self.django_user.date_joined @property def cafe_relations_no_sms(self): return self.cafe_relations.exclude(role__code_name="PAYMENT_NOTIFY") def __str__(self): return "%s (%s)" % (self.django_user.username, self.full_name) class UserProfilePhoneVerificationObjectManager(models.Manager): def create(self, **kwargs): created = False with transaction.atomic(): user_profile = kwargs.get('user_profile') # lock the user profile to prevent concurrent creations user_profile = UserProfile.objects.select_for_update().get(pk=user_profile.pk) time = timezone.now() - timezone.timedelta(minutes=UserProfilePhoneVerification.RETRY_TIME) # select the latest valid user profile phone verification object user_profile_phone = UserProfilePhoneVerification.objects.order_by('-create_date'). \ filter(create_date__gte=time, user_profile__phone_number=user_profile.phone_number) \ .last() # create a new object if none exists if not user_profile_phone: obj = UserProfilePhoneVerification(**kwargs) obj.save() created = True if created: return {'status': 201, 'obj': obj} return { 'status': 403, 'wait': timezone.timedelta(minutes=UserProfilePhoneVerification.RETRY_TIME) + (user_profile_phone.create_date - timezone.now())} class UserProfilePhoneVerification(models.Model): """ Used for phone verification by sms auto generates a 5 digit code limits select querying time intervals between consecutive creation """ RETRY_TIME = 0 MAX_QUERY = 5 user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="phone_numbers") code = models.CharField(max_length=13, default=generate_code) create_date = models.DateTimeField(auto_now_add=True) query_times = models.IntegerField(default=0) used = models.BooleanField(default=False) burnt = models.BooleanField(default=False) objects = UserProfilePhoneVerificationObjectManager() @receiver(post_save, sender=UserProfilePhoneVerification) def send_verification_sms(sender, instance, created, **kwargs): """ send the verification code if a new object is created """ if created: send_verification_code(instance.user_profile.phone_number, instance.code)
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,723
xdiabetes/xproject_api
refs/heads/master
/xapp/api_v1/helpers.py
import asyncio import calendar import datetime import json import random import jdatetime import pytz import requests from asgiref.sync import async_to_sync from django.db.models import F, Count from django.db.models.aggregates import Sum from django.shortcuts import get_object_or_404 from django.utils.translation import ugettext as _ from drf_yasg import openapi from furl import furl from persiantools.jdatetime import JalaliDateTime from rest_framework import serializers from rest_framework.exceptions import APIException from rest_framework.generics import ListAPIView, RetrieveAPIView from rest_framework.response import Response from xproject import settings from xproject.secret import DEMO from sms.models import Operator, Message from pydoc import locate from django.db.models import Sum class SumDistinctHACK(Sum): allow_distinct = True def locate_from_api_v1_serializers(path): _from = "%s.%s" % ("xapp.api_v1.serializers", path) c = locate(_from) return c def generate_code(): return str(random.randint(10000, 99999)) def generate_table_token(): return str(random.randint(100000000000, 999999999999)) def get_verification_text(code): return _("به کافه پی خوش آمدید: %s" % code) def send_verification_code(to, code): message = Message.objects.create(to=to, message=str(code)) if DEMO: # Don't send actual sms if running on debug mode return return Operator.objects.get(vendor=Operator.KAVENEGAR).send_message(message) def get_cafe_simple_json(cafe): return {'pk': cafe.pk, 'name': cafe.name} class OverallRatingField(serializers.JSONField): class Meta: swagger_schema_fields = { "type": openapi.TYPE_OBJECT, "title": "Overall Rating Field", "properties": { "rate": openapi.Schema( title="Overall rating", type=openapi.FORMAT_FLOAT, ), "count": openapi.Schema( title="Count", type=openapi.TYPE_INTEGER, ), }, } class PaymentInfoField(serializers.JSONField): class Meta: swagger_schema_fields = { "type": openapi.TYPE_OBJECT, "title": "Payment Info field", "properties": { "total_count": openapi.Schema( title="Total count", type=openapi.FORMAT_FLOAT, ), "total_amount": openapi.Schema( title="Total amount", type=openapi.FORMAT_FLOAT, ), "payed_amount": openapi.Schema( title="Payed Amount", type=openapi.TYPE_INTEGER, ), "refund_amount": openapi.Schema( title="Refund Amount", type=openapi.TYPE_INTEGER, ), "net_amount": openapi.Schema( title="Net Amount", type=openapi.TYPE_INTEGER, ), }, } # small helper serializer def get_payment_info(pbrs, only_invoices=False): """ :param pbrs: array of product bill relation objects to calculate payment info :return: aggregated payment info """ if not pbrs: return { 'total_count': 0, 'total_amount': 0, 'payed_amount_pos': 0, 'payed_amount_cash': 0, 'payed_amount_online': 0, 'refund_amount': 0, 'net_payed_amount': 0, 'net_amount': 0, } from xapp.api_v1.consts import InvoiceConsts from xapp.models import Invoice total_count = pbrs.aggregate(total_count=Sum('count')) total_amount = pbrs.aggregate(total_amount=Sum(F('count') * F('original_price') * (100 - F('discount')) / 100)) payed_invoices = Invoice.objects.filter(tag=InvoiceConsts.PAYED_FOR_PRODUCT, type=InvoiceConsts.DEPOSIT, status__in=[InvoiceConsts.INTERNAL, InvoiceConsts.PAYED], pbr__in=pbrs) payed_invoices_pos = payed_invoices.filter(method=InvoiceConsts.POS) payed_invoices_cash = payed_invoices.filter(method=InvoiceConsts.CASH) payed_invoices_online = payed_invoices.filter(method=InvoiceConsts.ONLINE) agg_payed = payed_invoices.aggregate(payed_amount=Sum('amount')) agg_payed_pos = payed_invoices_pos.aggregate(payed_amount=Sum('amount')) agg_payed_cash = payed_invoices_cash.aggregate(payed_amount=Sum('amount')) agg_payed_online = payed_invoices_online.aggregate(payed_amount=Sum('amount')) refund_invoices = Invoice.objects.filter(tag=InvoiceConsts.REFUND, type=InvoiceConsts.WITHDRAW, pbr__in=pbrs) agg_refund = refund_invoices.aggregate(refund_amount=Sum('amount')) if only_invoices: return { 'payed_invoices': payed_invoices, 'refund_invoices': refund_invoices } clean_null_values(agg_payed) clean_null_values(agg_payed_pos) clean_null_values(agg_payed_cash) clean_null_values(agg_payed_online) clean_null_values(agg_refund) clean_null_values(total_amount) clean_null_values(total_count) total_amount = total_amount['total_amount'] return { 'total_count': total_count['total_count'], 'total_amount': total_amount, 'payed_amount': agg_payed['payed_amount'], 'payed_amount_pos': agg_payed_pos['payed_amount'], 'payed_amount_cash': agg_payed_cash['payed_amount'], 'payed_amount_online': agg_payed_online['payed_amount'], 'refund_amount': agg_refund['refund_amount'], 'net_payed_amount': agg_payed['payed_amount'] - agg_refund['refund_amount'], 'net_amount': (total_amount - agg_payed['payed_amount'] + agg_refund['refund_amount']) } def get_user_profile_basic_info_serializer(phone=False): from xapp.models import UserProfile class Serializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['pk', 'full_name', 'email', 'first_name', 'last_name', 'phone_number'] class SerializerPhone(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['pk', 'full_name', 'email', 'phone_number', 'first_name', 'last_name', ] if not phone: return Serializer return SerializerPhone def get_cafe_info_serializer(simple=False): from xapp.models import Cafe from xapp.api_v1.serializers.AddressSerializers import CafeRegionDetailedSerializer class Serializer(serializers.ModelSerializer): if not simple: overall_rating = OverallRatingField(read_only=True) delivery_regions = CafeRegionDetailedSerializer(many=True) avatar = serializers.ImageField() class Meta: model = Cafe if not simple: fields = ['pk', 'overall_rating', 'has_delivery', 'delivery_regions', 'name', 'is_open', 'payment_only', 'avatar', 'payment_first', 'phone', 'xproject_fee'] else: fields = ['pk', 'name', 'xproject_fee', 'avatar', 'phone', 'has_delivery', 'payment_first', 'payment_only'] return Serializer def get_basic_menu_serializer(): from xapp.models import Menu class Serializer(serializers.ModelSerializer): class Meta: model = Menu fields = ['pk', 'name', 'staff', 'is_active'] return Serializer def get_product_basic_info_serializer(): from xapp.models import Product class _Serializer(serializers.ModelSerializer): class Meta: model = Product fields = ['pk', 'name', 'order'] ref_name = "pbis" return _Serializer def get_basic_char_field_serializer(): from xapp.models import CharacterField class Serializer(serializers.ModelSerializer): class Meta: model = CharacterField fields = ['pk', 'title', 'cafe', 'is_delete', 'menu', 'staff', 'type'] return Serializer def get_table_simple_serializer(): from xapp.models import Table class Serializer(serializers.ModelSerializer): class Meta: model = Table fields = ['pk', 'number', 'is_preorder'] return Serializer def get_table_by_token(token, user_profile): from xapp.models import TableToken table = get_object_or_404(TableToken, token=token, status=TableToken.ACTIVE).table return table class APIBadRequest(APIException): status_code = 400 def __init__(self, *args, **kwargs): self.status_code = kwargs.pop('status_code', 400) super(APIBadRequest, self).__init__(*args, **kwargs) JOIN = '0' TRANSFER = '2' def validate_table_operation(t1, t2, op): if t1 == t2: raise APIBadRequest(detail=_("Same table operations not valid")) if t1.cafe != t2.cafe: raise APIBadRequest(detail=_("Cafe mismatch")) if not t1.active_join and not t2.active_join: raise APIBadRequest(detail=_("Empty tables operation not valid")) if op == TRANSFER: if not t1.active_join: raise APIBadRequest(detail=_("Cannot transfer empty table")) def clean_null_values(aggregated_queryset): for key in aggregated_queryset.keys(): if aggregated_queryset[key] is None: aggregated_queryset[key] = 0 def _thread_notifier(table): from xapp.api_v1.consumers.DispatchConsumer import DispatchConsumer from xapp.models import TableToken # todo: send to all joins # ----------------- socket notifications notify_watcher = async_to_sync(DispatchConsumer.notify_watcher_endpoint) _table_token = table.table_tokens.filter(status=TableToken.ACTIVE).first() _table_uuid = table.uuid notify_watcher( 'table/%d/join/simple/by-id/' % table.pk ) notify_watcher( 'table/%d/aggregate/' % table.pk ) notify_watcher( 'cafe/%d/tables/join/simple/%s/' % (table.cafe.pk, TableToken.SELF_PICKUP) ) notify_watcher( 'cafe/%d/tables/join/simple/%s/' % (table.cafe.pk, TableToken.PAYMENT_ONLY) ) notify_watcher( 'cafe/%d/tables/join/simple/any/' % table.cafe.pk ) if _table_token: notify_watcher( 'table/%s/join/simple/by-token/' % _table_token.token) if _table_uuid: notify_watcher( 'table/%s/join/simple/by-token/' % _table_uuid) def _desktop_notification_thread(table): if table.is_preorder: print("before preorder check passed") cafe = table.cafe push_endpoints = cafe.push_endpoints.all() print("still here") push_requests = [] payload = { 'title': 'پیش سفارش | کافه پی', 'body': 'پیش سفارش جدید برای شما ثبت شده است', 'url': 'https://admin.xproject.app' } payload_text = json.dumps(payload) for push_endpoint in push_endpoints: push_requests.append({ 'text': payload_text, 'keys': push_endpoint.keys, 'subscription': push_endpoint.text }) data = { 'data': push_requests } print("before api call") print("request data") print(json.dumps(data)) print("sending request") result = requests.post("http://cfpyqr.info:5000/api/vapid-data", json=data, verify=False) print("status report") print(result.status_code) print(result.text) def _printer_thread_notifier(printer): from xapp.api_v1.consumers.DispatchConsumer import DispatchConsumer notify_watcher = async_to_sync(DispatchConsumer.notify_watcher_endpoint) notify_watcher( 'cafe/%d/printer/jobs/' % printer.cafe.pk ) def notify_watchers(table): import threading thread1 = threading.Thread(target=_thread_notifier, args=(table,)) thread1.start() def notify_printers(printer): import threading thread1 = threading.Thread(target=_printer_thread_notifier, args=(printer,)) thread1.start() def convert_jalali_to_gregorian(date, _time): """ :param date: date - either str or date object (str objects must be validated before passing to this function) :param _time: time - either str or time object (str objects must be validated before passing to this function) :return: converted and merged datetime object """ if type(date) == str: date_data = date.split('-') else: date_data = str(date).split('-') if type(_time) == str: time_data = _time.split(':') else: time_data = str(_time).split(':') datetime_data = date_data + time_data datetime_data = [int(dt) for dt in datetime_data] nytz = pytz.timezone('Asia/Tehran') return datetime.datetime.fromtimestamp( calendar.timegm(nytz.localize(jdatetime.datetime(*datetime_data).togregorian()).utctimetuple()), tz=pytz.timezone("utc")) def super_advanced_datetime_filter(queryset, datetime_field, start_date, start_time, end_date, end_time): """ :param queryset: :param datetime_field: :param start_date: :param start_time: :param end_date: :param end_time: :return: filter a queryset across a date and time frame """ # Scenario 1: start time < end time, perform a regular datetime filter if start_time <= end_time: return queryset.filter(**{ "%s__date__gte" % datetime_field: start_date, "%s__date__lte" % datetime_field: end_date, "%s__time__gte" % datetime_field: start_time, "%s__time__lte" % datetime_field: end_time, }) elif end_time < start_time: """ converted time is like: from 01:00 until 11:00 q1: *********************************** * ---- ---- ---- ---- ---- * 00:00 * | | | | | | | | | | * * | | | | | | | | | | * * ---- ---- ---- ---- ---- * 21:30 *********************************** q2: ********************************** * ---- ---- ---- ---- ---- * 07:30 * | | | | | | | | | | * * | | | | | | | | | | * * ---- ---- ---- ---- ---- * 00:00 ********************************** """ q1 = queryset.filter(**{ "%s__date__gte" % datetime_field: start_date, "%s__date__lt" % datetime_field: end_date, "%s__time__gte" % datetime_field: start_time }) q2 = queryset.filter(**{ "%s__date__gt" % datetime_field: start_date, "%s__date__lte" % datetime_field: end_date, "%s__time__lte" % datetime_field: end_time }) return (q1 | q2).distinct() else: raise Exception("[ERROR] CPU Malfunction") class AggregatedListAPIView(ListAPIView): """ ListAPIView with aggregated data on the filtered queryset also supports total queryset aggregation when pagination is used """ def get_extra_and_paginated_response(self, page, extra): """ :param page: page of data :param extra: a dictionary containing extra fields to be included in the final response :return: paginated and extra response """ serializer = self.get_serializer(page, many=True) if page is not None: response = self.get_paginated_response(serializer.data) else: response = serializer.data for key in extra.keys(): response.data[key] = extra.get(key, None) return response def get_aggregated_data(self, queryset): """ return a dictionary containing aggregated data of the given queryset """ return {} def list(self, request, *args, **kwargs): """ filter the given queryset generate some aggregate data return paginated data """ queryset = self.filter_queryset(self.get_queryset()) aggregated_data = self.get_aggregated_data(queryset=queryset) page = self.paginate_queryset(queryset) return self.get_extra_and_paginated_response(page, aggregated_data) class ManagerialReport(RetrieveAPIView): """ start datetime end datetime aggregation step **Managerial reports depend on a specific cafe therefore get_object must return the desired cafe that the reports may be generated for """ class DateTimeException(Exception): pass def get_raw_report_params(self): """ :return: { 'start_datetime', 'end_datetime', 'step': 24 (this is default value), } """ return { 'start_datetime': self.request.query_params.get('start_datetime'), 'end_datetime': self.request.query_params.get('end_datetime'), 'step': self.request.query_params.get('step', 24) } def _validate_datetime(self, _datetime): """ Convert _datetime start to actual python datetime objects catch any possible TypeError and ValueError exceptions and raise them as DateTimeException """ try: return datetime.datetime.strptime(_datetime, "%Y-%m-%dT%H:%M") except (TypeError, ValueError) as e: if _datetime is None: raise self.DateTimeException("this field is required") else: raise self.DateTimeException(str(e)) def validated_report_params(self): """ :return: validate raw reports params and return validated data """ raw_report_params = self.get_raw_report_params() errors = [] # parse and validate start/end datetime s try: start_datetime = self._validate_datetime(raw_report_params.get('start_datetime')) except self.DateTimeException as e: errors.append({'start_datetime': [str(e), ]}) try: end_datetime = self._validate_datetime(raw_report_params.get('end_datetime')) except self.DateTimeException as e: errors.append({'end_datetime': [str(e), ]}) # validate step try: step = int(raw_report_params.get('step', 24)) if step % 24 != 0: raise ValueError(_("step must be a multiple of 24 hours")) step = datetime.timedelta(hours=step) except (TypeError, ValueError) as e: errors.append({'step': [str(e), ]}) # in report api's, start_datetime and end_datetime is required # and must be convertible to valid python datetime objects if not not errors: raise APIBadRequest(errors) # return the validate query_params data return { 'start_datetime': start_datetime, 'end_datetime': end_datetime, 'step': step } def get_framed_queryset(self, start_datetime, end_datetime): """ count of items in the queryset that satisfies the given time constraints""" raise NotImplemented(_("Get framed queryset must be implemented")) def get_total_queryset_items(self): """Total number of items in an unbound (time wise) filter""" raise NotImplemented(_("Get total queryset items must be implemented")) def get_total_framed_items(self): """Total number of items in bounded (time wise) filter""" report_params = self.validated_report_params() return self.get_framed_queryset(report_params.get('start_datetime'), report_params.get('end_datetime')) def retrieve(self, request, *args, **kwargs): validated_params = self.validated_report_params() # extract report params start_datetime = validated_params.get('start_datetime') end_datetime = validated_params.get('end_datetime') step = validated_params.get('step') # total number of items in the given time frame total_bounded = self.get_total_framed_items() # total number of items in each step of the filter _start_datetime = start_datetime # used inside the while loop that generates step by step aggregated reports step_results = [] # calculate report result from start to end, excluding the last step while _start_datetime + step < end_datetime: queryset = self.get_framed_queryset(_start_datetime, _start_datetime + step) step_results.append(queryset) # increment counter start_datetime _start_datetime = _start_datetime + step # calculate the last step last_step = self.get_framed_queryset(_start_datetime, end_datetime) step_results.append(last_step) return Response({'total': self.get_total_queryset_items(), 'total_bounded': total_bounded, 'reports': step_results}) def kavenegar_send_sms(template, tokens, to): from xproject import settings import requests api_endpoint = "https://api.kavenegar.com/v1/{API-KEY}/verify/lookup.json" api = furl(api_endpoint.replace('{API-KEY}', settings.KAVENEGAR_API_KEY)) api.args['receptor'] = to api.args['template'] = template for key in tokens.keys(): api.args[key] = tokens.get(key) print(api.url) requests.get(api.url) def datetime_to_local_str(date_time): asia_tehran = pytz.timezone('Asia/Tehran') local_now = date_time.astimezone(asia_tehran) return JalaliDateTime.to_jalali(local_now).strftime('%y/%m/%dساعت%H:%M:%S') def datetime_to_asia_tehran(date_time): asia_tehran = pytz.timezone('Asia/Tehran') return date_time.astimezone(asia_tehran)
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,724
xdiabetes/xproject_api
refs/heads/master
/xapp/api_v1/permissions.py
from rest_framework import permissions from django.shortcuts import get_object_or_404 from rest_framework.permissions import SAFE_METHODS from xapp.models import * from django.utils.translation import gettext as _ from xapp.api_v1.consts import CafeUserProfileRelationConsts ANY = "__ANY__" def is_authenticated(request): # check if is authenticated if not bool(request.user and request.user.is_authenticated): return False return True def has_perm_in_cafe(request, cafe, permission): if not is_authenticated(request): return False if request.user.is_superuser: return True try: cupr = CafeUserProfileRelation.objects.filter(role__cafe=cafe, user_profile=request.user.user_profile, status=CafeUserProfileRelationConsts.VERIFIED).first() if not cupr: raise CafeUserProfileRelation.DoesNotExist user = cupr.user_profile.django_user if not permission == ANY: return user.has_perm("%s" % permission) return True except (CafeUserProfileRelation.DoesNotExist, UserProfile.DoesNotExist) as e: # logged in user is not a staff in this cafe return False def get_free_is_auth_with_perm(request, cafe, permission): """ No effect on GET method check for is staff status and permission specified :param request: :param cafe: :param permission: :return: True or False """ if request.method == 'GET': return True return has_perm_in_cafe(request, cafe, permission) class IsStaff(permissions.BasePermission): """ Check if currently logged in user is a staff of the given cafe """ def has_permission(self, request, view): if view.kwargs.get('table_id'): cafe = get_object_or_404(Table, pk=view.kwargs.get('table_id')).cafe elif view.kwargs.get('table_token'): cafe = get_object_or_404(TableToken, token=view.kwargs.get('table_token')).table.cafe elif view.kwargs.get('category_id'): cafe = get_object_or_404(CharacterField, pk=view.kwargs.get('category_id')).cafe elif view.kwargs.get('cafe_id'): cafe = get_object_or_404(Cafe, pk=view.kwargs.get('cafe_id')) elif view.kwargs.get('pbr_id'): cafe = get_object_or_404(ProductBillRelation, pk=view.kwargs.get('pbr_id')).product.cafe elif view.kwargs.get('join_id'): cafe = get_object_or_404(TableJoin, pk=view.kwargs.get('join_id')).cafe elif view.kwargs.get('printer_id'): cafe = get_object_or_404(Printer, pk=view.kwargs.get('printer_id')).cafe elif view.kwargs.get('printer_job_id'): cafe = get_object_or_404(PrinterJob, pk=view.kwargs.get('printer_job_id')).printer.cafe elif view.kwargs.get('cafe_image_id'): cafe = get_object_or_404(Gallery, pk=view.kwargs.get('cafe_image_id')).cafe elif view.kwargs.get('region_price_id'): cafe = get_object_or_404(CafeRegionPrice, pk=view.kwargs.get('region_price_id')).cafe return has_perm_in_cafe(request, cafe, ANY) class IsStaffOrCustomer(permissions.BasePermission): def has_object_permission(self, request, view, obj) -> bool: return IsStaff().has_permission(request, view) or IsCustomer().has_object_permission(request, view, obj) class CanUpdatePBR(permissions.BasePermission): """ Check if currently logged in user is a staff of the given cafe """ def has_object_permission(self, request, view, obj) -> bool: cafe = get_object_or_404(ProductBillRelation, pk=view.kwargs.get('pbr_id')).product.cafe return has_perm_in_cafe(request, cafe, ANY) class IsCustomer(permissions.BasePermission): """ Check if currently logged in user is a customer on the given object """ def has_object_permission(self, request, view, join) -> bool: user_profile = request.user.user_profile customers = [] for bill in join.bills.all(): for pbr in bill.all_products: customers.append(pbr.user_profile) return user_profile in customers class IsLoggedIn(permissions.BasePermission): """ """ def has_permission(self, request, view): return is_authenticated(request) and hasattr(request.user, 'user_profile') class IsElevatedUser(permissions.BasePermission): """ Is superuser """ def has_permission(self, request, view): if is_authenticated(request) and hasattr(request.user, 'user_profile'): return request.user.user_profile.is_elevated_user class IsLoggedInOrCanSeeCafeInfo(permissions.BasePermission): """ """ def has_permission(self, request, view): table_token = get_object_or_404(TableToken, token=view.kwargs.get('table_token')) if table_token.menu_only: return True return is_authenticated(request) class CanActivateTableToken(permissions.BasePermission): """ Permission to activate table token any staff is allowed """ def has_permission(self, request, view): table_token = get_object_or_404(TableToken, pk=view.kwargs.get('table_token_id')) cafe = table_token.table.cafe return has_perm_in_cafe(request, cafe, ANY) class CanManagePost(permissions.BasePermission): """ Permission to create | update | delete post No effect on get """ message = _("You are not allowed to manage post") def has_permission(self, request, view): cafe = get_object_or_404(Post, pk=view.kwargs.get('post_id', None)).cafe return get_free_is_auth_with_perm(request, cafe, 'xapp.can_manage_post') class CanManageStaff(permissions.BasePermission): """ Permission to add or remove staff """ message = _("You must have can_manage_staff permission") def has_permission(self, request, view): obj = get_object_or_404(Cafe, pk=view.kwargs.get('cafe_id')) return has_perm_in_cafe(request, obj, 'xapp.can_manage_staff') class CanManageRole(permissions.BasePermission): """ Permission to create update delete role """ def has_permission(self, request, view): if view.kwargs.get('cafe_id'): cafe = get_object_or_404(Cafe, pk=view.kwargs.get('cafe_id')) elif request.data.get('cafe_id'): cafe = get_object_or_404(Cafe, pk=view.kwargs.get('cafe_id')) elif view.kwargs.get('role_id'): cafe = get_object_or_404(CafeUserProfileRelationRole, pk=view.kwargs.get('role_id')).cafe return has_perm_in_cafe(request, cafe, 'xapp.can_manage_role') class CanCreatePost(permissions.BasePermission): """ Permission to create | update | delete post No effect on get """ message = _("You are not allowed to manage post") def has_permission(self, request, view): cafe = get_object_or_404(Cafe, pk=view.kwargs.get('cafe_id')) return get_free_is_auth_with_perm(request, cafe, 'xapp.can_create_post') class CanManageComment(permissions.BasePermission): """ Who commented, can delete the comment """ message = _("You are not allowed to manage this comment") def has_permission(self, request, view): if not is_authenticated(request): return False comment = get_object_or_404(Comment, pk=view.kwargs.get('comment_id')) return comment.user == request.user.user_profile class CanManageProduct(permissions.BasePermission): """ no effect on get method checks for authentication, is cafe staff and CanManageProduct permission """ message = _("You are not allowed to manage this product") def has_object_permission(self, request, view, obj): if type(obj) == ProductImage: cafe = obj.product.cafe elif type(obj) == Product: cafe = obj.cafe return get_free_is_auth_with_perm(request, cafe, 'xapp.can_manage_product') class CanProductBeViewed(permissions.BasePermission): """ check if cafe has permitted to show menu items or not if the requested user is a staff. permission is granted """ message = _("You are not allowed to view this product") def has_permission(self, request, view): product = get_object_or_404(Product, pk=view.kwargs.get('product_id')) if product.cafe.menu_items_on: return True if not is_authenticated(request): return False # check staff status return has_perm_in_cafe(request, product.cafe, ANY) class CanProductsBeViewed(permissions.BasePermission): """ check if cafe has permitted to show menu items or not if the requested user is a staff. permission is granted """ message = _("You are not allowed to view product list of this cafe") def has_permission(self, request, view): cafe_pk = view.kwargs.get('cafe_id') menu_pk = view.kwargs.get('menu_id') category_pk = view.kwargs.get('category_id') if cafe_pk is not None: """ Products are either being requested from list cafe products endpoint or from retrieve menu endpoint """ cafe = get_object_or_404(Cafe, pk=cafe_pk) elif menu_pk is not None: cafe = get_object_or_404(Menu, pk=menu_pk).cafe elif category_pk is not None: cafe = get_object_or_404(CharacterField, pk=category_pk).cafe if cafe.menu_items_on: return True if not is_authenticated(request): return False return has_perm_in_cafe(request, cafe, ANY) class CanCreateProduct(permissions.BasePermission): """ no effect on get method check for staff status and permission for product creation """ message = _("You are not allowed to create products for this cafe") def has_permission(self, request, view): cafe = get_object_or_404(Cafe, pk=view.kwargs.get('cafe_id')) return get_free_is_auth_with_perm(request, cafe, 'xapp.can_create_product') class CanCreateMenu(permissions.BasePermission): """ no effect on GET request check for staff status and can create menu permission """ message = _("You are not allowed to create menus for this cafe") def has_permission(self, request, view): cafe = Cafe.objects.get(pk=view.kwargs.get('cafe_id')) return get_free_is_auth_with_perm(request, cafe, 'xapp.can_create_menu') class CanManageMenu(permissions.BasePermission): """ no effect on GET method is staff and can manage menu required """ def has_object_permission(self, request, view, obj): return get_free_is_auth_with_perm(request, obj.cafe, 'xapp.can_manage_menu') class CanCreateListCategory(permissions.BasePermission): """ No effect on GET method staff users with can_create_list_category are granted permission """ def has_permission(self, request, view): cafe = get_object_or_404(Cafe, pk=view.kwargs.get('cafe_id')) return get_free_is_auth_with_perm(request, cafe, "xapp.can_create_list_category") class CanCreateListGroup(permissions.BasePermission): """ No effect on GET method staff users with can_create_list_group are granted permission """ def has_permission(self, request, view): cafe = get_object_or_404(Cafe, pk=view.kwargs.get('cafe_id')) return get_free_is_auth_with_perm(request, cafe, "xapp.can_create_list_group") class CanManageCategory(permissions.BasePermission): """ No effect on GET method staff users with can_manage_category are granted permission """ def has_object_permission(self, request, view, obj): cafe = obj.cafe return get_free_is_auth_with_perm(request, cafe, 'xapp.can_manage_category') class CanManageGroup(permissions.BasePermission): """ No effect on GET method staff users with can_manage_group are granted permission """ def has_object_permission(self, request, view, obj): cafe = obj.cafe return get_free_is_auth_with_perm(request, cafe, 'xapp.can_manage_group') class CanUpdateCafe(permissions.BasePermission): """ no effect on GET can update cafe permission required """ def has_object_permission(self, request, view, obj): return has_perm_in_cafe(request, obj, 'xapp.can_manage_cafe') class CanCreateTable(permissions.BasePermission): """ can create table """ def has_permission(self, request, view): cafe = get_object_or_404(Cafe, pk=view.kwargs.get('cafe_id')) return has_perm_in_cafe(request, cafe, 'xapp.can_create_table') class CanManageTable(permissions.BasePermission): """ no effect on GET request """ def has_obj_permission(self, request, view, obj): cafe = obj.cafe return get_free_is_auth_with_perm(request, cafe, 'xapp.can_manage_table') class CanManageTableProduct(permissions.BasePermission): """ check if product exists on the table or not checks happen on DELETE method """ def has_permission(self, request, view): table = get_object_or_404(Table, pk=view.kwargs.get('table_id')) product = get_object_or_404(Product, pk=view.kwargs.get('product_id')) if table.cafe == product.cafe: if request.method == 'DELETE': if table.active_bill and table.active_bill.has_product(product): return True return False return True return False class CanSeparateTable(permissions.BasePermission): """ check if more than one table remain in the join after separation """ def has_permission(self, request, view): table = get_object_or_404(Table, pk=view.kwargs.get('table_id')) if table.active_join: join = table.get_or_create_join return len(join.bills.all()) > 1 return False class CanJoinORTransferTables(permissions.BasePermission): """ Check if two tables are from the same cafe """ def has_permission(self, request, view): table_x = get_object_or_404(Table, pk=view.kwargs.get('table_x')) table_y = get_object_or_404(Table, pk=view.kwargs.get('table_y')) if table_x != table_y: return table_x.cafe == table_y.cafe return False
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,495,725
xdiabetes/xproject_api
refs/heads/master
/xapp/api_v1/consumers/BasicConsumer.py
import json from json import JSONDecodeError from channels.generic.websocket import AsyncWebsocketConsumer from django.utils.translation import gettext as _ from rest_framework.authtoken.models import Token from channels.db import database_sync_to_async from xapp.api_v1.consumers.ConsumerView import ConsumerResponse from xapp.api_v1.consumers.helpers import SocketException from rest_framework.renderers import JSONRenderer def dict_to_json(dict_data): try: return JSONRenderer().render(dict_data).decode("utf-8") except: print("-------------") print(dict_data) print("-------------") class BasicConsumer(AsyncWebsocketConsumer): async def authenticate(self, authorization_header): token = authorization_header.replace("Token ", "") try: token_obj = await self.db_get(Token, key=token) return token_obj.user except Token.DoesNotExist: await self.channel_400(_("Invalid Token")) raise SocketException(_("Invalid Token")) async def send_back_info(self, dict_info): # Send message to the active channel await self.send( dict_to_json({ 'type': 'info', 'message': dict_info }) ) async def channel_400(self, details): """ Raise socket exception and send back response to the channel :param details: :return: """ # Send message to the active channel await self.send_back_response(details, 400) raise SocketException(details) async def send_back_response(self, details, status_code): # Send message to the active channel await self.send( dict_to_json({ 'type': 'response', 'message': { 'status': status_code, 'data': details } }) ) async def view_response(self, response: ConsumerResponse, source=None): # Send message to the active channel await self.send(dict_to_json( { 'type': 'response', 'message': { 'source': source, 'status_code': response.status, 'data': response.data } } )) async def view_response_gp(self, response: ConsumerResponse, gp_name, source=None): # Send message to the active channel await self.channel_layer.group_send( gp_name, { 'type': 'response', 'message': { 'source': source, 'status_code': response.status, 'data': response.data } } ) async def get_request(self, text_data): """ Extract request text_data and make request object :param text_data: :return: """ try: text_data_json = json.loads(text_data) request = text_data_json.get('request', {}) # request object check if not request.get('endpoint'): await self.channel_400(_("'endpoint' must be specified")) if 'data' not in request.keys(): await self.channel_400(_("'data' must be specified")) if 'headers' not in request.keys(): await self.channel_400(_("'headers' must be specified")) if not request.get('method'): await self.channel_400(_("'method' must be specified")) return request except JSONDecodeError as e: await self.channel_400(str(e)) async def info(self, event): message = event.get('message', {}) response = {'message': message} text_data = dict_to_json(response) await self.send(text_data=text_data) async def response(self, event): message = event.get('message', {}) response = {'message': message} text_data = dict_to_json(response) await self.send(text_data=text_data) @database_sync_to_async def db_get(self, base_class, **kwargs): return base_class.objects.get(**kwargs)
{"/user_profile/models.py": ["/location/models.py", "/user_profile/helpers.py"], "/diabo/tests.py": ["/diabo/models.py", "/job/models.py", "/user_profile/serializers.py", "/user_profile/tests.py"], "/job/tests.py": ["/job/models.py", "/user_profile/tests.py"], "/diabo/views.py": ["/diabo/models.py", "/job/models.py", "/diabo/serializers.py", "/job/serializers.py", "/user_profile/permissions.py"], "/diabo/urls.py": ["/diabo/views.py"], "/walking_tracker/admin.py": ["/walking_tracker/models.py"], "/location/serializers.py": ["/location/models.py"], "/diabo/serializers.py": ["/diabo/models.py", "/job/serializers.py", "/user_profile/serializers.py"], "/user_profile/migrations/0001_initial.py": ["/user_profile/helpers.py"], "/user_profile/admin.py": ["/user_profile/models.py"], "/location/admin.py": ["/location/models.py"], "/diabo/models.py": ["/job/models.py", "/user_profile/models.py"], "/diabetes_therapy/helpers.py": ["/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py"], "/user_profile/tests.py": ["/location/models.py", "/user_profile/models.py"], "/diabetes_therapy/tests.py": ["/diabetes_therapy/models.py", "/user_profile/models.py", "/user_profile/tests.py"], "/user_profile/urls.py": ["/user_profile/views.py"], "/user_profile/views.py": ["/user_profile/models.py", "/user_profile/permissions.py", "/user_profile/serializers.py"], "/job/admin.py": ["/job/models.py"], "/diabetes_therapy/serializes.py": ["/diabetes_therapy/models.py"], "/diabetes_therapy/urls.py": ["/diabetes_therapy/views.py"], "/diabetes_therapy/views.py": ["/diabetes_therapy/helpers.py", "/diabetes_therapy/models.py", "/diabetes_therapy/serializes.py", "/user_profile/permissions.py"], "/user_profile/serializers.py": ["/location/serializers.py", "/user_profile/helpers.py", "/user_profile/models.py"], "/walking_tracker/models.py": ["/user_profile/models.py"], "/job/serializers.py": ["/job/models.py"], "/walking_tracker/serializers.py": ["/walking_tracker/models.py"], "/walking_tracker/views.py": ["/walking_tracker/models.py", "/walking_tracker/serializers.py"], "/location/views.py": ["/location/models.py", "/location/serializers.py"], "/diabetes_therapy/admin.py": ["/diabetes_therapy/models.py"], "/location/urls.py": ["/location/views.py"], "/location/tests.py": ["/location/models.py", "/location/serializers.py", "/user_profile/models.py"], "/walking_tracker/urls.py": ["/walking_tracker/views.py"], "/job/urls.py": ["/diabo/views.py"], "/xapp/api_v1/consumers/DispatchConsumer.py": ["/xapp/api_v1/consumers/BasicConsumer.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/paths.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/consumers/ConsumerView.py": ["/xapp/api_v1/consumers/helpers.py"], "/xapp/api_v1/modules/payment/common.py": ["/xapp/api_v1/consts.py"], "/xapp/api_v1/views/UserProfileViews.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/permissions.py", "/xapp/api_v1/serializers/UserProfileSerializrs.py", "/xapp/models.py"], "/xapp/api_v1/serializers/UserProfileSerializrs.py": ["/xapp/api_v1/consts.py", "/xapp/models.py"], "/xapp/api_v1/modules/payment/vandar.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/models.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/urls.py": ["/xapp/api_v1/views/UserProfileViews.py"], "/xapp/api_v1/modules/payment/pep.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/modules/payment/common.py", "/xapp/api_v1/modules/payment/index.py"], "/xapp/api_v1/consumers/paths.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/consumer_views.py"], "/xapp/api_v1/consumers/consumer_views.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py", "/xapp/api_v1/helpers.py", "/xapp/api_v1/permissions.py", "/xapp/models.py"], "/xapp/migrations/0001_initial.py": ["/xapp/api_v1/helpers.py"], "/xapp/api_v1/modules/payment/index.py": ["/xapp/api_v1/modules/payment/pep.py", "/xapp/api_v1/modules/payment/vandar.py"], "/xapp/models.py": ["/xapp/api_v1/consts.py", "/xapp/api_v1/helpers.py"], "/xapp/api_v1/helpers.py": ["/xapp/api_v1/consts.py", "/xapp/models.py", "/xapp/api_v1/consumers/DispatchConsumer.py"], "/xapp/api_v1/permissions.py": ["/xapp/models.py", "/xapp/api_v1/consts.py"], "/xapp/api_v1/consumers/BasicConsumer.py": ["/xapp/api_v1/consumers/ConsumerView.py", "/xapp/api_v1/consumers/helpers.py"]}
39,534,170
tegardp/Arsipku
refs/heads/master
/arsip/views.py
from django.shortcuts import render, redirect from django.views.generic import ListView, CreateView, UpdateView, DetailView, DeleteView from .models import * from django.urls import reverse_lazy from django import forms # Umum View class UmumList(ListView): model = Umum template_name = 'arsip/umum/umum_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['current_user'] = self.request.user return context class UmumCreate(CreateView): model = Umum fields = ['nama', 'keterangan', 'kategori', 'periode', 'upload'] template_name = 'arsip/umum/umum_form.html' success_url = reverse_lazy('umum_list') def form_valid(self, form): form.instance.author = self.request.user return super(UmumCreate, self).form_valid(form) def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['periode'].widget = forms.DateInput(attrs={'type':'date'}) return form class UmumDetail(DetailView): model = Umum template_name = 'arsip/umum/umum_detail.html' class UmumUpdate(UpdateView): model = Umum fields = ['nama', 'keterangan', 'kategori', 'periode', 'upload'] template_name = 'arsip/umum/umum_form.html' success_url = reverse_lazy('umum_list') class UmumDelete(DeleteView): model = Umum success_url = reverse_lazy('umum_list') def UmumApprove(request, pk): umum = Umum.objects.get(pk=pk) umum.approval = 1 umum.save() return redirect('umum_list') # SKPA View class SkpaList(ListView): model = Surat template_name = 'arsip/skpa/skpa_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['current_user'] = self.request.user return context class SkpaCreate(CreateView): model = Surat fields = ['nomor', 'perihal', 'tanggal_surat', 'upload'] template_name = 'arsip/skpa/skpa_form.html' success_url = reverse_lazy('skpa_list') def form_valid(self, form): form.instance.author = self.request.user return super(SkpaCreate, self).form_valid(form) def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['tanggal_surat'].widget = forms.DateInput(attrs={'type':'date'}) return form class SkpaDetail(DetailView): model = Surat template_name = 'arsip/skpa/skpa_detail.html' class SkpaUpdate(UpdateView): model = Surat fields = ['nomor', 'perihal', 'tanggal_surat', 'upload'] template_name = 'arsip/skpa/skpa_form.html' success_url = reverse_lazy('skpa_list') class SkpaDelete(DeleteView): model = Surat success_url = reverse_lazy('skpa_list') def SkpaApprove(request, pk): skpa = Surat.objects.get(pk=pk) skpa.approval = 1 skpa.save() return redirect('skpa_list') # DIPA View class DipaList(ListView): model = Dipa template_name = 'arsip/dipa/dipa_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['current_user'] = self.request.user return context class DipaCreate(CreateView): model = Dipa fields = ['uraian_dipa', 'file_pok', 'file_adk', 'file_dipa'] template_name = 'arsip/dipa/dipa_form.html' success_url = reverse_lazy('dipa_list') def form_valid(self, form): form.instance.author = self.request.user return super(DipaCreate, self).form_valid(form) class DipaDetail(DetailView): model = Dipa template_name = 'arsip/dipa/dipa_detail.html' class DipaUpdate(UpdateView): model = Dipa fields = ['nomor', 'perihal', 'tanggal_surat', 'upload'] template_name = 'arsip/dipa/dipa_form.html' success_url = reverse_lazy('dipa_list') class DipaDelete(DeleteView): model = Dipa success_url = reverse_lazy('dipa_list') def DipaApprove(request, pk): dipa = Dipa.objects.get(pk=pk) dipa.approval = 1 dipa.save() return redirect('dipa_list') # SPM View class SpmList(ListView): model = Spm template_name = 'arsip/spm/spm_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['current_user'] = self.request.user return context class SpmCreate(CreateView): model = Spm fields = ['nomor_spm', 'jenis_spm', 'tanggal_spm', 'nomor_sp2d', 'tanggal_sp2d', 'jumlah_potongan', 'jumlah_bersih', 'file_spm', 'file_sp2d'] template_name = 'arsip/spm/spm_form.html' success_url = reverse_lazy('spm_list') def form_valid(self, form): form.instance.author = self.request.user return super(SpmCreate, self).form_valid(form) def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['tanggal_spm'].widget = forms.DateInput(attrs={'type':'date'}) form.fields['tanggal_sp2d'].widget = forms.DateInput(attrs={'type':'date'}) return form class SpmDetail(DetailView): model = Spm template_name = 'arsip/spm/spm_detail.html' class SpmUpdate(UpdateView): model = Spm fields = ['nomor_spm', 'jenis_spm', 'tanggal_spm', 'nomor_sp2d', 'tanggal_sp2d', 'jumlah_potongan', 'jumlah_bersih', 'file_spm', 'file_sp2d'] template_name = 'arsip/spm/spm_form.html' success_url = reverse_lazy('spm_list') class SpmDelete(DeleteView): model = Spm success_url = reverse_lazy('spm_list') def SpmApprove(request, pk): spm = Spm.objects.get(pk=pk) spm.approval = 1 spm.save() return redirect('spm_list') # TUP View class TupList(ListView): model = Tup template_name = 'arsip/tup/tup_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['current_user'] = self.request.user return context class TupCreate(CreateView): model = Tup fields = ['nomor', 'keterangan', 'tanggal_surat', 'jumlah_tup', 'upload'] template_name = 'arsip/tup/tup_form.html' success_url = reverse_lazy('tup_list') def form_valid(self, form): form.instance.author = self.request.user return super(TupCreate, self).form_valid(form) def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['tanggal_surat'].widget = forms.DateInput(attrs={'type':'date'}) return form class TupDetail(DetailView): model = Tup template_name = 'arsip/tup/tup_detail.html' class TupUpdate(UpdateView): model = Tup fields = ['nomor', 'keterangan', 'tanggal_surat', 'jumlah_tup', 'upload'] template_name = 'arsip/tup/tup_form.html' success_url = reverse_lazy('tup_list') class TupDelete(DeleteView): model = Tup success_url = reverse_lazy('tup_list') def TupApprove(request, pk): tup = tup.objects.get(pk=pk) tup.approval = 1 tup.save() return redirect('tup_list') # Survei View class SurveiList(ListView): model = Survei template_name = 'arsip/survei/survei_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['current_user'] = self.request.user return context class SurveiCreate(CreateView): model = Survei fields = ['nama_survei', 'kategori', 'periode', 'penanggung_jawab', 'keterangan', 'upload'] template_name = 'arsip/survei/survei_form.html' success_url = reverse_lazy('survei_list') def form_valid(self, form): form.instance.author = self.request.user return super(SurveiCreate, self).form_valid(form) def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['periode'].widget = forms.DateInput(attrs={'type':'date'}) return form class SurveiDetail(DetailView): model = Survei template_name = 'arsip/survei/survei_detail.html' class SurveiUpdate(UpdateView): model = Survei fields = ['nama_survei', 'kategori', 'periode', 'penanggung_jawab', 'keterangan', 'upload'] template_name = 'arsip/survei/survei_form.html' success_url = reverse_lazy('survei_list') class SurveiDelete(DeleteView): model = Survei success_url = reverse_lazy('survei_list') def SurveiApprove(request, pk): survei = survei.objects.get(pk=pk) survei.approval = 1 survei.save() return redirect('survei_list') # Daftar Sampel View class DaftarSampelList(ListView): model = DaftarSampel template_name = 'arsip/daftar-sampel/daftarsampel_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['current_user'] = self.request.user return context class DaftarSampelCreate(CreateView): model = DaftarSampel fields = ['nama_survei', 'kategori', 'periode', 'wilayah', 'penanggung_jawab', 'keterangan', 'upload'] template_name = 'arsip/daftar-sampel/daftarsampel_form.html' success_url = reverse_lazy('daftar_sampel_list') def form_valid(self, form): form.instance.author = self.request.user return super(DaftarSampelCreate, self).form_valid(form) def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['periode'].widget = forms.DateInput(attrs={'type':'date'}) return form class DaftarSampelDetail(DetailView): model = DaftarSampel template_name = 'arsip/daftar-sampel/daftarsampel_detail.html' class DaftarSampelUpdate(UpdateView): model = DaftarSampel fields = ['nama_survei', 'kategori', 'periode', 'wilayah', 'penanggung_jawab', 'keterangan', 'upload'] template_name = 'arsip/daftar-sampel/daftarsampel_form.html' success_url = reverse_lazy('daftar_sampel_list') class DaftarSampelDelete(DeleteView): model = DaftarSampel success_url = reverse_lazy('daftar_sampel_list') def DaftarSampelApprove(request, pk): daftar_sampel = daftar_sampel.objects.get(pk=pk) daftar_sampel.approval = 1 daftar_sampel.save() return redirect('daftar_sampel_list')
{"/arsip/admin.py": ["/arsip/models.py"], "/arsip/urls.py": ["/arsip/views.py"], "/arsip/views.py": ["/arsip/models.py"]}
39,620,401
frankie-g1/Lab2Pong
refs/heads/master
/ball.py
import pygame class Ball: RADIUS = 10 def __init__(self, x, y, vx, vy, fgcolor, bgcolor, screen, wall, ceiling, floor): # Instance variables self.x = x self.y = y self.screen = screen self.vx = vx self.vy = vy self.fgcolor = fgcolor self.bgcolor = bgcolor self.wall = wall + self.RADIUS self.ceiling = ceiling + self.RADIUS self.floor = floor - self.RADIUS def show(self, color): pygame.draw.circle(self.screen, color, (self.x, self.y), self.RADIUS) def update(self): # Check if I'm colliding with wall position: # Flip the direction if self.x <= self.wall + self.RADIUS: self.vx = -1 * self.vx elif self.y <= self.ceiling + self.RADIUS or self.y >= self.floor - self.RADIUS: self.vy = -1 * self.vy # new position = old position + delta position # delta position = velocity # delete the old ball self.show(self.bgcolor) self.x = self.x + self.vx self.y = self.y + self.vy self.show(self.fgcolor)
{"/pongLab3.py": ["/ball.py"]}
39,620,402
frankie-g1/Lab2Pong
refs/heads/master
/pongLab3.py
import pygame as pg from ball import Ball import random def main(): pg.init() pg.display.set_caption("My Pong") # Create a surface WIDTH = 800 HEIGHT = 480 BORDER = 20 VELOCITY_x = -7 FPS = 60 if (bool(random.getrandbits(1)) == True): VELOCITY_y = -7 else: VELOCITY_y = 7 screen = pg.display.set_mode((WIDTH, HEIGHT)) # add a solid background: r, g, b screen.fill((0, 0, 0)) # double buffering: stage all changes and update them all at once # avoids flickering pg.display.update() # Draw walls as rectangles # https://www.pygame.org/docs/ref/draw.html#pygame.draw.rect # rect(surface, color, rect) -> Rect # Rect((left, top), (width, height)) -> Rect blackColor = pg.Color("Black") wcolor = pg.Color("White") # top wall pg.draw.rect(screen, wcolor, pg.Rect((0, 0), (WIDTH, BORDER))) # left wall pg.draw.rect(screen, wcolor, pg.Rect((0, 0), (BORDER, HEIGHT))) # bottom wall pg.draw.rect(screen, wcolor, pg.Rect((0, HEIGHT - BORDER), (WIDTH, BORDER))) # no right wall # pg.draw.rect(screen, wcolor, pg.Rect((0,HEIGHT), (BORDER, WIDTH))) # Ball init x0 = WIDTH - Ball.RADIUS y0 = HEIGHT // 2 vx0 = VELOCITY_x vy0 = VELOCITY_y wall = BORDER ceiling = BORDER floor = HEIGHT - BORDER ycolor = pg.Color("Yellow") a = Ball(x0, y0, vx0, vy0, ycolor, blackColor, screen, wall, ceiling, floor) pg.display.update() # define a variable to control the main loop running = True clock = pg.time.Clock() # main loop while running: # event handling, gets all event from the event queue (POLLING) # Event is a queue for event in pg.event.get(): # only do something if the event is of TYPE QUIT if event.type == pg.QUIT: # change value to false, to exit the main loop running = False a.update() pg.display.update() clock.tick(FPS) if __name__ == "__main__": # call the main function main()
{"/pongLab3.py": ["/ball.py"]}
39,643,173
lesite/Shoplifter
HEAD
/shoplifter/payment/backend/modules/dummy.py
from shoplifter.payment.lib.credentials import GiftCard, DebitCard from shoplifter.payment.backend import BaseBackend from shoplifter.payment.backend.modules.dummy_controllers import ( enable_controllers, DummyDebitLookup) class TransactionTypeNotSupported(Exception): pass class DummyBackend(BaseBackend): name = 'dummypayment' def prepare_payment(self, order, amount, cc_num, exp_year, exp_mo, csc=None, processing_order=1): # TODO!! Need to figure out exception handling. # Do we want the backend to take care of removing this if it # fails? How do we deal with this? Create a faild payment? transaction_id = self.gen_transaction_id(order.id) billing, shipping = self.addressee_class.get_address_pair(order) data = { 'transaction_id': transaction_id, 'order_id': order.id, 'amount': amount, 'processed': False, 'processing_order': processing_order, 'backend_key': self.name, 'billing': billing, 'shipping': shipping, } cc = self.credential_class( transaction_id, cc_num, exp_year, exp_mo, csc) cc.save() payment = self.payment_class(**data) payment.save() return payment def purchase(self, payment): payment.processed = True # Get gateway order id to retrive CC. transaction_id = payment.transaction_id.encode('utf8') # Get credit card from encrypted temp storage. cc = self.credential_class.get(transaction_id) # Fails if not present. if not cc: raise self.WaitedTooLong() # Payment code to contact payment gateway would go # here.. # Now save avs data. avs_res = self.avs_class( avs_message='Postal code and verything matches!', avs_result='F', avs_postal_match=True, avs_address_match=True, ) payment.avs_result = avs_res # Set csc result (which is usually an integer coming from # payment gateway payment.csc_result = 1 # Auth is successful! payment.success = True # Save in DB. payment.save() return payment.success def authorize(self, authorization): authorization.processed = True transaction_id = authorization.transaction_id.encode('utf8') # Get credit card from encrypted temp storage. cc = self.credential_class.get(transaction_id) # Fails if not present. if not cc: raise self.WaitedTooLong() # Authorization code to contact payment gateway would go # here.. # Now save avs data. avs_res = self.avs_class( avs_message='Postal code and verything matches!', avs_result='F', avs_postal_match=True, avs_address_match=True, ) authorization.avs_result = avs_res # Set csc result (which is usually an integer coming from # payment gateway authorization.csc_result = 1 # Auth is successful! authorization.success = True # Save in DB. authorization.save() return authorization.success def confirm(self, authorization, amount=None, force=False): """ authorization : The authorization object to confirm. amount : The amount to confirm (most likely the pre-auth amount) force : if a capture exists but is not yet processed, this could mean that something went wrong or that another instance is already trying to capture. Force will ignore this fact and attempt to capture anyways. """ # Prepare data. if not amount: amount = authorization.amount trn_id = self.gen_transaction_id( authorization.order_id) # Perform a few checks: capture = authorization.authorization_capture if not capture: capture = authorization.create_capture(trn_id, amount, self.name) elif capture and ((not capture.processed and not force) or capture.processed): raise self.CaptureAlreadyExists # Create capture capture.processed = True capture.success = True capture.save() return capture class DummyDebitCardBackend(BaseBackend): name = 'dummydebit' credential_class = DebitCard def __init__(self, *a, **kw): super(DummyDebitCardBackend, self).__init__(*a, **kw) # Provide some controllers for payment systems that require # post-back from third party site. # TODO: Make this work. if enable_controllers: self.controller = DummyDebitLookup(self) def prepare_payment(self, order, amount, dc_num, processing_order=0): """ Note that processing_order is set to 0 here, because the system assumes that gift card transactions should be processed before credit card ones. """ transaction_id = self.gen_transaction_id(order.id) billing, shipping = self.addressee_class.get_address_pair(order) data = { 'transaction_id': transaction_id, 'order_id': order.id, 'amount': amount, 'processed': False, 'processing_order': processing_order, 'backend_key': self.name, 'billing': billing, 'shipping': shipping, } dc = self.credential_class( transaction_id, dc_num) dc.save() payment = self.payment_class(**data) payment.save() return payment def purchase(self, payment): payment.processed = True transaction_id = payment.transaction_id.encode('utf8') dc = self.credential_class.get(transaction_id) if not dc: raise self.WaitedTooLong() payment.success = True payment.save() return True def authorize(self, authorization): raise TransactionTypeNotSupported class DummyGiftCardBackend(BaseBackend): name = 'dummygiftcard' credential_class = GiftCard def prepare_payment(self, order, amount, gc_num, processing_order=0): """ Note that processing_order is set to 0 here, because the system assumes that gift card transactions should be processed before credit card ones. """ transaction_id = self.gen_transaction_id(order.id) billing, shipping = self.addressee_class.get_address_pair(order) data = { 'transaction_id': transaction_id, 'order_id': order.id, 'amount': amount, 'processed': False, 'processing_order': processing_order, 'backend_key': self.name, 'billing': billing, 'shipping': shipping, } gc = self.credential_class( transaction_id, gc_num) gc.save() payment = self.payment_class(**data) payment.save() return payment def purchase(self, payment): payment.processed = True transaction_id = payment.transaction_id.encode('utf8') gc = self.credential_class.get(transaction_id) if not gc: raise self.WaitedTooLong() payment.success = True payment.save() return True def authorize(self, authorization): authorization.processed = True transaction_id = authorization.transaction_id.encode('utf8') gc = self.credential_class.get(transaction_id) if not gc: raise self.WaitedTooLong() authorization.success = True authorization.save() return True def confirm(self, authorization, amount=None, force=False): """ authorization : The authorization object to confirm. amount : The amount to confirm (most likely the pre-auth amount) force : if a capture exists but is not yet processed, this could mean that something went wrong or that another instance is already trying to capture. Force will ignore this fact and attempt to capture anyways. """ # Prepare data. if not amount: amount = authorization.amount trn_id = self.gen_transaction_id( authorization.order_id) # Perform a few checks: capture = authorization.authorization_capture if not capture: capture = authorization.create_capture(trn_id, amount, self.name) elif capture and ((not capture.processed and not force) or capture.processed): raise self.CaptureAlreadyExists # Create capture capture.processed = True capture.success = True capture.save() return capture
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,174
lesite/Shoplifter
HEAD
/tests/core/util/string_examples.py
# encoding: utf-8 from shoplifter.core.util import force_unicode, slugify from ...helpers import * def assert_unicode_and_equal(got, expected): assert_equal(got, expected) assert_is_instance(got, unicode) class ForceUnicodeExamples(object): def test_force_unicode_on_unicode(self): u = u'some unicôde' assert_unicode_and_equal(force_unicode(u), u) def test_force_unicode_on_bytestring(self): s = 'some string' u = u'some string' assert_unicode_and_equal(force_unicode(s), u) def test_force_unicode_on_object_with_unicode_method(self): class A(object): __unicode__ = lambda s: u'fdsa' a = A() u = u'fdsa' assert_unicode_and_equal(force_unicode(a), u) def test_force_unicode_on_object_with_only_str_method(self): class A(object): __str__ = lambda s: 'fdsa' a = A() u = u'fdsa' assert_unicode_and_equal(force_unicode(a), u) def test_slugify(): got_and_expected = [ (slugify(None), u''), (slugify(''), u''), (slugify('FDSA'), u'fdsa'), (slugify('This is a sentence'), u'this-is-a-sentence'), (slugify('Thîs is a senténce'), u'this-is-a-sentence'), (slugify('Thîs is a senténce', limit=6), u'this-i'), (slugify('Thîs is a senténce', limit=7), u'this-is'), (slugify('Thîs is a senténce', limit=8), u'this-is'), ] for got, expected in got_and_expected: yield assert_unicode_and_equal, got, expected
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,175
lesite/Shoplifter
HEAD
/tests/payment/credential_spec.py
# encoding: utf-8 import mongoengine from unittest import TestCase from shoplifter.payment import config from shoplifter.core import plugins as core_plugins from shoplifter.payment.lib.credentials import ( CreditCard, GiftCard, DebitCard, PaymentCredential) from nose.tools import assert_equals, assert_raises class CredentialSpecs(TestCase): def setUp(self): config.cc_store_time = 60 * 5 core_plugins.load('temp_storage', 'dummy', None, 'thisisakey123456') config.temp_store = core_plugins['temp_storage'].dummy def it_fails_when_badly_implemented(self): class BadCredential(PaymentCredential): pass assert_raises(NotImplementedError, BadCredential().get, *('some_id', )) assert_raises(NotImplementedError, BadCredential().save) def it_fails_when_luhn_fails(self): assert_raises( PaymentCredential.CardFormatError, CreditCard, *('derp1', '4242424242424241')) assert_raises( PaymentCredential.CardFormatError, DebitCard, *('derp1', '4242424242424241')) def test_luhn_validation(self): # Check that luhn check fails early when instantiating a CC badluhn = { 'transaction_id': 'derp', 'number': '4530911622722221', 'exp_year': '2011', 'exp_month': '07', 'csc': '770', 'cc_type': 'V'} assert_raises( CreditCard.CardFormatError, CreditCard, **badluhn) # Saves a cc in temp_store cc = CreditCard( transaction_id='derp', number='4530911622722220', exp_year='2011', exp_month='07', csc='770', cc_type='V') cc.save() # Retrieves it and checks it still has data. cc = CreditCard.get('derp') assert_equals(cc.number, '4530911622722220') # Checks that passing bad key returns None cc = CreditCard.get('fail') assert_equals(cc, None)
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,176
lesite/Shoplifter
HEAD
/tests/payment/api_spec.py
import mongoengine import decimal from shoplifter.core import plugins as core_plugins from shoplifter.payment.lib.test_helpers import TestOrder from shoplifter.payment import plugins from shoplifter.payment import config from shoplifter.payment.models import ( Authorization, Payment, Addressee, BaseTransaction) from shoplifter.payment.backend import BaseBackend from shoplifter.payment.backend.modules.dummy import TransactionTypeNotSupported from nose.tools import assert_equals, assert_raises def get_order(amount=decimal.Decimal('30')): return TestOrder(amount) class TestAddressee(object): def it_gets_an_address_from_order_if_available(self): order = get_order() addressee = Addressee.from_order_address(order.billing) assert_equals(addressee.first_name, 'Benoit') order.billing = None addressee = Addressee.from_order_address(order.billing) assert(not addressee) class BackendPaymentApiSpec(object): def setup(self): config.cc_store_time = 60 * 5 core_plugins.load('temp_storage', 'dummy', None, 'thisisakey123456') config.temp_store = core_plugins['temp_storage'].dummy def prepare_payment(self, order, amount): amount = decimal.Decimal(amount) if self.backend.name == 'dummypayment': args = ( order, amount, '4242424242424242', '2011', '05',) kwargs = { 'csc': 123} elif self.backend.name == 'dummygiftcard': args = ( order, amount, '4242424242424242') kwargs = {} elif self.backend.name == 'dummydebit': args = ( order, amount, '4242424242424242') kwargs = {} pay = self.backend.prepare_payment(*args, **kwargs) return pay def load_backend(self, use_pre_auth, plugin='dummypayment'): # use_preauth defines whether the backend uses # pre-authorization (True) or one-time capture (False). plugins.load( 'payment_backends', plugin, {'use_pre_auth': use_pre_auth}) self.backend = plugins['payment_backends'][plugin] def test_second_capture_fail(self): """ The second attemps at an authorization capture fails if a capture was already attempted but 'processed' was never set to True. This can be overidden using force_capture argument in capture_all_authorizations. """ self.load_backend(True) order = get_order() auth = self.prepare_payment(order, '30') auth.process() auth.create_capture( self.backend.gen_transaction_id(order.id), decimal.Decimal('30'), 'dummypayment') assert_raises( self.backend.CaptureAlreadyExists, order.payment.capture_all_authorizations) order.payment.capture_all_authorizations(force_capture=True) assert_equals( order.payment.get_captured_amount(), decimal.Decimal('30')) def test_second_capture_fail_giftcard(self): """ Second attemp with unprocessed capture, but when using GiftCard. """ self.load_backend(True, 'dummygiftcard') order = get_order() auth = self.prepare_payment(order, '30') auth.process() auth.create_capture( self.backend.gen_transaction_id(order.id), decimal.Decimal('30'), 'dummypayment') assert_raises( self.backend.CaptureAlreadyExists, order.payment.capture_all_authorizations) order.payment.capture_all_authorizations(force_capture=True) assert_equals( order.payment.get_captured_amount(), decimal.Decimal('30')) def test_transaction_fails_when_badly_implemented(self): class BadBackend(BaseTransaction): pass assert_raises(NotImplementedError, BadBackend().process) def it_fails_authorizing_when_cc_not_in_cache(self): self.load_backend(True) order = get_order() auth = self.prepare_payment(order, '30') # Excplicitly delete the key from temp store. config.temp_store.delete(auth.transaction_id) # Now processing fails. assert_raises( self.backend.WaitedTooLong, auth.process) def it_fails_purchasing_when_cc_not_in_cache(self): self.load_backend(False) order = get_order() auth = self.prepare_payment(order, '30') # Excplicitly delete the key from temp store. config.temp_store.delete(auth.transaction_id) # Now processing fails. assert_raises( self.backend.WaitedTooLong, auth.process) def it_fails_authorizing_when_cc_not_in_cache_giftcard(self): self.load_backend(True, 'dummygiftcard') order = get_order() auth = self.prepare_payment(order, '30') # Excplicitly delete the key from temp store. config.temp_store.delete(auth.transaction_id) # Now processing fails. assert_raises( self.backend.WaitedTooLong, auth.process) def it_fails_purchasing_when_cc_not_in_cache_giftcard(self): self.load_backend(False, 'dummygiftcard') order = get_order() auth = self.prepare_payment(order, '30') # Excplicitly delete the key from temp store. config.temp_store.delete(auth.transaction_id) # Now processing fails. assert_raises( self.backend.WaitedTooLong, auth.process) def it_fails_when_trying_to_authorize_debit(self): self.load_backend(True, 'dummydebit') order = get_order() auth = self.prepare_payment(order, '30') # Now processing fails. assert_raises(TransactionTypeNotSupported, auth.process) def it_fails_purchasing_when_cc_not_in_cache_debitcard(self): self.load_backend(False, 'dummydebit') order = get_order() auth = self.prepare_payment(order, '30') # Excplicitly delete the key from temp store. config.temp_store.delete(auth.transaction_id) # Now processing fails. assert_raises( self.backend.WaitedTooLong, auth.process) def it_fails_when_backend_badly_implemented(self): class BadBackend(BaseBackend): pass sample_conf = {'use_pre_auth': False} assert_raises(NotImplementedError, BadBackend(sample_conf).purchase, *(None, )) assert_raises(NotImplementedError, BadBackend(sample_conf).authorize, *(None, )) assert_raises(NotImplementedError, BadBackend(sample_conf).confirm, *(None, )) assert_raises(NotImplementedError, BadBackend(sample_conf).cancel, *(None, )) assert_raises(NotImplementedError, BadBackend(sample_conf).refund, *(None, )) def it_doesnt_need_an_address_to_process_an_order(self): self.load_backend(True) order = get_order() order.billing = None order.shipping = None self.prepare_payment(order, '15') self.prepare_payment(order, '15') order.payment.process_all_payments() order.payment.capture_all_authorizations() assert_equals(order.balance, decimal.Decimal('0')) assert(order.is_prepared) assert_equals(len(order.payment.get_payments()), 2) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('0')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0')) def can_prepare_preauth(self): self.load_backend(True) order = get_order() self.prepare_payment(order, '30') assert_equals(order.balance, decimal.Decimal('30')) assert(order.is_prepared) assert_equals(len(order.payment.get_payments()), 1) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('30')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0')) def can_process_preauth(self): self.load_backend(True) order = get_order() auth = self.prepare_payment(order, '30') auth.process() assert_equals(order.balance, decimal.Decimal('0')) assert(order.is_prepared) assert_equals(len(order.payment.get_payments()), 1) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('0')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0')) def can_process_multiple_preauth_for_one_order(self): self.load_backend(True) order = get_order() self.prepare_payment(order, '15') self.prepare_payment(order, '15') order.payment.process_all_payments() assert_equals(order.balance, decimal.Decimal('0')) assert(order.is_prepared) assert_equals(len(order.payment.get_payments()), 2) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('0')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0')) def can_capture_preauth(self): self.load_backend(True) order = get_order() self.prepare_payment(order, '15') self.prepare_payment(order, '15') order.payment.process_all_payments() order.payment.capture_all_authorizations() assert_equals(order.balance, decimal.Decimal('0')) assert(order.is_prepared) assert_equals(len(order.payment.get_payments()), 2) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('0')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0')) def can_confirm_lesser_amount(self): self.load_backend(True) order = get_order() auth1 = self.prepare_payment(order, '15') auth2 = self.prepare_payment(order, '15') assert(order.is_prepared) order.payment.process_all_payments() assert_equals(len(order.payment.get_payments(processed=True, success=True)), 2) auth1.reload() auth2.reload() self.backend.confirm(auth1, decimal.Decimal('0.09')) self.backend.confirm(auth2, decimal.Decimal('7.51')) assert_equals(order.balance, decimal.Decimal('0')) assert_equals(len(order.payment.get_payments()), 2) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('7.60')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(),decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('0')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0')) def can_automatically_find_the_amount(self): self.load_backend(True) order = get_order() p1 = self.prepare_payment(order, '30') order.payment.process_all_payments() p1.reload() self.backend.confirm(p1) assert_equals(order.balance, decimal.Decimal('0')) assert(order.is_prepared) assert_equals(len(order.payment.get_payments()), 1) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('0')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0')) def can_perform_one_time_purchase(self): self.load_backend(False) order = get_order() payment = self.prepare_payment(order, '30') payment.process() assert_equals(order.balance, decimal.Decimal('0')) assert(order.is_prepared) assert_equals(len(order.payment.get_payments()), 1) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('0')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0')) def can_prepare_preauth_giftcard(self): self.load_backend(True, 'dummygiftcard') order = get_order() self.prepare_payment(order, '30') assert_equals(order.balance, decimal.Decimal('30')) assert(order.is_prepared) assert_equals(len(order.payment.get_payments()), 1) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('30')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0')) def can_process_preauth_giftcard(self): self.load_backend(True, 'dummygiftcard') order = get_order() auth = self.prepare_payment(order, '30') auth.process() assert_equals(order.balance, decimal.Decimal('0')) assert(order.is_prepared) assert_equals(len(order.payment.get_payments()), 1) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('0')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0')) def can_process_multiple_preauth_for_one_order_giftcard(self): self.load_backend(True, 'dummygiftcard') order = get_order() self.prepare_payment(order, '15') self.prepare_payment(order, '15') order.payment.process_all_payments() assert_equals(order.balance, decimal.Decimal('0')) assert(order.is_prepared) assert_equals(len(order.payment.get_payments()), 2) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('0')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0')) def can_capture_preauth_giftcard(self): self.load_backend(True, 'dummygiftcard') order = get_order() self.prepare_payment(order, '15') self.prepare_payment(order, '15') order.payment.process_all_payments() order.payment.capture_all_authorizations() assert_equals(order.balance, decimal.Decimal('0')) assert(order.is_prepared) assert_equals(len(order.payment.get_payments()), 2) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('0')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0')) def can_confirm_lesser_amount_giftcard(self): self.load_backend(True, 'dummygiftcard') order = get_order() auth1 = self.prepare_payment(order, '15') auth2 = self.prepare_payment(order, '15') assert(order.is_prepared) order.payment.process_all_payments() assert_equals(len(order.payment.get_payments(processed=True, success=True)), 2) auth1.reload() auth2.reload() self.backend.confirm(auth1, decimal.Decimal('0.09')) self.backend.confirm(auth2, decimal.Decimal('7.51')) assert_equals(order.balance, decimal.Decimal('0')) assert_equals(len(order.payment.get_payments()), 2) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('7.60')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(),decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('0')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0')) def can_automatically_find_the_amount_giftcard(self): self.load_backend(True, 'dummygiftcard') order = get_order() p1 = self.prepare_payment(order, '30') order.payment.process_all_payments() p1.reload() self.backend.confirm(p1) assert_equals(order.balance, decimal.Decimal('0')) assert(order.is_prepared) assert_equals(len(order.payment.get_payments()), 1) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('0')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0')) def can_perform_one_time_purchase_giftcard(self): self.load_backend(False, 'dummygiftcard') order = get_order() payment = self.prepare_payment(order, '30') payment.process() assert_equals(order.balance, decimal.Decimal('0')) assert(order.is_prepared) assert_equals(len(order.payment.get_payments()), 1) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('0')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0')) def can_perform_one_time_purchase_debitcard(self): self.load_backend(False, 'dummydebit') order = get_order() payment = self.prepare_payment(order, '30') payment.process() assert_equals(order.balance, decimal.Decimal('0')) assert(order.is_prepared) assert_equals(len(order.payment.get_payments()), 1) assert_equals(order.payment.get_payment_sum(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_amount(), decimal.Decimal('0')) assert_equals(order.payment.get_captured_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_prepared_and_processed_payment_amount(), decimal.Decimal('30')) assert_equals(order.payment.get_balance(), decimal.Decimal('0')) assert_equals(order.payment.get_to_prepare_amount(), decimal.Decimal('0'))
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,177
lesite/Shoplifter
HEAD
/tests/core/util/cipher_specs.py
# -*- coding: utf-8 -*- from nose.tools import assert_equals from shoplifter.core.util import Cipher class CipherSpecs(object): def setup(self): self.cipher = Cipher('testkey123456789') def can_encrypt_a_string(self): original = 'derp herp' expected_encrypted = 'a89d1d6f224e8f2a3c' encrypted = self.cipher.encrypt(original) decrypted = self.cipher.decrypt(encrypted) assert_equals(encrypted, expected_encrypted) assert_equals(original, decrypted) def can_encrypt_a_unicode_string(self): original = u'Mêlé comme ça.' expected_encrypted = '81df5bd6334f72c3767487febb58c4c456' encrypted = self.cipher.encrypt(original) decrypted = self.cipher.decrypt(encrypted) assert_equals(encrypted, expected_encrypted) assert_equals(original, decrypted) def can_encrypt_a_dictionary(self): original = {1: 'derp herp'} expected_encrypted = {1: 'a89d1d6f224e8f2a3c'} encrypted = self.cipher.encrypt(original) decrypted = self.cipher.decrypt(encrypted) assert_equals(encrypted, expected_encrypted) assert_equals(original, decrypted) def can_encrypt_a_list(self): original = ['derp herp', ] expected_encrypted = ['a89d1d6f224e8f2a3c', ] encrypted = self.cipher.encrypt(original) decrypted = self.cipher.decrypt(encrypted) assert_equals(encrypted, expected_encrypted) assert_equals(list(original), decrypted) def can_encrypt_tuple(self): original = ('derp herp', ) expected_encrypted = ('a89d1d6f224e8f2a3c', ) encrypted = self.cipher.encrypt(original) decrypted = self.cipher.decrypt(encrypted) assert_equals(encrypted, expected_encrypted) assert_equals(original, decrypted) def can_encrypt_a_tuple_containing_integer(self): original = ('derp herp', 2) expected_encrypted = ('a89d1d6f224e8f2a3c', 2) encrypted = self.cipher.encrypt(original) decrypted = self.cipher.decrypt(encrypted) assert_equals(encrypted, expected_encrypted) assert_equals(original, decrypted)
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,178
lesite/Shoplifter
HEAD
/shoplifter/core/util/string.py
# encoding: utf-8 import re import unicodedata __all__ = ['force_unicode', 'slugify'] def force_unicode(value, encoding='utf-8', errors='strict'): """ Force a value to be unicode. If the value is a bytestring, it will call decode using the given encoding and errors strategy. If it has a __unicode__ method, it will call that, otherwise it will call str() on the value and then convert that to unicode. """ if isinstance(value, unicode): u = value elif isinstance(value, str): u = value.decode(encoding, errors) else: if hasattr(value, '__unicode__'): u = unicode(value) else: u = unicode(str(value), encoding, errors) return u SLUGIFY_STRIP_RE = re.compile(r'[^\w\s-]') SLUGIFY_HYPHENATE_RE = re.compile(r'[-\s]+') def slugify(value, limit=None): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. Can be limited to a certain length. """ if not value: return u'' if not isinstance(value, unicode): value = force_unicode(value) # remove all non-ascii characters, recoding as ascii value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') # remove all non-word, non-space characters, and strip and lowercase, # decoding back into unicode value = SLUGIFY_STRIP_RE.sub('', value) if limit: value = value[:limit] value = SLUGIFY_HYPHENATE_RE.sub('-', value.strip().lower()) return unicode(value)
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,179
lesite/Shoplifter
HEAD
/shoplifter/payment/models.py
from mongoengine import IntField, BooleanField, StringField, \ EmailField, DateTimeField, EmbeddedDocumentField, \ ReferenceField, EmbeddedDocument, Document from shoplifter.core.db.field import MoneyField from shoplifter.payment import plugins class Addressee(EmbeddedDocument): """ This is metadata that can optionally be provided to payment gateways, for example to define billing and shipping address. """ first_name = StringField(required=True) last_name = StringField() email = EmailField() phone_number = StringField() street_number = StringField(required=True) street_name = StringField(required=True) street_type = StringField() unit_number = StringField() street_direction = StringField() street_line_2 = StringField() postal_code = StringField() city = StringField(required=True) province = StringField(required=True) country = StringField(required=True) @staticmethod def from_order_address(address): if not address: return None return Addressee( first_name=address.first_name, last_name=address.last_name, email=address.email, phone_number=address.phone_number, street_number=address.street_number, street_name=address.street_name, street_type=address.street_type, street_direction=address.street_direction, unit_numer=address.unit_number, street_line_2=address.street_line_2, postal_code=address.postal_code, city=address.city, province=address.province, country=address.country, ) @staticmethod def get_address_pair(order): return Addressee.from_order_address(order.billing), \ Addressee.from_order_address(order.shipping) class AVSData(EmbeddedDocument): """ This is used to record AVS response data. """ avs_message = StringField() avs_result = StringField(max_length=1) avs_postal_match = BooleanField() avs_address_match = BooleanField() """ The following describes the actual data models. """ class BaseTransaction(Document): """ Base transaction class that defines the basic behaviour of financial transaction objects, including Authorization, Authorization Capture, Purchase and Cancellation. * id: This is the order_id that's been transmitted to the payment gateway. * transaction_id: Payment gateways return a transaction ID that identifies the transaction in their system. This is where to store it. * order_id: This should be the order's unique identifier. It is used to establish a relationship between orders and transactions. * processed: Defines whether or not an attempt was made to process the transaction against the payment gateway. Anytime that an attempt is made to process a transaction, this should be set to True, regardless on whether or not it is successful. * process_time_stamp: This is the time that the processing attempt was attempted. * processing_order: This defines the order that transactions should be processed. For example, we may want to process GiftCard transactions before we process CreditCard ones. * backend_key: This is a string that identifies the payment backend that set-up this transaction. This is used to select the proper payment backend when retrieving the transaction. * response_code: This is the transaction response code returned by the payment gateway. * message: This is the message string that has been returned by the payment gateway. """ transaction_id = StringField(unique=True) gateway_transaction_id = StringField() order_id = StringField(required=True) processed = BooleanField() processing_order = IntField() backend_key = StringField() response_code = StringField() message = StringField() processed_time_stamp = DateTimeField() gateway_times_stamp = DateTimeField() @property def backend(self): """ This returns the payment that set up this transaction """ return plugins['payment_backends'][self.backend_key] def process(self): raise NotImplementedError class Payment(BaseTransaction): """ * amount: The money amount requested. * billing: This is an Address document. If you want address verification to be validated, you need to enter billing data. * shipping: You can supply shipping information to some payment gateways. If the gateway supports this, this is where you will populate the shipping data. * success: Whether the transaction was successful or not. * csc_result: This is the result for CSC check. This is either one of the following: 0: Fail 1: Pass -1: Not Processed * avs_result: This is the address verification result code. This may be different for each payment gateway. This should at least be recorded and displayed to the site admin when reviewing orders. TODO: Think of this more? """ amount = MoneyField(required=True) billing = EmbeddedDocumentField(Addressee) shipping = EmbeddedDocumentField(Addressee) success = BooleanField() csc_result = IntField() avs_result = EmbeddedDocumentField(AVSData) @classmethod def get_capture_class(cls): return None def process(self): return self.backend.purchase(self) class AuthorizationCapture(BaseTransaction): """ This is instantiated and saved when capturing an already pre-authorized payment. * auth_id: Authorization document identifier. """ amount = MoneyField(required=True) success = BooleanField() class Authorization(Payment): """ amount_requested: This is the desired transaction amount. amount_approved: This is the amount that's been been approved by the payment gateway. capture is a reference to the AuthorizationCapture transaction. """ authorization_capture = ReferenceField(AuthorizationCapture) @classmethod def get_capture_class(cls): # Inspect model to find the authorization capture document # class. return cls._fields['authorization_capture'].document_type_obj def create_capture(self, trn_id, amount, backend_name): """ This is called by the BaseBackend as the first steps of creating an authorization capture. """ capture = AuthorizationCapture( transaction_id=trn_id, order_id=self.order_id, amount=amount, processed=False, backend_key=backend_name) capture.save() self.authorization_capture = capture self.save() return capture def process(self): return self.backend.authorize(self) def capture(self, force=False): return self.backend.confirm(self, self.amount, force) class Cancellation(BaseTransaction): """ meh """ success = BooleanField()
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,180
lesite/Shoplifter
HEAD
/features/steps.py
# -*- coding: utf-8 -*- # Monkeypatching memcache client to use mockcache instead. import memcache import mockcache memcache.Client = mockcache.Client import decimal from pkg_resources import load_entry_point import mongoengine from lettuce import step, world from nose.tools import assert_equals from shoplifter.payment import config, plugins from shoplifter.core import plugins as core_plugins TEST_CREDENTIALS = { 'dummypayment': ('4242424242424242', '2011', '01', '123'), 'dummygiftcard': ('derp', ), } mongoengine.connect('testdb6') core_plugins.load('temp_storage', 'memcache', **{ 'key': 'testkey123456789', 'location': ('127.0.0.1:11211', ), }) config.update({ 'cc_store_time': 5 * 60, 'temp_store': core_plugins['temp_storage'].memcache, }) backend_settings = { 'dummypayment': { 'username': 'derp', 'password': 'derp', 'api_key': 'derp', 'url': 'http://derp', }, 'dummygiftcard': { 'username': 'derp', 'password': 'derp', 'api_key': 'derp', 'url': 'http://derp', }, 'dummydebit': { 'username': 'derp', 'password': 'derp', 'api_key': 'derp', 'url': 'http://derp', }, } @step(u'I have an order worth (\d[\.\d]*)\$') def i_have_an_order_worth(step, amount): from shoplifter.payment.lib.test_helpers import TestOrder world.order = TestOrder(decimal.Decimal(amount)) assert_equals(world.order.total, decimal.Decimal('30')) @step(u'I have a backend "([^"]*)" using "([^"]*)"') def prepare_backend(step, backend_name, payment_type): use_pre_auth = payment_type == 'pre-auth' backend_conf = backend_settings[backend_name] backend_conf['use_pre_auth'] = use_pre_auth plugins.load('payment_backends', backend_name, backend_conf) assert backend_name in plugins['payment_backends'] # assert_equals(settings.backends[backend_name].name, backend_name) @step(u'I prepare a payment of (\d[\.\d]*)\$ using "([^"]*)"') def prepare_payment(step, amount, backend_name): amount = decimal.Decimal(amount) backend = plugins['payment_backends'][backend_name] args = TEST_CREDENTIALS[backend_name] payment = backend.prepare_payment( world.order, amount, *args) assert_equals(payment.amount, amount) @step(u'the order balance is (\d[\.\d]*)\$') def the_order_balance_is(step, amount): assert_equals(world.order.balance, decimal.Decimal(amount)) @step(u'the order prepared payment amount is (\d[\.\d]*)\$') def the_order_prepared_payment_amount_is(step, amount): assert_equals(world.order.payment.get_prepared_amount(), decimal.Decimal(amount)) @step(u'the order to prepare payment amount is (\d[\.\d]*)\$') def the_order_to_prepare_payment_amount_is(step, amount): assert_equals(world.order.payment.get_to_prepare_amount(), decimal.Decimal(amount)) @step(u'I process the payments for the order') def and_i_process_the_payments_for_the_order(step): world.order.payment.process_all_payments() assert True @step(u'the order is (not )?prepared') def and_the_order_is_prepared(step, not_bool): assert ((not(not_bool) and world.order.is_prepared) or not_bool and not world.order.is_prepared) @step(u'the captured amount is (\d[\.\d]*)\$') def the_captured_amount_is(step, amount): assert_equals(world.order.payment.get_captured_amount(), decimal.Decimal(amount)) @step(u'Then I capture all authorizations') def then_i_capture_all_authorizations(step): world.order.payment.capture_all_authorizations() assert True @step(u'When the user goes to the bank website to approve the transaction') def when_the_user_goes_to_the_bank_website_to_approve_the_transaction(step): assert False, 'This step must be implemented' @step(u'Then the bank system does a post to the (approval|denied) URL with a transaction ID') def then_the_bank_system_does_a_post_to_the_approval_url_with_a_transaction_id(step): assert False, 'This step must be implemented'
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,181
lesite/Shoplifter
HEAD
/tests/__init__.py
import mongoengine as db def setup(): db.connect('shoplifter_test')
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,182
lesite/Shoplifter
HEAD
/tests/catalog/product_spec.py
# encoding: utf-8 from shoplifter.catalog.product.model import Product from tests.helpers import * from .. import db from .helpers import create_product class ProductSpec(object): def resave(self, **kwargs): "Resave the Product in self.p with some fields changed." for k, v, in kwargs.items(): setattr(self.p, k, v) self.p.save() def setup(self): self.code = 'SHOPTEE' self.name = 'Shoplifter T-Shirt' self.slug = 'shoplifter-t-shirt' Product._test_defaults = dict(name=self.name) create_product(code=self.code) self.p = Product.objects.get(code=self.code) def it_is_identified_by_a_unique_code(self): assert_equal(self.p.code, self.p.id) assert_equal(Product.objects(code=self.code).count(), 1) create_product(code=self.code) assert_equal(Product.objects(code=self.code).count(), 1) assert_raises(db.OperationError, create_product, code=self.code, force_insert=True) def it_must_have_a_code_between_3_and_30_characters_long(self): assert_equal(self.p.code, self.code) # new name for each new saved product, for unique slug names = (str(i) * 3 for i in xrange(10)) assert_invalid(create_product, code=None, name=names.next()) assert_invalid(create_product, code='', name=names.next()) assert_invalid(create_product, code='aa', name=names.next()) create_product(code='aaa', name=names.next()) create_product(code='a'*30, name=names.next()) assert_invalid(create_product, code='a'*31, name=names.next()) def it_must_have_a_name_between_3_and_255_characters_long(self): assert_equal(self.p.name, self.name) assert_invalid(self.resave, name=None) assert_invalid(self.resave, name='') assert_invalid(self.resave, name='aa') assert_invalid(self.resave, name='a'*256) def it_must_have_a_slug_between_3_and_30_characters_long(self): assert_equal(self.p.slug, self.slug) assert_invalid(self.resave, name=None) assert_invalid(self.resave, name='') assert_invalid(self.resave, slug='aa') assert_invalid(self.resave, slug='a'*31) def it_should_auto_generate_slug_from_name_when_slug_is_blank(self): self.resave(slug=None) assert_equal(self.p.slug, self.slug) self.resave(slug='') assert_equal(self.p.slug, self.slug) def it_can_have_a_description(self): assert_equal(self.p.description, None) self.resave(description="some description") assert_equal(self.p.description, "some description") def it_can_have_a_meta_description(self): assert_equal(self.p.meta_description, None) self.resave(meta_description="some meta description") assert_equal(self.p.meta_description, "some meta description") def it_can_have_meta_keywords(self): assert_equal(self.p.meta_keywords, None) self.resave(meta_keywords="meta, keywords") assert_equal(self.p.meta_keywords, "meta, keywords") def it_has_a_static_slugify_method(self): assert_equal(Product.slugify(u"Test Slügify"), 'test-slugify') def teardown(self): Product.objects.delete()
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,183
lesite/Shoplifter
HEAD
/shoplifter/payment/exceptions.py
class LuhnCheckFail(Exception): pass class GatewayTimeOut(Exception): pass class EarlyAuthFail(Exception): pass class AuthorizationAmountTooHigh(Exception): """ TODO: Try to automatically deal with?.. """ pass class RequestError(Exception): pass class GatewayError(Exception): pass class TransactionDeclined(Exception): pass class CSCFail(Exception): pass
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,184
lesite/Shoplifter
HEAD
/shoplifter/payment/backend/modules/__init__.py
from shoplifter.payment.backend.modules.dummy import DummyBackend, \ DummyGiftCardBackend, DummyDebitCardBackend __all__ = ['DummyBackend', 'DummyGiftCardBackend', 'DummyDebitCardBackend']
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,185
lesite/Shoplifter
HEAD
/shoplifter/core/__init__.py
from shoplifter.core.config import PluginHost __all__ = ['plugins', ] plugins = PluginHost('shoplifter', __package__)
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,186
lesite/Shoplifter
HEAD
/tests/catalog/__init__.py
# encoding: utf-8 from shoplifter.catalog.product.model import Product, Variant def setup(): Variant.drop_collection() Product.drop_collection()
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,187
lesite/Shoplifter
HEAD
/tests/core/temp_store_specs.py
# Monkeypatching memcache client to use mockcache instead. import memcache import mockcache memcache.Client = mockcache.Client from shoplifter.core.tempstore import ( TempStore, MemcacheStore, DummyStore) from shoplifter.core.util import Cipher from unittest import TestCase from nose.tools import assert_equals, assert_raises class TempStoreSpecs(TestCase): def setUp(self): self.key = 'testkey123456789' self.store_time = 5 * 60, def get_mstore(self): return MemcacheStore(('127.0.0.1:11211', ), self.key) def get_dstore(self): return DummyStore(None, self.key) def it_fails_when_badly_implemented(self): class SampleStore(TempStore): pass sample = SampleStore('1234567890123456', Cipher) assert_raises(NotImplementedError, sample.get, *(None, )) assert_raises(NotImplementedError, sample.store, *(None, None, None, None)) assert_raises(NotImplementedError, sample.delete, *(None, )) def test_memcache_store(self): key1 = 'testkey1' key2 = 'testkey2' expire = 3600 value = 'testval' store = self.get_mstore() store.store(key1, value, expire) store.store(key2, value, expire, encrypted=True) assert_equals(store.get(key1), value) assert_equals(store.get(key2), value) assert_equals(store.get('nothing'), None) store.delete(key1) assert_equals(store.get(key1), None) def test_dummy_store(self): key1 = 'testkey1' key2 = 'testkey2' expire = 3600 value = 'testval' store = self.get_dstore() store.store(key1, value, expire) store.store(key2, value, expire, encrypted=True) assert_equals(store.get(key1), value) assert_equals(store.get(key2), value) assert_equals(store.get('nothing'), None) store.delete(key1) assert_equals(store.get(key1), None)
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,188
lesite/Shoplifter
HEAD
/shoplifter/payment/backend/modules/dummy_controllers.py
try: from web.core import RESTMethod, Controller from web.core.http import HTTPNotFound except ImportError: enable_controllers = False DummyDebitLookup = None else: enable_controllers = True class DummyDebitController(RESTMethod): def __init__(self, payment, backend, *a, **kw): super(DummyDebitController, *a, **kw) self.backend = backend self.payment = payment def post(self, gateway_transaction_id): self.backend.prepare_payment(self.transaction) class DummyDebitLookup(Controller): def __init__(self, backend, *a, **kw): self.backend = backend super(DummyDebitLookup, self).__init__(*a, **kw) def lookup(self, trn_id, *args): try: transaction = self.backend.payment_class.objects.get( transaction_id=trn_id) return DummyDebitController(transaction, self.backend), args except self.backend.payment_class.DoesNotExist: raise HTTPNotFound
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,189
lesite/Shoplifter
HEAD
/shoplifter/core/util/cipher.py
# encoding: utf-8 from Crypto.Cipher import AES __all__ = ['Cipher'] class Cipher(object): def __init__(self, key): self.key = key def get_cipher(self): """ Returns a Crypto AES Cipher object """ return AES.new(self.key, AES.MODE_CFB) def encrypt(self, data): """ Makes call to encrypt data """ return self.crypt(data, 'encrypt') def decrypt(self, data): """ Makes call to decrypt data """ return self.crypt(data, 'decrypt') def crypt(self, data, call): """ This will encrypt all strings and unicode strings (as strings), it accepts str, unicode, dict, list and tuple TODO: Return unicode instead of str when passing unicode? """ str_func = getattr(self, '_'.join((call, 'string'))) func = getattr(self, call) if isinstance(data, unicode): return str_func(data.encode('utf8')) elif isinstance(data, str): return str_func(data) elif isinstance(data, dict): encrypted_data = {} for k in data.keys(): encrypted_data[k] = func(data[k]) return encrypted_data elif isinstance(data, list): encrypted_data = [] for d in data: encrypted_data.append(func(d)) return encrypted_data elif isinstance(data, tuple): encrypted_data = [] for d in data: encrypted_data.append(func(d)) return tuple(encrypted_data) else: return data def encrypt_string(self, data): """ This is what encrypts strings, called by self.crypt """ cipher = self.get_cipher() return cipher.encrypt(data).encode('hex') def decrypt_string(self, data): """ This is what decrypts strings, called by self.crypt. This always returns unicode data to make it easier on everyone. """ cipher = self.get_cipher() return cipher.decrypt(data.decode('hex')).decode('utf8')
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,190
lesite/Shoplifter
HEAD
/tests/catalog/variant_spec.py
# encoding: utf-8 from nose.tools import * from shoplifter.catalog.product.model import Product, Variant from .. import db from .helpers import create_product, create_variant class VariantSpec(object): def setup(self): self.code = 'SHOPTEE' self.name = 'Shoplifter T-Shirt' Product._test_defaults = dict(name=self.name) create_product(code=self.code) self.p = Product.objects.get(code=self.code) Variant._test_defaults = dict(product=self.p) self.sku1 = 'STRS001' create_variant(product=self.p, sku=self.sku1) self.v = Variant.objects.get(sku=self.sku1) def it_is_identified_by_a_unique_sku(self): assert_equal(self.v.sku, self.v.id) assert_equal(Variant.objects(sku=self.sku1).count(), 1) create_variant(sku=self.sku1) assert_equal(Variant.objects(sku=self.sku1).count(), 1) assert_raises(db.OperationError, create_variant, sku=self.sku1, force_insert=True) def teardown(self): Variant.objects.delete() Product.objects.delete()
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,191
lesite/Shoplifter
HEAD
/shoplifter/catalog/product/model.py
# encoding: utf-8 import mongoengine as db from shoplifter.core import util from shoplifter.catalog.taxonomy.model import Taxonomy class Product(db.Document): code = db.StringField(primary_key=True, min_length=3, max_length=30, unique=True) name = db.StringField(required=True, min_length=3, max_length=255) slug = db.StringField(required=True, min_length=3, max_length=30, unique=True) description = db.StringField() meta_description = db.StringField() meta_keywords = db.StringField() available_on = db.DateTimeField() taxonomies = db.ListField(db.ReferenceField(Taxonomy)) # taxclass # shipclass meta = { 'indexes': ['slug'] } # url # absolute_url # inject the util slugify method as a static method slugify = staticmethod(util.slugify) @classmethod def pre_save(cls, sender, document, **kwargs): if not document.slug: document.slug = cls.slugify(document.name, limit=30) def __repr__(self): return '<Product {} "{}">'.format(self.code, self.slug) # pragma: no cover db.signals.pre_save.connect(Product.pre_save, sender=Product) class Variant(db.Document): product = db.ReferenceField(Product, required=True, reverse_delete_rule=db.DENY) sku = db.StringField(primary_key=True, min_length=3, max_length=100, unique=True)
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,192
lesite/Shoplifter
HEAD
/shoplifter/core/tempstore.py
import memcache from shoplifter.core.util import Cipher class TempStore(object): """ Base class for Temporary Storage backends. Use as template. """ def __init__(self, key, cipher): self.cipher = cipher(key) def get(self, key): raise NotImplementedError def store(self, key, data, time, encrypted=False): raise NotImplementedError def delete(self, key): raise NotImplementedError class DummyStore(TempStore): """ Simple Dummy Store backend that stores data in the dummy_store dictionary. """ dummy_store = {} def __init__(self, location, key, cipher=Cipher): super(DummyStore, self).__init__(key, cipher) def get(self, key): try: data = self.dummy_store[key] except KeyError: return None if data[1]: return self.cipher.decrypt(data[0]) return data[0] def store(self, key, data, time, encrypted=False): if encrypted: to_store = self.cipher.encrypt(data), encrypted else: to_store = data, encrypted self.dummy_store[key] = to_store def delete(self, key): self.dummy_store.pop(key) class MemcacheStore(TempStore): """ This is a working storage backend that works with memcached. This is the recommended one to use for storing sensitive data. * Make sure that your memcached server is protected by a firewall! """ def __init__(self, location, key, cipher=Cipher): super(MemcacheStore, self).__init__(key, cipher) self.client = memcache.Client(location) def get(self, key): data = self.client.get(key) if not data: return None if data[1]: return self.cipher.decrypt(data[0]) return data[0] def store(self, key, data, time, encrypted=False): if encrypted: to_store = self.cipher.encrypt(data), encrypted else: to_store = data, encrypted self.client.set(key, to_store, time) def delete(self, key): self.client.delete(key)
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,193
lesite/Shoplifter
HEAD
/shoplifter/core/config.py
import pkg_resources from marrow.util.bunch import Bunch class PluginHost(object): """ This is used to provide a simple internal API for loading and finding plugins that are advertised as entry points. Note: In the context of this documentation, I refer to 'distributon' any package or collection of packages that has a setup.py and is installed using distribute or setup tools. It can work two ways: 1- Find plugins matching a package name. This is useful if you want to have more than one PluginHost in 1 distribution (for example in shoplifter, there is are shoplifter.core.plugins and shoplifter.payment.plugins) This can be achieved by prefixing the entry point group names with the package name where you intend to have a plugin host instance, *AND* by using the optional "package" argument when instantiating a PluginHost, with the package name that's been prefixed. Example: >>> plugins = PluginHost('shoplifter', 'shoplifter.core') The above will find all installed entry points advertised by any distribution if the group name matches a group that's advertised by 'shoplifter', *IF* the group name is also prefixed by the 'package' argument. Those plugins will be made available in plugin_instance.available_plugins. For example, if you want to create a new "payment_backend" to be used un shoplifter.payment, in your package's setup.py, you should have something like this: >>> entry_points={ >>> 'shoplifter.payment.payment_backends': [ >>> 'my_payment_backend = my_distribution:SomePaymentBackend', >>> ], >>> }, >>> }, Then this payment backend will be available in shoplifter.payment.plugins.available_plugins['payment_backends'] (because it's been instantiated using PluginHost('shoplifter', 'shoplifter.payment') 2- Find all plugins for a distribution. >>> plugins = PluginHost('shoplifter') The above will find all installed entry points with a group name matching a the entry point group names advertised by the distribution. Example, if a distribution's setup.py looks like this: >>> entry_points={ >>> 'rainbow_makers': [ >>> 'colorful_rainbow = my_distribution.rainbow_makers:ColorRainbowMaker', >>> ], >>> }, And the code looks for plugins in PluginHost('my_distribution') Then another project can contribute plugins that will be available in plugins.available_plugins by having an entry_points entry in setup.py with the same group name, example: >>> entry_points={ >>> 'rainbow_makers': [ >>> 'grayscale_rainbow = my_other_distribution.rainbow_makers:GrayScaleRainbowMaker', >>> ], >>> }, """ def __init__(self, distribution, package=None): # Entry points will live in self.available_plugins self.available_plugins = Bunch() # Instantiated plugins will live in self.loaded_plugins self.loaded_plugins = Bunch() # Find entry points. try: self._find_plugins(distribution, package) except pkg_resources.DistributionNotFound: # I am ignoring this exception because it's always raised # before a distribution is installed. pass def __getitem__(self, key): # This allows you to access instantiated plugins using # self['plugin_name'] return self.loaded_plugins[key] def _find_plugins(self, distribution, package=None): """ This populates self.available_plugins """ distribution = pkg_resources.get_distribution(distribution) # First get the distribution group names. for group in distribution.get_entry_map().keys(): if not package: # Otherwise the key for available_plugins and # loaded_plugins is the same than the group name. group_name = group elif not group.startswith(package): # If the group name doesn't start with the supplied # package name, skip the group. continue elif group.startswith(package): # If package name is supplied, trim the package name # from group name, and use that as a key in # self.available_plugins and self.loaded_plugins group_name = group.split(package)[1].strip('.') self.available_plugins[group_name] = Bunch() # Load entry points in plugin dict. for x in pkg_resources.iter_entry_points(group): self.available_plugins[group_name][x.name] = x def load(self, group, plugin_name, *args, **kwargs): """ Load a plugin (calling entry_point.load() and passing *args and **kwargs to loaded plugin. """ # Create a Bunch as self[entry_point.group] if it doesn't yet exist. if group not in self.loaded_plugins: self.loaded_plugins[group] = Bunch() # Instantiate plugin with supplied args and kwargs. self.loaded_plugins[group][plugin_name] = ( self.available_plugins[group][plugin_name].load()( *args, **kwargs)) class Config(Bunch): """ A simple configuration class that can be used to store arbitrary data. """ pass
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,194
lesite/Shoplifter
HEAD
/tests/catalog/taxonomy_specs.py
# encoding: utf-8 import mongoengine as db from nose.tools import * from shoplifter.catalog.taxonomy.model import Taxonomy from shoplifter.catalog.product.model import Product from ludibrio import Stub db.connect('shoplifter_test') with Stub() as get_lang: from shoplifter.core.db.field import get_lang get_lang() >> [u'en', u'se', u'eg'] def _create_products(): men = Taxonomy(name={'en': 'men'}) men.save() women = Taxonomy(name={'en': 'women'}) women.save() m_pants = Taxonomy(name={'en': 'Pants'}, parent=men) m_pants.save() m_tops = Taxonomy(name={'en': 'tops'}, parent=men) m_tops.save() w_pants = Taxonomy(name={'en': 'Pants'}, parent=women) w_pants.save() w_tops = Taxonomy(name={'en': 'tops'}, parent=women) w_tops.save() sales = Taxonomy(name={'en': 'sales'}) sales.save() Product(code='mpants', name='man\'s pants', slug='pants', taxonomies=[m_pants,]).save() Product(code='mtops', name='man\'s tops', slug='tops', taxonomies=[m_tops,]).save() Product(code='mpants-sale', name='man\'s pants on sale', slug='men-pants-sale', taxonomies=[m_pants, sales]).save() Product(code='mtops-sale', name='man\'s tops on sale', slug='men-tops-sale', taxonomies=[m_tops, sales]).save() Product(code='wpants', name='women\'s pants', slug='women-pants', taxonomies=[w_pants,]).save() Product(code='wtops', name='women\'s tops', slug='women-tops', taxonomies=[w_tops,]).save() Product(code='wpants-sale', name='women\'s pants on sale', slug='women-pants-sale', taxonomies=[w_pants, sales]).save() Product(code='wtops-sale', name='women\'s tops on sale', slug='women-tops-sale', taxonomies=[w_tops, sales]).save() def setup(): Product.drop_collection() Taxonomy.drop_collection() _create_products() class TestTaxonomySpec(object): def setup(self): self.men = Taxonomy.objects.get(path=u'/men') self.women = Taxonomy.objects.get(path=u'/women') self.sales = Taxonomy.objects.get(path=u'/sales') def teardown(self): pass def test_simple_taxonomy(self): from mongoengine.document import OperationError pants = Taxonomy.objects(name__en__iexact='pants') assert_true(pants, "The query have return a populated queryset") assert_equal(pants.count(), 2, "The queryset have 2 items") assert_true(pants[0].path != pants[1].path, "The items are unique") pants2 = Taxonomy(name={'en': 'Pants'}, parent=self.men) assert_raises(OperationError, pants2.save) def test_multiple_taxonomies(self): children = Taxonomy.objects.filter(parent=self.men) assert_equal(children.count(), 2, 'The men category have 2 children') def test_union_taxonomies(self): all_prods = Product.objects(self.men | self.women) men_tops = Taxonomy.objects.get(path='/men/tops') men_pants = Taxonomy.objects.get(path='/men/pants') men_prods = set(Product.objects(taxonomies__in=self.men.descendants)) men_prods2 = set(Product.objects(men_pants | men_tops)) assert_equal(all_prods.count(), 8, 'All root taxonomies return all the products') assert_equal(men_prods2, men_prods, 'All children products are equal to parents products') def test_intersect_taxonomies(self): men = set(Product.objects(taxonomies__in=self.men.descendants)) women = set(Product.objects(taxonomies__in=self.women.descendants)) sales = set(Product.objects(taxonomies__in=self.sales.descendants)) no_prods = Product.objects(self.men & self.women) men_sales = Product.objects(self.men & self.sales) assert_equal(set(men & women), set(no_prods), 'disjoint taxonomies provide no products') assert_equal(set(men & sales), set(men_sales), 'parent and child is equal to parents products') def test_substraction_taxonomies(self): men = set(Product.objects(taxonomies__in=self.men.descendants)) sales = set(Product.objects(taxonomies__in=self.sales.descendants)) mens_no_sale = Product.objects(self.men - self.sales) assert_equal(len(men - sales), 2) assert_equal(mens_no_sale.count(), 2) assert_equal((set(mens_no_sale) & (men - sales)), set(mens_no_sale)) assert_true(not set(self.sales).intersection(mens_no_sale[0].taxonomies))
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,195
lesite/Shoplifter
HEAD
/setup.py
#!/usr/bin/env python # encoding: utf-8 import os import sys from setuptools import setup, find_packages if sys.version_info < (2, 6): raise SystemExit("Python 2.6 or later is required.") setup( name = "shoplifter", version = '0.0.2', description = 'Shoplifter e-Commerce', author = 'Le Site, Inc', author_email = '', url = "http://github.com/lesite/Shoplifter", license = 'LGPL', install_requires = [ 'mongoengine', 'blinker', 'marrow.util', 'pycrypto', 'python-memcached', 'webcore', ], test_suite='nose.collector', tests_require = [ 'nose', 'coverage', 'pinocchio==0.2', 'mockcache', 'ludibrio', ], dependency_links = [ 'https://github.com/lesite/mongoengine/tarball/master#egg=mongoengine', 'https://github.com/unpluggd/pinocchio/tarball/0.2#egg=pinocchio-0.2', ], packages = find_packages(exclude=['examples', 'tests', 'features']), zip_safe = True, include_package_data = True, package_data = {'': ['README.textile', 'LICENSE']}, namespace_packages=['shoplifter'], entry_points={ 'shoplifter.core.temp_storage': [ 'memcache = shoplifter.core.tempstore:MemcacheStore', 'dummy = shoplifter.core.tempstore:DummyStore', ], 'shoplifter.payment.payment_backends': [ 'dummypayment = shoplifter.payment.backend.modules:DummyBackend', 'dummygiftcard = shoplifter.payment.backend.modules:DummyGiftCardBackend', 'dummydebit = shoplifter.payment.backend.modules:DummyDebitCardBackend', ], }, classifiers = [ "Development Status :: 1 - Planning", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", # TODO: Python 3 "Topic :: Software Development :: Libraries :: Python Modules", ] )
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,196
lesite/Shoplifter
HEAD
/tests/core/test_config.py
from shoplifter.core.config import PluginHost from unittest import TestCase from ..helpers import * class PluginSpecs(TestCase): def can_load_plugins_for_package(self): # Load plugins for a package part of a distribution. pls = PluginHost('shoplifter', 'shoplifter.core') assert('temp_storage' in pls.available_plugins.keys()) assert(not 'temp_storage' in pls.loaded_plugins.keys()) # Test loading plugins. pls.load('temp_storage', 'dummy', None, 'asd') assert('temp_storage' in pls.loaded_plugins.keys()) # Check that you can access loaded plugins using dictionary # like syntax. assert_equals( pls['temp_storage'], pls.loaded_plugins['temp_storage']) for key in pls.available_plugins.keys(): group = pls.available_plugins[key] for ep_key in group.keys(): entry_point = group[ep_key] assert(entry_point.module_name.startswith('shoplifter.core')) def can_load_plugins_for_distribution(self): # Load plugins for distribution. pls = PluginHost('shoplifter') assert('shoplifter.core.temp_storage' in pls.available_plugins.keys()) assert(not 'shoplifter.core.temp_storage' in pls.loaded_plugins.keys()) # Test loading plugins. pls.load('shoplifter.core.temp_storage', 'dummy', None, 'asd') assert('shoplifter.core.temp_storage' in pls.loaded_plugins.keys()) # Check that you can access loaded plugins using dictionary # like syntax. assert_equals( pls['shoplifter.core.temp_storage'], pls.loaded_plugins['shoplifter.core.temp_storage']) def it_doesnt_fail_when_distribution_does_not_exist(self): # During installation, the distribution is not yet installed # therefore instantiation of PluginHost should not raise # pkg_resources.DistributionNotFound pls = PluginHost('herp_a_derp') assert_is_instance(pls, PluginHost) assert_equal(len(pls.available_plugins), 0) assert_equal(len(pls.loaded_plugins), 0)
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,197
lesite/Shoplifter
HEAD
/tests/catalog/helpers.py
from shoplifter.catalog.product.model import Product, Variant def create_model(cls, save=True, force_insert=False, **kwargs): opts = getattr(cls, '_test_defaults', {}) opts.update(kwargs) i = cls(**opts) if save: i.save(force_insert=force_insert) return i def create_product(*args, **kwargs): return create_model(Product, *args, **kwargs) def create_variant(*args, **kwargs): return create_model(Variant, *args, **kwargs)
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,198
lesite/Shoplifter
HEAD
/shoplifter/core/util/__init__.py
from .string import force_unicode, slugify from .cipher import Cipher
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,199
lesite/Shoplifter
HEAD
/shoplifter/payment/__init__.py
from shoplifter.core.config import Config, PluginHost __all__ = ['config', 'plugins'] plugins = PluginHost('shoplifter', __package__) config = Config()
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,200
lesite/Shoplifter
HEAD
/shoplifter/core/db/field/__init__.py
#encoding: utf-8 import decimal from mongoengine.fields import DictField, IntField from mongoengine.base import BaseDict class MissingLanguageFunctionError(Exception): pass def get_lang(): # pragma: no cover raise MissingLanguageFunctionError class TranslatedString(BaseDict): def __unicode__(self): langs = get_lang() if isinstance(langs, basestring): return self.get(langs, u"NO TRANSLATION FOUND") else: for lang in langs: if lang in self: return self[lang] return u"NO TRANSLATION FOUND" def __str__(self): return self.__unicode__() class TranslatedStringField(DictField): """ A locale aware string field """ def __init__(self, **kwargs): super(TranslatedStringField, self).__init__(**kwargs) def __get__(self, instance, owner): if instance is None: return self dict_items = instance._data.get(self.name, dict()) trans_str = TranslatedString(dict_items, instance, self.name) return trans_str class MoneyField(IntField): """ This is actually an integer field that stores the number of cents. This can be used when we need to store precise money amounts that cannot afford to lose precision. Pros: This supports database operations like sum """ def __init__( self, min_value=None, max_value=None, decimal_digits=2, **kwargs): self.min_value, self.max_value, self.decimal_digits = \ min_value, max_value, decimal_digits super(MoneyField, self).__init__(**kwargs) def aggregate_to_python(self, value): return self.to_python(value) def to_python(self, value): return decimal.Decimal(str(value)) / (10 ** self.decimal_digits) def to_mongo(self, value): return int( (value * (10 ** self.decimal_digits)).to_integral())
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,201
lesite/Shoplifter
HEAD
/shoplifter/catalog/taxonomy/model.py
# encoding: utf-8 import operator import mongoengine as db from shoplifter.core import util from shoplifter.core.db.field import TranslatedStringField class Taxonomy(db.Document): """ The model will help the categorization of products The taxonomy can up and down using it's self as a reference point Using set theory we could create a new set of products (pants | tops) we want products that either pants or tops (pants & sale) we want products that are pants and on sale (pants - sale) we want products that are pants and not on sale """ id = db.ObjectIdField('_id') name = TranslatedStringField(required=True) description = TranslatedStringField() path = db.StringField(unique=True) parent = db.ReferenceField('self') parents = db.ListField(db.ReferenceField('self'), default=list) meta = { 'indexes': ['path'] } @property def descendants(self): """ Returns all children of self including self """ return Taxonomy.objects(path__startswith=self.path) @classmethod def pre_save(cls, sender, document, **kwargs): slug = util.slugify(document.name['en'], limit=30) # TODO: # If name is dirty, update path of all descendants! if document.parent: document.parents = document.parent.parents + [document.parent] document.path = document.parent.path + u'/' + slug else: document.parents = [] document.path = u'/' + slug def __repr__(self): return '<Taxonomy {} "{}">'.format(self.path, self.name) # pragma: no cover def __or__(self, other): """ Return query components that find products in either self or other taxonomy """ taxonomies = ([self] + list(self.descendants.only('id')) + [other] + list(other.descendants.only('id'))) return db.Q(taxonomies__in=taxonomies) def __and__(self, other): """ Return query components that find products contained in both self and other taxonomy. """ ours = list(self.descendants) theirs = list(other.descendants) query = db.Q(taxonomies__in=ours) & db.Q(taxonomies__not__nin=theirs) return query def __sub__(self, other): """ Return query components that find products contained in self and not other taxonomy. """ ours = list(self.descendants) theirs = list(other.descendants) query = db.Q(taxonomies__in=ours) & db.Q(taxonomies__nin=theirs) return query db.signals.pre_save.connect(Taxonomy.pre_save, sender=Taxonomy)
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,202
lesite/Shoplifter
HEAD
/shoplifter/payment/api.py
import decimal from mongoengine import Q from shoplifter.payment import plugins """ TODO: Uses another keyword than store? Was suggested 'set' for method name but will it not override native set object type? """ __all__ = ('DummyStore', 'MemcacheStore') class PayableOrder(object): @property def payment(self): """ This may need to be refactored to some extent... but basically, this returns an OrderHelper object that is then used to make various queries when given an order instance. """ # Check if it's bee initialized. if not hasattr(self, '_payment_initialized'): self._payment = OrderApi(self) self._payment_initialized = True # Return instance. return self._payment @property def balance(self): return self.payment.get_balance() @property def is_prepared(self): return self.payment.is_prepared() class OrderApi(object): """ This is the type of object returned by order.payment. This allows to make various queries to the payment system. TODO: Change name... not OrderHelper, not querying.py.""" def __init__(self, order): self.order = order def get_payments(self, *a, **kw): """ This returns payments matching self.order.id. Any parameters passed as keyword arguments or arguments will be passed to the mongodb query. """ # TODO: Maybe set a get_payment method for each backend? Or # find way to make this more efficient? payments = [] backends = plugins['payment_backends'] for k in backends.keys(): payments += list( backends[k].payment_class.objects.filter( order_id=self.order.id, backend_key=k, *a, **kw)) return payments def get_payment_sum(self, *a, **kw): """ This is a wrapper for self.get_payments that aggregates the sum of 'amount' for the query. """ # TODO: Maybe set a get_payment_sum method for each backend? Or # find way to make this more efficient? Howto? payment_sum = decimal.Decimal(0) backends = plugins['payment_backends'] for k in backends.keys(): payments = backends[k].payment_class.objects.filter( order_id=self.order.id, backend_key=k, *a, **kw) payment_sum += payments.sum('amount') return payment_sum def get_paid_for_amount(self): """ Returns the sum of all payments that have been successfully processed against the payment gateway. """ return self.get_payment_sum(processed=True, success=True) def get_prepared_amount(self): """ Returns the sum of all payments that have not yet been processed against payment gateway. """ return self.get_payment_sum(processed=False) def get_captured_amount(self): """ Returns the cumulated payment amounts for payments that have been captured; an authorization needs post-capture, but a purchase transaction needs only to be processed to capture the funds. You shouldn't to call this other than to debug. """ def reduce_captured_amount(s, payment): # TODO: I think this operation should be done with # MongoDB instead of python. Think about it. if payment.backend.use_pre_auth: increment = decimal.Decimal(0) \ if not payment.authorization_capture \ else payment.authorization_capture.amount return s + increment else: return s + payment.amount payments = self.get_payments(processed=True, success=True) return reduce(reduce_captured_amount, payments, decimal.Decimal(0)) def get_prepared_and_processed_payment_amount(self): """ Returns the sum of all payments that have been successfully processed, plus the sum of those that have not yet been processed, but are prepared. """ return self.get_payment_sum( Q(processed=False) | Q(processed=True, success=True)) def get_balance(self): """ Balance returns the difference between self.order.total and the total amount of payments that have been successfully been processed. """ return (self.order.total - self.get_paid_for_amount()) def get_to_prepare_amount(self): """ Returns how much more to prepare payments for. Basically, similar to balance, except it also takes into account the unprocessed payments. """ return (self.order.total - self.get_prepared_and_processed_payment_amount()) def is_prepared(self): """ Whether or not the payment sum, including prepared and sucessfully processed payments is equal to self.order.total. """ return self.get_to_prepare_amount() == decimal.Decimal('0') def process_all_payments(self): """ TODO: Exception Handling """ payments = self.get_payments(processed=False) payments = sorted(payments, key=lambda x: x.processing_order) for payment in payments: payment.process() def capture_all_authorizations(self, force_capture=False): """ TODO: Exception Handling """ payments = self.get_payments(processed=True) payments = sorted(payments, key=lambda x: x.processing_order) for p in payments: if p.backend.use_pre_auth: capture = p.authorization_capture if not capture or (capture and not capture.processed): p.capture(force=force_capture)
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,203
lesite/Shoplifter
HEAD
/shoplifter/payment/lib/test_helpers.py
import random from mongoengine import Document from shoplifter.payment.api import PayableOrder class DummyAddress(object): """ A dummy Address. """ first_name = 'Benoit' last_name = 'C. Doe' email = 'bendoe@example.com' phone_number = '5146593328' street_number = '55' street_name = 'Derpy' street_type = 'Ave' unit_number = '730' street_direction = 'W' street_line_2 = 'rr 2' postal_code = 'H2T1N6' city = 'Montreal' province = 'QC' country = 'CA' class TestOrder(PayableOrder): """ This is basically, over time, making assumptions on some of order's behaviours and attributes, though it's only used for testing here. """ # TODO # Maybe this whould be a "Payable" interface of some # sort.. and orders can subclass the main class. def __init__(self, total): self.total = total self.id = str(random.randint(99999, 10000000)) super(TestOrder, self).__init__() billing = DummyAddress() shipping = DummyAddress()
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,204
lesite/Shoplifter
HEAD
/tests/helpers.py
# encoding: utf-8 import mongoengine as db import functools from nose.tools import * assert_invalid = functools.partial(assert_raises, db.ValidationError) def assert_is_instance(inst, cls): assert_true(isinstance(inst, cls), u"{inst} is not of type {cls}".format(inst=inst, cls=cls))
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,205
lesite/Shoplifter
HEAD
/tests/core/db/field/test_translated_text.py
# encoding: utf-8 from nose.tools import * import mongoengine as db from shoplifter.core.db.field import TranslatedStringField from shoplifter.core.db.field import TranslatedString from shoplifter.core.db.field import MissingLanguageFunctionError from shoplifter.core.db import field from mongoengine import * from mongoengine.base import ValidationError from ludibrio import Stub class TranslatedDoc(db.Document): text = TranslatedStringField() translated_string = dict( se=u'Detta är svenska', en=u'This is English', eg=u'هذه هي اللغة العربية', ) def setup(): TranslatedDoc.drop_collection() doc = TranslatedDoc(text=translated_string) doc.save() class TestTanslatedTextOperations(object): def setUp(self): with Stub() as get_lang: from shoplifter.core.db.field import get_lang get_lang() >> [u'en', u'se', u'eg'] def test_default_values(self): doc = TranslatedDoc.objects.all()[0] assert_equal(unicode(doc.text), translated_string['en']) assert_true(isinstance(TranslatedDoc.text, TranslatedStringField)) def test_query_translated_string(self): en = TranslatedDoc.objects(text__en=u'This is English') se = TranslatedDoc.objects(text__se__exists=True) assert_true(en.count() == 1) assert_true(se.count() == 1) def test_query_translated_string_not_found(self): fr = TranslatedDoc.objects(text__fr__exists=True) assert_true(fr.count() == 0) def test_valide_translated_string(self): with Stub() as get_lang: from shoplifter.core.db.field import get_lang get_lang() >> 'fr' doc = TranslatedDoc.objects.all()[0] assert_true(isinstance(doc.text, TranslatedString)) assert_equal(doc.text['se'], translated_string['se']) assert_equal(str(doc.text), u"NO TRANSLATION FOUND") with Stub() as get_lang: from shoplifter.core.db.field import get_lang get_lang() >> ['fr', 'gr'] assert_equal(unicode(doc.text), u"NO TRANSLATION FOUND")
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,206
lesite/Shoplifter
HEAD
/shoplifter/payment/backend/__init__.py
__import__('pkg_resources').declare_namespace(__name__) from shoplifter.payment.models import Authorization, Addressee, \ AVSData, Payment, AuthorizationCapture from shoplifter.payment.lib.credentials import CreditCard class BaseBackend(object): """ This is the base class for Backends. If you write a backend, it will be easier if your backend inherits from this class. """ credential_class = CreditCard addressee_class = Addressee payment_class = Payment avs_class = AVSData name = 'basebackend' def __init__(self, configuration): """ This should initialize the API connections """ self.use_pre_auth = configuration['use_pre_auth'] if self.use_pre_auth: self.payment_class = Authorization def gen_transaction_id(self, order_id, prefixes=[]): """This returns an order_id that's built using the prefixes, the order_id and the transaction count.""" capture_class = self.payment_class.get_capture_class() prefix = '_'.join(prefixes) count = ( self.payment_class.objects.filter(order_id=order_id).count()) # There should only be a capture class if this is an Authorization. if capture_class: count += ( capture_class.objects.filter(order_id=order_id).count()) trn_id = '%s_%s_%s_%d' % ( self.name, prefix, str(order_id), count) return trn_id def purchase(self, payment): raise NotImplementedError def authorize(self, authorization): raise NotImplementedError def confirm(self, authorization, amount=None, force=False): raise NotImplementedError def cancel(self, authorization): raise NotImplementedError def refund(self, payment): raise NotImplementedError class CaptureAlreadyExists(Exception): """ This is raised when an authorizatioin capture already exists for a given authorization. """ class WaitedTooLong(Exception): """ This is raised when a payment credential cannot be found in temp storage. """ pass
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,207
lesite/Shoplifter
HEAD
/shoplifter/payment/lib/credentials.py
import shoplifter.payment from shoplifter.payment import config class PaymentCredential(object): class CardFormatError(Exception): pass def is_luhn_valid(self): """ This checks that the CC number validates against the luhn algorithm. Code taken from http://en.wikipedia.org/wiki/Luhn_algorithm """ num = map(int, self.number) return sum(num[::-2] + [ sum(divmod(d * 2, 10)) for d in num[-2::-2]]) % 10 == 0 @staticmethod def get(transaction_id): raise NotImplementedError def save(self): raise NotImplementedError class GiftCard(PaymentCredential): """ This is used to store gift card credentials. """ def __init__(self, transaction_id, number): self.transaction_id = str(transaction_id) self.number = number @staticmethod def get(transaction_id): gc = config.temp_store.get(transaction_id) if not gc: return None return GiftCard( transaction_id, gc['number'], ) def save(self): to = config.cc_store_time key = self.transaction_id gc = { 'number': self.number, } config.temp_store.store(key, gc, to, encrypted=True) class CreditCard(PaymentCredential): """ This is the CreditCard class definition. It's not a mongoengine data model but rather it stores its data encrypted in the tempstore, hence the need for tempstore to be both secure and temporary. Make sure that all arguments passed to constructor are strings or unicode strings, except store which needs to be a temp store implementing shoplifter.payment.core.ITempStore. """ def __init__(self, transaction_id, number, exp_year=None, exp_month=None, csc=None, cc_type=None): self.transaction_id = str(transaction_id) self.number = number self.exp_month = exp_month self.exp_year = exp_year self.csc = csc # Note: Amex is 4 digits. self.cc_type = cc_type if not self.is_luhn_valid(): raise self.CardFormatError( 'Credit card number format fails luhn check') @staticmethod def get(transaction_id): cc = config.temp_store.get(transaction_id) if not cc: return None return CreditCard( transaction_id, cc['number'], cc['exp_month'], cc['exp_year'], cc['csc'], cc['cc_type'], ) def save(self): to = config.cc_store_time key = self.transaction_id cc = { 'number': self.number, 'exp_month': self.exp_month, 'exp_year': self.exp_year, 'csc': self.csc, 'cc_type': self.cc_type, } config.temp_store.store(key, cc, to, encrypted=True) class DebitCard(PaymentCredential): """ """ def __init__(self, transaction_id, number): self.transaction_id = str(transaction_id) self.number = number if not self.is_luhn_valid(): raise self.CardFormatError( 'Credit card number format fails luhn check') @staticmethod def get(transaction_id): dc = config.temp_store.get(transaction_id) if not dc: return None return DebitCard( transaction_id, dc['number'], ) def save(self): to = config.cc_store_time key = self.transaction_id dc = { 'number': self.number, } config.temp_store.store(key, dc, to, encrypted=True)
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,643,208
lesite/Shoplifter
HEAD
/tests/core/db/field/money_field_spec.py
import decimal import mongoengine from ....helpers import assert_is_instance from nose.tools import assert_equals from shoplifter.core.db.field import MoneyField class HongZhiBi(mongoengine.Document): """ Default 2 digit precision """ value = MoneyField() class FiveDecPlacesDoc(mongoengine.Document): """ Bigger precision """ value = MoneyField(decimal_digits=5) class MoneyFieldSpec(object): def get_db(self): return mongoengine.connection._get_db() def get_original(self, mongoengineobj, coll): return self.get_db()[coll].find_one(id=mongoengineobj.id) def it_takes_in_decimal_but_stores_integer(self): doc = HongZhiBi() doc.value = decimal.Decimal('100') doc.save() orig = self.get_original(doc, 'hong_zhi_bi') assert_equals(orig['value'], 100 ** 2) def it_returns_decimal(self): doc = HongZhiBi() doc.value = decimal.Decimal('100') doc.save() doc.reload() assert_is_instance(doc.value, decimal.Decimal) def its_decimal_place_is_configurable(self): doc = FiveDecPlacesDoc() doc.value = decimal.Decimal('100.12345') doc.save() doc.reload() orig = self.get_original(doc, 'five_dec_places_doc') assert_equals(doc.value, decimal.Decimal('100.12345')) assert_equals(orig['value'], 10012345)
{"/shoplifter/catalog/product/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/catalog/taxonomy/model.py"], "/tests/catalog/__init__.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/payment/backend/modules/dummy.py": ["/shoplifter/payment/lib/credentials.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy_controllers.py"], "/tests/core/util/string_examples.py": ["/shoplifter/core/util/__init__.py", "/tests/helpers.py"], "/tests/payment/credential_spec.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/credentials.py"], "/tests/payment/api_spec.py": ["/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py", "/shoplifter/payment/__init__.py", "/shoplifter/payment/models.py", "/shoplifter/payment/backend/__init__.py", "/shoplifter/payment/backend/modules/dummy.py"], "/tests/core/util/cipher_specs.py": ["/shoplifter/core/util/__init__.py"], "/shoplifter/payment/models.py": ["/shoplifter/core/db/field/__init__.py", "/shoplifter/payment/__init__.py"], "/features/steps.py": ["/shoplifter/payment/__init__.py", "/shoplifter/core/__init__.py", "/shoplifter/payment/lib/test_helpers.py"], "/tests/catalog/product_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/helpers.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/payment/backend/modules/__init__.py": ["/shoplifter/payment/backend/modules/dummy.py"], "/shoplifter/core/__init__.py": ["/shoplifter/core/config.py"], "/tests/core/temp_store_specs.py": ["/shoplifter/core/tempstore.py", "/shoplifter/core/util/__init__.py"], "/tests/catalog/variant_spec.py": ["/shoplifter/catalog/product/model.py", "/tests/__init__.py", "/tests/catalog/helpers.py"], "/shoplifter/core/tempstore.py": ["/shoplifter/core/util/__init__.py"], "/tests/catalog/taxonomy_specs.py": ["/shoplifter/catalog/taxonomy/model.py", "/shoplifter/catalog/product/model.py", "/shoplifter/core/db/field/__init__.py"], "/tests/core/test_config.py": ["/shoplifter/core/config.py", "/tests/helpers.py"], "/tests/catalog/helpers.py": ["/shoplifter/catalog/product/model.py"], "/shoplifter/core/util/__init__.py": ["/shoplifter/core/util/string.py", "/shoplifter/core/util/cipher.py"], "/shoplifter/payment/__init__.py": ["/shoplifter/core/config.py"], "/shoplifter/catalog/taxonomy/model.py": ["/shoplifter/core/__init__.py", "/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/api.py": ["/shoplifter/payment/__init__.py"], "/shoplifter/payment/lib/test_helpers.py": ["/shoplifter/payment/api.py"], "/tests/core/db/field/test_translated_text.py": ["/shoplifter/core/db/field/__init__.py"], "/shoplifter/payment/backend/__init__.py": ["/shoplifter/payment/models.py", "/shoplifter/payment/lib/credentials.py"], "/shoplifter/payment/lib/credentials.py": ["/shoplifter/payment/__init__.py"], "/tests/core/db/field/money_field_spec.py": ["/tests/helpers.py", "/shoplifter/core/db/field/__init__.py"]}
39,674,974
jjh2613/django-restapi-test
refs/heads/master
/springproject/apiServer/urls.py
from django.urls import path from . import views app_name = 'apiServer' urlpatterns = [ path('', views.SampleDataView.as_view()), path('/<int:datum_id>', views.SampleDataView.as_view()), ]
{"/springproject/apiServer/views.py": ["/springproject/apiServer/serializers.py"]}
39,674,975
jjh2613/django-restapi-test
refs/heads/master
/springproject/apiServer/views.py
from rest_framework import views, response, permissions, status from .models import SampleData from .serializers import SampleDataSerializer # Create your views here. # REST API 로 구성해보자. class SampleDataView(views.APIView): def get(self, request, **kwargs): datum_id = kwargs.get('datum_id') serializer = SampleDataSerializer if datum_id is None: serializer = SampleDataSerializer(SampleData.objects.all(), many=True) else: serializer = serializer(SampleData.objects.get(id=datum_id)) return response.Response(serializer.data, status=status.HTTP_200_OK) def post(self, request): serializer = SampleDataSerializer(data=request.data) if(serializer.is_valid()): serializer.save() # serializer 에서 저장을 그냥 때려버리는구나 return response.Response(serializer.data, status=status.HTTP_201_CREATED) else: return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def put(self, request, **kwargs): datum_id = kwargs.get('datum_id') if datum_id is None: return response.Response("invalid requests", status=status.HTTP_400_BAD_REQUEST) else: # 정말 직관적이지 않은 update 방식인데...? # Serialzer 란 hibernate 의 entity manager 이자 object mapper 이냐? serializer = SampleDataSerializer(SampleData.objects.get(id=datum_id), data=request.data) if serializer.is_valid(): serializer.save() return response.Response(serializer.data, status=status.HTTP_200_OK) else: return response.Response("invalid requests", status=status.HTTP_400_BAD_REQUEST) def delete(self, request, **kwargs): datum_id = kwargs.get('datum_id') if datum_id is None: return response.Response("invalid requests", status=status.HTTP_400_BAD_REQUEST) else: SampleData.objects.get(id=datum_id).delete() return response.Response("invalid requests", status=status.HTTP_200_OK)
{"/springproject/apiServer/views.py": ["/springproject/apiServer/serializers.py"]}
39,674,976
jjh2613/django-restapi-test
refs/heads/master
/springproject/api/views.py
from django.shortcuts import render from api.forms import Form from api.models import Article # Create your views here. def write(request): if request.method == 'POST': form = Form(request.POST) if(form.is_valid()): form.save() else: form = Form() return render(request, 'write.html', {'form': form}) def list(request): articleList = Article.objects.all() return render(request, "list.html", {'articleList': articleList}) def one(request, num): article = Article.objects.get(id=num) return render(request, "getone.html", {'article': article})
{"/springproject/apiServer/views.py": ["/springproject/apiServer/serializers.py"]}
39,724,113
jesiqueira/script_logof_session_login_servidor
refs/heads/master
/buscar_login.py
import subprocess import csv import os lista_servidores = os.path.join('csv','lista_servidores.csv') pessoas_session = os.path.join('csv', 'pessoas_session.csv') session = os.path.join('file','session.txt') with open(lista_servidores) as entrada: for servidor in csv.reader(entrada): servidores = [int(i) for i in servidor] # percorrer todos os servidores da lista e pegar os logins dos colaboradores que estão com session no servidor, após isso salvar dados desse colaboradores no arquivo session.txt for lista in servidores: with open(session, 'a+') as saida: list_files = subprocess.run(['query', 'session', f"/server:vbr001vdi-{lista}"], capture_output=True, text=True) stdout = f"servidor {lista}\n" + list_files.stdout.strip() print(stdout, file=saida) # Tradar arquivo session.txt e transformar em um arquivo csv para facilitar leitura do arquivo. with open(session) as list_session: with open(pessoas_session, 'w') as saida: for texto in list_session: if "servidor" in texto: servidor = texto[-5::] temp =texto[19:-30] nome = temp[:10] id = temp[-9:] if not "SERNAME" in nome and nome.strip(" "): print('{}, {}, {}'.format(nome.strip(), id.strip(), servidor.strip()), file=saida)
{"/main.py": ["/util/utilitarios.py", "/client/funcionario.py"]}
39,724,114
jesiqueira/script_logof_session_login_servidor
refs/heads/master
/util/utilitarios.py
import os def criar_diretorio(diretorio): CSV_DIR = os.path.join(diretorio, "csv") FILE_DIR = os.path.join(diretorio, "file") if not os.path.isdir(CSV_DIR): os.mkdir(CSV_DIR) if not os.path.isdir(FILE_DIR): os.mkdir(FILE_DIR)
{"/main.py": ["/util/utilitarios.py", "/client/funcionario.py"]}
39,724,115
jesiqueira/script_logof_session_login_servidor
refs/heads/master
/client/teste1.py
import os user = os.environ.get('SENHA_DEFAULT') print(user)
{"/main.py": ["/util/utilitarios.py", "/client/funcionario.py"]}
39,724,116
jesiqueira/script_logof_session_login_servidor
refs/heads/master
/main.py
from util.utilitarios import criar_diretorio from client.funcionario import Funcionario import os f = Funcionario() f.criar_diretorio(os.getcwd()) opcao = 0 while opcao != 3: print("======================== Escolha Opção =====================") print('1 - Carregar Base de Dados') print('2 - Realizar Logoff') print('3 - Sair') print('4 - Teste') opcao = int(input('Informe sua escolha: ')) if opcao == 1: os.system('cls') f.carraga_dados_servidor('jesiqueira') elif opcao == 2: os.system('cls') login = input('Informe o Login para realizar logof: ') f.logof(login.strip().lower(), 'jesiqueira') os.system('cls') elif opcao == 3: os.system('cls') print('Você saiu') else: os.system('cls') print('Opção selecionada não é Válida')
{"/main.py": ["/util/utilitarios.py", "/client/funcionario.py"]}
39,724,117
jesiqueira/script_logof_session_login_servidor
refs/heads/master
/client/teste.py
def recursao(numero, lista): if numero == 0: print('Ultimo') return True else: continuar = int(input('continuar digite 1: ')) if continuar == 1: print(lista[numero-1]) del lista[numero-1] recursao(numero -1, lista) else: return False lista = range(10) ni = recursao(len(lista), lista)
{"/main.py": ["/util/utilitarios.py", "/client/funcionario.py"]}
39,724,118
jesiqueira/script_logof_session_login_servidor
refs/heads/master
/client/funcionario.py
import os import csv import subprocess from datetime import datetime import concurrent.futures class Funcionario: def criar_diretorio(self, diretorio): CSV_DIR = os.path.join(diretorio, "csv") FILE_DIR = os.path.join(diretorio, "file") if not os.path.isdir(CSV_DIR): os.mkdir(CSV_DIR) if not os.path.isdir(FILE_DIR): os.mkdir(FILE_DIR) def carraga_dados_servidor(self, login_admin): namefileServidoresCSV = 'lista_servidores.csv' if self._calcTimeCrieteFile(login_admin) > 5: self._remover_file(login_admin) self._create_file_user_servidor(namefileServidoresCSV, login_admin) else: print(f'Arquivo já existe e foi criado tem menos de { self._calcTimeCrieteFile(login_admin)} minutos') opcao = input("Deseja atualizar arquivo agora? Precione 'S/N': ") if opcao.lower() == 's': os.system('cls') print('Carregando Dados.......') self._remover_file(login_admin) self._create_file_user_servidor(namefileServidoresCSV, login_admin) os.system('cls') print('Dados Atualizados') else: print('Opção deseja é não!') def _create_file_user_servidor(self, namefileServidoresCSV, login_admin): print('Carregando Dados') list_server_csv = os.path.join("csv", namefileServidoresCSV) file_people = os.path.join("csv", login_admin + "_analista.csv") file_session = os.path.join("file", login_admin + "_session.txt") lista = [] with open(list_server_csv) as entrada: for servidor in csv.reader(entrada): for i in servidor: dados = {} dados['servidor'] = i dados['path'] = file_session lista.append(dados) # percorrer todos os servidores da lista e pegar os logins dos colaboradores que estão com session no servidor, após isso salvar dados desse colaboradores no arquivo session.txt with concurrent.futures.ThreadPoolExecutor() as executor: results = executor.map(self._carregar_dados_user, lista) # Tradar arquivo session.txt e transformar em um arquivo csv para facilitar leitura do arquivo. with open(file_session) as list_session: with open(file_people, 'w') as saida: for texto in list_session: if "servidor" in texto: servidor = texto[-5::] temp =texto[19:-30] nome = temp[:13] id = temp[-9:] if not "SERNAME" in nome and nome.strip(" "): print('{}, {}, {}'.format(nome.strip().lower(), id.strip(), servidor.strip()), file=saida) def _carregar_dados_user(self, lista): servidor, file_session = lista.values() with open(file_session, 'a+') as saida: list_files = subprocess.run(['query', 'session', f"/server:vbr001vdi-{int(servidor)}"], capture_output=True, text=True) stdout = f"servidor {servidor}\n" + list_files.stdout.strip() print(stdout, file=saida) def _realizarLogof(self, lista): _ , id , servidor = lista logof = subprocess.run(['logoff',f'{int(id)}', f'/server:vbr001vdi-{int(servidor)}'], capture_output=True, text=True ) return logof def _buscarLogin(self, login_operador, login_admin): with open(os.path.join('csv', login_admin + '_analista.csv')) as entrada: listaPessoa = [] for pessoa in csv.reader(entrada): if pessoa[0] == login_operador: listaPessoa.append(pessoa) return listaPessoa def logof(self, login_operador, login_admin): listAtendente = self._buscarLogin(login_operador, login_admin) if len(listAtendente) >= 1: print('Realizando Logof, aguarde...') with concurrent.futures.ThreadPoolExecutor() as executor: results = executor.map(self._realizarLogof, listAtendente) os.system('cls') print('Logof realizado com sucesso!\nExcluindo pasta de usuário do $user, por favor, aguarde...') self._deletFileUser(login_operador) else: os.system('cls') print('\nLogin não encontrado\n') os.system('pause') def _remover_file(self, login_admin): try: os.remove(os.path.join("csv", login_admin + "_analista.csv")) os.remove(os.path.join("file", login_admin +"_session.txt")) except FileNotFoundError: pass def _calcTimeCrieteFile(self, login_admin): try: if os.path.isfile(os.path.join("csv", login_admin + "_analista.csv")): data = os.stat(os.path.join('csv', login_admin + '_analista.csv')).st_atime data_anterior = datetime.fromtimestamp(data) data_atual = datetime.now() tempo_decorrido = data_atual - data_anterior minutos = int(tempo_decorrido.seconds / 60) return minutos else: return 1 except FileNotFoundError as e: print('erro ao encontrar arquivo', e) def _deletFileUser(self, user_login): # if exist "\\vbr001vdi-800\users$\%login%" ( rmdir /s /q "\\vbr001vdi-800\users$\%login%" ) if os.path.isdir(os.path.join('//vbr001vdi-800/users$/' + user_login)): servidor = os.path.join('//vbr001vdi-800/users$/'+ user_login) try: return subprocess.run(['rm', '-rf', f'{servidor}']) except ValueError as e: print('erro, ', e) else: print(f'Não foi entrando login: {user_login}')
{"/main.py": ["/util/utilitarios.py", "/client/funcionario.py"]}
39,736,980
blacknoize404/stickNAUTA
refs/heads/master
/src/stickNAUTA/PortalNauta.py
from json import (dump, load) from re import (search) from lxml import (html) from requests import (Session) from requests.utils import (dict_from_cookiejar, cookiejar_from_dict) class PortalNauta(object): __portal_nauta_homepage_url: str = 'https://www.portal.nauta.cu/' __portal_nauta_login_url: str = 'https://www.portal.nauta.cu/user/login' __portal_nauta_user_url: str = 'https://www.portal.nauta.cu/useraaa' __portal_nauta_captcha: str = 'https://www.portal.nauta.cu/captcha' __language: str __session: Session __username: str __password: str __csrf: str __account_data: dict = None def __init__(self, username: str, password: str, lang_english: bool = True): if type(username) is not str: raise TypeError('username must be a str().') elif type(password) is not str: raise TypeError('password must be a str().') if not username.endswith(('@nauta.com.cu', '@nauta.co.cu')): raise ValueError('username is not valid. It must end with @nauta.com.cu or @nauta.co.cu.') self.__username = username self.__password = password self.__language = 'en-en' if lang_english else 'es-es' self.__session = Session() self.__session.headers['User-Agent'] = 'python-requests' response = self.__session.get(f'{self.__portal_nauta_login_url}/{self.__language}') if not response.ok: raise RuntimeError(f'Failed to init session with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') html_tree = html.fromstring(response.text) self.__csrf = html_tree.xpath('//*[@name="csrf"]')[0].value def get_captcha_image(self) -> bytes: response = self.__session.get(self.__portal_nauta_captcha) if not response.ok: raise RuntimeError(f'Failed to get captcha with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') return response.content def submit_captcha(self, captcha: str) -> None: if not type(captcha) is str: raise TypeError('captcha must be a str().') response = self.__session.post(self.__portal_nauta_login_url, { 'csrf': self.__csrf, 'login_user': self.__username, 'password_user': self.__password, 'captcha': captcha, 'btn_submit': '' }) if not response.ok: raise RuntimeError(f'Failed to submit CAPTCHA with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') if response.url == self.__portal_nauta_login_url: main_error = search(r"toastr.error\('<ul><li class=\"msg_error\">(.*)<ul>", response.text) if main_error: derived_errors = search(r"<li class=\"sub-message\">(.*)</li></ul></li></ul>'", response.text) \ .group(1).split('</li><li class="sub-message">') error_description = f'"{derived_errors[0]}"' for error in derived_errors[1:]: error_description += f', "{error}"' raise RuntimeError(f'Failed to submit CAPTCHA code with error: "{main_error.group(1)}", ' f'description: {error_description}.') self.__account_data = {} def recharge_account(self, recharge_code: str) -> None: if not self.__account_data: raise AttributeError('This method is not available until a valid CAPTCHA is submitted!') if not type(recharge_code) is str: raise TypeError('recharge_dode must be a str().') elif not recharge_code.isdigit(): raise ValueError('recharge_code chars must be all digits.') elif not 12 <= len(recharge_code) <= 16: raise ValueError('recharge_code must be between 12 and 16 digits long.') response = self.__session.post(self.__portal_nauta_login_url, { 'csrf': self.__csrf, 'recharge_code': recharge_code, 'btn_submit': '' }) if not response.ok: raise RuntimeError(f'Failed to post recharge code with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') main_error = search(r"toastr.error\('<ul><li class=\"msg_error\">(.*)<ul>", response.text) if main_error: derived_errors = search(r"<li class=\"sub-message\">(.*)</li></ul></li></ul>'", response.text) \ .group(1).split('</li><li class="sub-message">') error_description = f'"{derived_errors[0]}"' for error in derived_errors[1:]: error_description += f', "{error}"' raise RuntimeError(f'Failed to post recharge code with error: "{main_error.group(1)}", ' f'description: {error_description}.') def change_account_password(self, new_password: str) -> None: if not self.__account_data: raise AttributeError('This method is not available until a valid CAPTCHA is submitted!') if not type(new_password) is str: raise TypeError('new_password must be a str().') response = self.__session.post(f'{self.__portal_nauta_user_url}/change_password', { 'csrf': self.__csrf, 'old_password': self.__password, 'new_password': new_password, 'repeat_new_password': new_password, 'btn_submit': '' }) if not response.ok: raise RuntimeError(f'Failed to change password code with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') main_error = search(r"toastr.error\('<ul><li class=\"msg_error\">(.*)<ul>", response.text) if main_error: derived_errors = search(r"<li class=\"sub-message\">(.*)</li></ul></li></ul>'", response.text) \ .group(1).split('</li><li class="sub-message">') error_description = f'"{derived_errors[0]}"' for error in derived_errors[1:]: error_description += f', "{error}"' raise RuntimeError(f'Failed to post recharge code with error: "{main_error.group(1)}", ' f'description: {error_description}.') def change_email_password(self, old_password: str, new_password: str) -> None: if not self.__account_data: raise AttributeError('This method is not available until a valid CAPTCHA is submitted!') if not type(old_password) is str: raise TypeError('old_password must be a str().') elif not type(new_password) is str: raise TypeError('new_password must be a str().') response = self.__session.post(f'{self.__portal_nauta_homepage_url}/email/change_password', { 'csrf': self.__csrf, 'old_password': old_password, 'new_password': new_password, 'repeat_new_password': new_password, 'btn_submit': '' }) if not response.ok: raise RuntimeError(f'Failed to change password code with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') main_error = search(r"toastr.error\('<ul><li class=\"msg_error\">(.*)<ul>", response.text) if main_error: derived_errors = search(r"<li class=\"sub-message\">(.*)</li></ul></li></ul>'", response.text) \ .group(1).split('</li><li class="sub-message">') error_description = f'"{derived_errors[0]}"' for error in derived_errors[1:]: error_description += f', "{error}"' raise RuntimeError(f'Failed to post recharge code with error: "{main_error.group(1)}", ' f'description: {error_description}.') def transfer_balance(self, target_account: str, amount: float): if not self.__account_data: raise AttributeError('This method is not available until a valid CAPTCHA is submitted!') if not type(target_account) is str: raise TypeError('target_account must be a str().') elif not type(amount) is float: raise TypeError('amount must be a float().') if not target_account.endswith(('@nauta.com.cu', '@nauta.co.cu')): raise ValueError('username is not valid. It must end with @nauta.com.cu or @nauta.co.cu.') response = self.__session.post(f'{self.__portal_nauta_user_url}/transfer_balance', { 'csrf': self.__csrf, 'transfer': amount, 'password_user': self.__password, 'id_cuenta': target_account, 'action': 'checkdata' }) if not response.ok: raise RuntimeError(f'Failed to transfer money with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') main_error = search(r"toastr.error\('<ul><li class=\"msg_error\">(.*)<ul>", response.text) if main_error: derived_errors = search(r"<li class=\"sub-message\">(.*)</li></ul></li></ul>'", response.text) \ .group(1).split('</li><li class="sub-message">') error_description = f'"{derived_errors[0]}"' for error in derived_errors[1:]: error_description += f', "{error}"' raise RuntimeError(f'Failed to post recharge code with error: "{main_error.group(1)}", ' f'description: {error_description}.') def get_account_data(self, refresh: bool = True) -> dict: if not self.__account_data: raise AttributeError('This property is not available until a valid CAPTCHA is submitted!') if refresh or not len(self.__account_data.keys()): response = self.__session.get(f'{self.__portal_nauta_user_url}/user_info') if not response.ok: raise RuntimeError(f'Failed to get account info with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') html_tree = html.fromstring(response.text) self.__account_data = { 'username': html_tree.xpath('//*[@id="content"]/div[2]/div/div/div/div[2]/div/p/text()')[0], 'blocking_date': html_tree.xpath('//*[@id="content"]/div[2]/div/div/div/div[3]/div[1]/p/text()')[0], 'elimination_date': html_tree.xpath('//*[@id="content"]/div[2]/div/div/div/div[3]/div[2]/p/text()')[0], 'account_type': html_tree.xpath('//*[@id="content"]/div[2]/div/div/div/div[4]/div[1]/p/text()')[0], 'service_type': html_tree.xpath('//*[@id="content"]/div[2]/div/div/div/div[4]/div[2]/p/text()')[0], 'available_balance': html_tree.xpath('//*[@id="content"]/div[2]/div/div/div/div[5]/div[1]/p/text()')[0], 'remaining_time': html_tree.xpath('//*[@id="content"]/div[2]/div/div/div/div[5]/div[2]/p/text()')[0], 'email_account': html_tree.xpath('//*[@id="content"]/div[2]/div/div/div/div[6]/div/p/text()')[0] } return self.__account_data def get_connection_details(self) -> dict: if not self.__account_data: raise AttributeError('This method is not available until a valid CAPTCHA is submitted!') connection_details = {} response = self.__session.get(f'{self.__portal_nauta_user_url}/service_detail') if not response.ok: raise RuntimeError(f'Failed to get connection details timestamp with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') for timestamp in html.fromstring(response.text).xpath('//*[@name="year_month"]/option'): year_month = timestamp.attrib['value'] connection_details[year_month] = {} response = self.__session.post(f'{self.__portal_nauta_user_url}/service_detail_summary', { 'csrf': self.__csrf, 'year_month': year_month, 'list_type': 'service_detail' }) if not response.ok: raise RuntimeError( f'Failed to get connection details summary with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') summary_data = html.fromstring(response.text).xpath('//*[@class="card-stats-number"]/text()') connection_details[year_month]['connections'] = summary_data[0] connection_details[year_month]['total_time'] = summary_data[1] connection_details[year_month]['total_import'] = summary_data[2] connection_details[year_month]['upload_traffic'] = summary_data[3] connection_details[year_month]['download_traffic'] = summary_data[4] connection_details[year_month]['total_traffic'] = summary_data[5] connection_details[year_month]['all_sessions'] = [] for i in range(1, int(int(connection_details[year_month]['connections']) / 15) + 2): response = self.__session.get(f"{self.__portal_nauta_user_url}/service_detail_list/" f"{year_month}/{connection_details[year_month]['connections']}/{i}") if not response.ok: raise RuntimeError( f'Failed to get all sessions connection details with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') rows = html.fromstring(response.text).xpath('/html/body/div[1]/div/table/tr/td/text()') for j in range(0, len(rows), 6): connection_details[year_month]['all_sessions'].append({ 'start_datetime': rows[j], 'end_datetime': rows[j + 1], 'duration': rows[j + 2], 'upload_traffic': rows[j + 3], 'download_traffic': rows[j + 4], 'import': rows[j + 5], }) return connection_details def get_recharge_details(self) -> dict: if not self.__account_data: raise AttributeError('This method is not available until a valid CAPTCHA is submitted!') recharge_details = {} response = self.__session.get(f'{self.__portal_nauta_user_url}/recharge_detail') if not response.ok: raise RuntimeError(f'Failed to get recharge details timestamp with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') for timestamp in html.fromstring(response.text).xpath('//*[@name="year_month"]/option'): year_month = timestamp.attrib['value'] recharge_details[year_month] = {} response = self.__session.post(f'{self.__portal_nauta_user_url}/recharge_detail_summary', { 'csrf': self.__csrf, 'year_month': year_month, 'list_type': 'service_detail' }) if not response.ok: raise RuntimeError( f'Failed to get recharge details summary with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') summary_data = html.fromstring(response.text).xpath('//*[@class="card-stats-number"]/text()') recharge_details[year_month]['recharges'] = summary_data[0] recharge_details[year_month]['total_import'] = summary_data[1] recharge_details[year_month]['all_recharges'] = [] for i in range(1, int(int(recharge_details[year_month]['recharges']) / 15) + 2): response = self.__session.get(f"{self.__portal_nauta_user_url}/recharge_detail_list/" f"{year_month}/{recharge_details[year_month]['recharges']}/{i}") if not response.ok: raise RuntimeError( f'Failed to get all recharges details with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') rows = html.fromstring(response.text).xpath('/html/body/div[1]/div/table/tr/td/text()') for j in range(0, len(rows), 4): recharge_details[year_month]['all_recharges'].append({ 'datetime': rows[j], 'import': rows[j + 1], 'channel': rows[j + 2], 'type': rows[j + 3] }) return recharge_details def get_transfer_details(self) -> dict: if not self.__account_data: raise AttributeError('This method is not available until a valid CAPTCHA is submitted!') transfer_details = {} response = self.__session.get(f'{self.__portal_nauta_user_url}/transfer_detail') if not response.ok: raise RuntimeError(f'Failed to get transfer details timestamp with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') for timestamp in html.fromstring(response.text).xpath('//*[@name="year_month"]/option'): year_month = timestamp.attrib['value'] transfer_details[year_month] = {} response = self.__session.post(f'{self.__portal_nauta_user_url}/transfer_detail_summary', { 'csrf': self.__csrf, 'year_month': year_month, 'list_type': 'service_detail' }) if not response.ok: raise RuntimeError( f'Failed to get transfer details summary with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') summary_data = html.fromstring(response.text).xpath('//*[@class="card-stats-number"]/text()') transfer_details[year_month]['transfers'] = summary_data[0] transfer_details[year_month]['total_import'] = summary_data[1] transfer_details[year_month]['all_transfers'] = [] for i in range(1, int(int(transfer_details[year_month]['transfers']) / 15) + 2): response = self.__session.get(f"{self.__portal_nauta_user_url}/transfer_detail_list/" f"{year_month}/{transfer_details[year_month]['transfers']}/{i}") if not response.ok: raise RuntimeError( f'Failed to get all transfer details with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') rows = html.fromstring(response.text).xpath('/html/body/div[1]/div/table/tr/td/text()') for j in range(0, len(rows), 3): transfer_details[year_month]['all_transfers'].append({ 'datetime': rows[j], 'import': rows[j + 1], 'target_account': rows[j + 2] }) return transfer_details def get_session_data(self) -> dict: if not self.__account_data: raise RuntimeError('Cannot get session data since user is not logged in. Submit a valid CAPTCHA first!') session_data = { 'username': self.__username, 'cookies': dict_from_cookiejar(self.__session.cookies), } return session_data def set_session_data(self, session_data: dict) -> None: if self.__account_data: raise RuntimeError('Cannot set session data since user is logged in. Submit a valid CAPTCHA first!') required_keys = ['username', 'cookies'] for key in required_keys: if key not in session_data.keys(): raise ValueError(f'session_data kas not required key: \'{key}\'.') if not session_data['username'] == self.__username: raise ValueError('Session data is not for this account.') self.__session.cookies = cookiejar_from_dict(session_data['cookies']) self.__account_data = {} def save_session_data_to_file(self, file_path: str) -> None: with open(file_path, 'w') as file: dump(self.get_session_data(), file) def load_session_data_from_file(self, file_path: str) -> None: with open(file_path, 'r') as file: session_data = load(file) if isinstance(session_data, dict): self.set_session_data(session_data) else: raise ValueError('File does not contain a dict and therefore not a session data.')
{"/src/stickNAUTA/__init__.py": ["/src/stickNAUTA/NautaSession.py", "/src/stickNAUTA/PortalNauta.py"]}
39,736,981
blacknoize404/stickNAUTA
refs/heads/master
/setup.py
from setuptools import (setup, find_packages) with open('README.md', 'r', encoding='utf-8') as file: readme = file.read() with open('requirements.txt', 'r', encoding='utf-8') as file: requirements = [requirement[:-1] if requirement.endswith('\n') else requirement for requirement in file] setup( script_name='setup.py', name='stickNAUTA', version='2.0.0', author='stickM4N', author_email='jcgalindo.jcgh@gmail.com', license='MIT', description='Simple managing interface for ETECSA Nauta.', long_description=readme, long_description_content_type='text/markdown', url='https://github.com/stickM4N/stickNAUTA', project_urls={}, download_url=f'https://pypi.org/project/stickNAUTA', keywords='python nauta etecsa', classifiers=[ 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Internet', 'Topic :: Internet :: WWW/HTTP :: Session', 'Topic :: Internet :: WWW/HTTP :: Site Management' ], install_requires=requirements, package_dir={'': 'src'}, packages=find_packages(where='src'), python_requires='>=3.7', )
{"/src/stickNAUTA/__init__.py": ["/src/stickNAUTA/NautaSession.py", "/src/stickNAUTA/PortalNauta.py"]}
39,736,982
blacknoize404/stickNAUTA
refs/heads/master
/src/stickNAUTA/NautaSession.py
from __future__ import (annotations) from ctypes import (Union) from json import (load, dump) from re import (search) from lxml import (html) from requests import (Session) from requests.utils import (dict_from_cookiejar, cookiejar_from_dict) class NautaSession(object): __nauta_homepage_url: str = 'https://secure.etecsa.net:8443/' __nauta_login_url: str = 'https://secure.etecsa.net:8443/LoginServlet' __nauta_query_url: str = 'https://secure.etecsa.net:8443/EtecsaQueryServlet' __nauta_logout_url: str = 'https://secure.etecsa.net:8443/LogoutServlet' __logged_in: bool = False __user_information: dict = None __language: str __session: Session __username: str __password: str __wlanuserip: str __CSRFHW: str __ATTRIBUTE_UUID: str def __init__(self, username: str, password: str, acquire_user_info: bool = True, lang_english: bool = True) -> None: if type(username) is not str: raise TypeError('username must be a str().') elif type(password) is not str: raise TypeError('password must be a str().') if not username.endswith(('@nauta.com.cu', '@nauta.co.cu')): raise ValueError('username is not valid. It must end with @nauta.com.cu or @nauta.co.cu.') self.__username = username self.__password = password self.__language = 'en_US' if lang_english else 'es_ES' self.__session = Session() response = self.__session.get(self.__nauta_homepage_url) if not response.ok: raise RuntimeError(f'Failed to init session with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') html_tree = html.fromstring(response.text) self.__wlanuserip = html_tree.xpath('//*[@id="wlanuserip"]')[0].value self.__CSRFHW = html_tree.xpath('//*[@name="CSRFHW"]')[0].value if acquire_user_info: response = self.__session.post(self.__nauta_query_url, { 'username': self.__username, 'password': self.__password, 'wlanuserip': self.__wlanuserip, 'CSRFHW': self.__CSRFHW, 'lang': self.__language }) if not response.ok: raise RuntimeError(f'Failed to get user data (credit) with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') alert = search(r'alert\("(?P<_>[^"]*?)"\)', response.text) if alert: raise RuntimeError(f'Failed to get user data (probably related to wrong credentials or ' f'insufficient balance in the account. More info: "{alert.group(1)}"') html_tree = html.fromstring(response.text) account_state = html_tree.xpath('//*[@id="sessioninfo"]/tbody/tr[1]/td[2]/text()')[0][13:-12] credit = html_tree.xpath('//*[@id="sessioninfo"]/tbody/tr[2]/td[2]/text()')[0][13:-13] expiration_date = html_tree.xpath('//*[@id="sessioninfo"]/tbody/tr[3]/td[2]/text()')[0][13:-12] access_areas = html_tree.xpath('//*[@id="sessioninfo"]/tbody/tr[4]/td[2]/text()')[0][13:-12] sessions_data = html_tree.xpath('//*[@id="sesiontraza"]/tbody/tr/td/text()') self.__user_information = { 'account_state': account_state, 'credit': credit, 'expiration_date': expiration_date, 'access_areas': access_areas, 'sessions': [ { 'start': sessions_data[0], 'end': sessions_data[1], 'duration': sessions_data[2] }, { 'start': sessions_data[3], 'end': sessions_data[4], 'duration': sessions_data[5] }, { 'start': sessions_data[6], 'end': sessions_data[7], 'duration': sessions_data[8] } ] } def __enter__(self) -> NautaSession: self.login() return self def __exit__(self, exc_type, exc_val, exc_tb) -> None: self.logout() def login(self) -> None: if self.__logged_in: raise RuntimeError('User is already logged in.') response = self.__session.post(self.__nauta_login_url, { 'username': self.__username, 'password': self.__password, 'wlanuserip': self.__wlanuserip, 'CSRFHW': self.__CSRFHW, 'lang': self.__language }) if not response.ok: raise RuntimeError(f'Login failure with HTTP code: {response.status_code} and reason: "{response.reason}".') if 'online.do' not in response.url: reason = search(r'alert\("(?P<_>[^"]*?)"\)', response.text).group(1) raise RuntimeError(f'Login failure reason: "{reason}".') self.__ATTRIBUTE_UUID = search(r'ATTRIBUTE_UUID=(\w+)&CSRFHW=', response.text).group(1) self.__logged_in = True def logout(self) -> None: if not self.__logged_in: raise RuntimeError('User is not logged in.') response = self.__session.get(f'{self.__nauta_logout_url}?' f'username={self.__username}&' f'wlanuserip={self.__wlanuserip}&' f'CSRFHW={self.__CSRFHW}&' f'ATTRIBUTE_UUID={self.__ATTRIBUTE_UUID}') if not response.ok: raise RuntimeError( f'Logout failure with HTTP code: {response.status_code} and reason: "{response.reason}".') if "SUCCESS" not in response.text: raise RuntimeError(f'Logout failure reason: "{response.text}".') self.__logged_in = False self.__ATTRIBUTE_UUID = str() def get_user_info(self) -> dict: if not self.__user_information: raise AttributeError('NautaSession has no user information since acquire_user_info=False ' 'was passed to __init__.') return self.__user_information def get_remaining_time(self, in_seconds: bool = False) -> Union[str, int]: response = self.__session.post(self.__nauta_query_url, { 'op': 'getLeftTime', 'username': self.__username, 'wlanuserip': self.__wlanuserip, 'CSRFHW': self.__CSRFHW, 'ATTRIBUTE_UUID': self.__ATTRIBUTE_UUID }) if not response.ok: raise RuntimeError( f'Failed to get user data (remaining_time) with HTTP code: {response.status_code}, ' f'reason: "{response.reason}".') remaining_time = response.text if in_seconds: (hours, minutes, seconds) = [int(number) for number in remaining_time.split(':')] remaining_time = hours * 3600 + minutes * 60 + seconds return remaining_time def get_session_data(self) -> dict: if not self.__logged_in: raise RuntimeError('Cannot get session data since user is not logged in.') session_data = { 'username': self.__username, 'cookies': dict_from_cookiejar(self.__session.cookies), 'wlanuserip': self.__wlanuserip, 'CSRFHW': self.__CSRFHW, 'ATTRIBUTE_UUID': self.__ATTRIBUTE_UUID } return session_data def set_session_data(self, session_data: dict) -> None: if self.__logged_in: raise RuntimeError('Cannot set session data since user is logged in.') required_keys = ['username', 'cookies', 'wlanuserip', 'CSRFHW', 'ATTRIBUTE_UUID'] for key in required_keys: if key not in session_data.keys(): raise ValueError(f'session_data kas not required key: \'{key}\'.') if not session_data['username'] == self.__username: raise ValueError('Session data is not for this account.') self.__session.cookies = cookiejar_from_dict(session_data['cookies']) self.__wlanuserip = session_data['wlanuserip'] self.__CSRFHW = session_data['CSRFHW'] self.__ATTRIBUTE_UUID = session_data['ATTRIBUTE_UUID'] self.__logged_in = True def save_session_data_to_file(self, file_path: str) -> None: with open(file_path, 'w') as file: dump(self.get_session_data(), file) def load_session_data_from_file(self, file_path: str) -> None: with open(file_path, 'r') as file: session_data = load(file) if isinstance(session_data, dict): self.set_session_data(session_data) else: raise ValueError('File does not contain a dict and therefore not a session data.')
{"/src/stickNAUTA/__init__.py": ["/src/stickNAUTA/NautaSession.py", "/src/stickNAUTA/PortalNauta.py"]}
39,736,983
blacknoize404/stickNAUTA
refs/heads/master
/src/stickNAUTA/__init__.py
from .NautaSession import (NautaSession) from .PortalNauta import (PortalNauta) __version__ = '2.0.0' __all__ = ['NautaSession', 'PortalNauta'] __author__ = 'stickM4N jcgalindo.jcgh@gmail.com'
{"/src/stickNAUTA/__init__.py": ["/src/stickNAUTA/NautaSession.py", "/src/stickNAUTA/PortalNauta.py"]}
39,856,151
valentinoli/deep-learning-project-1
refs/heads/master
/tuning.py
from helpers import tune_hyperparameters tune_hyperparameters(start=0, end=1)
{"/network.py": ["/network_helpers.py"], "/test.py": ["/network.py", "/helpers.py", "/generate_plot.py"], "/tuning.py": ["/helpers.py"], "/helpers.py": ["/network.py"]}
39,856,152
valentinoli/deep-learning-project-1
refs/heads/master
/network_helpers.py
from __future__ import annotations from torch import nn, tensor, float """Layer helpers""" def conv(in_channels, out_channels, kernel_size = 3, padding = 1): return nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=padding) def pool(kernel_size = 2, stride = 2): return nn.MaxPool2d(2, stride=stride) def linear(in_features, out_features): return nn.Linear(in_features, out_features) def relu(inplace = True): return nn.ReLU(inplace=inplace) def softmax(dim = 1): return nn.Softmax(dim) def sequential(*modules): return nn.Sequential(*modules) """Block helpers""" def block_cnn(): """ Returns a convolutional block with max pooling to learn meaningful representations in MNIST images input dimension: 1 x 14 x 14 output dimension: 64 x 3 x 3 """ return sequential( # 1 x 14 x 14 # -> 32 x 14 x 14 conv(1, 32), # -> 32 x 7 x 7 pool(), # -> 64 x 7 x 7 conv(32, 64), # -> 64 x 3 x 3 pool() ) def block_digit_classifier(hidden_layers: int): """ Returns a fully-connected block for MNIST digit classification input units: 64 * 3 * 3 = 576 output units: 10 """ modules = [ linear(64 * 3 * 3, 100), relu() ] if hidden_layers == 1: modules.extend([ linear(100, 50), relu() ]) elif hidden_layers == 2: modules.extend([ linear(100, 70), relu(), linear(70, 50), relu() ]) else: raise ValueError('Invalid number of hidden layers') # 10 output units, one for each digit classification modules.append(linear(50, 10)) return sequential(*modules) def block_output(): """ Returns a fully-connected block that synthesizes the classification results of the two digits and outputs input units: 20 output units: 1 """ return sequential( linear(20, 10), relu(), linear(10, 2), softmax() ) """Miscallaneous""" def leq(x, y): # mimick prob. distribution for training output = [[0, 1] if (x_ <= y_) else [1, 0] for x_, y_ in zip(x, y)] return tensor(output, dtype=float)
{"/network.py": ["/network_helpers.py"], "/test.py": ["/network.py", "/helpers.py", "/generate_plot.py"], "/tuning.py": ["/helpers.py"], "/helpers.py": ["/network.py"]}
39,856,153
valentinoli/deep-learning-project-1
refs/heads/master
/test.py
import sys from collections import defaultdict import torch import dlc_practical_prologue as prologue from network import NaiveNet, SharedWeightNet, BenchmarkNet from helpers import train_model, compute_accuracy, bootstrapping from generate_plot import performance_plot num_samples = 1000 # Change this parameter to control the number of rounds NUM_ROUNDS = 10 PLOT = True BOOTSTRAP = False # We test five types of nets with appropriate hyper-parameters titles = [ 'Naive network, no weight sharing, 1 hidden layer', 'Siamese network with weight sharing, 1 hidden layer', 'Siamese network with weight sharing, 1 hidden layer and auxiliary loss', 'Siamese network with weight sharing, 2 hidden layers and auxiliary loss', 'Siamese network with weight sharing, 2 hidden layers, auxiliary loss and <= operator' ] hyper_parameters = [ {'learning_rate': 0.0002, 'batch_size': 100, 'lambda_': 0}, {'learning_rate': 0.0005, 'batch_size': 100, 'lambda_': 0}, {'learning_rate': 3.1e-3, 'batch_size': 100, 'lambda_': 0.23}, {'learning_rate': 1.2e-2, 'batch_size': 100, 'lambda_': 0.23}, {'learning_rate': 1.2e-2, 'batch_size': 100, 'lambda_': 0.23} ] with_aux_loss = [False, False, True, True, True] # dicts to collect train and test errors for each model agg_train_results = defaultdict(list) agg_test_results = defaultdict(list) print(f'Running {NUM_ROUNDS} rounds of {len(titles)} models.') print('Change NUM_ROUNDS to control the number of rounds\n') for i in range(NUM_ROUNDS): # reset models in each round models = [ NaiveNet(), SharedWeightNet(), SharedWeightNet(), SharedWeightNet(hidden_layers=2), BenchmarkNet(hidden_layers=2) ] print(f'\n*** Round {i+1}/{NUM_ROUNDS} ***\n') train_input, train_target, train_classes, \ test_input, test_target, test_classes = prologue.generate_pair_sets(num_samples) for title, model, params, auxiliary_loss in zip(titles, models, hyper_parameters, with_aux_loss): print(title) # Train the model using the default number of epochs and batch size train_model(model, train_input, train_target, train_classes, **params, auxiliary_loss=auxiliary_loss) sys.stdout.write('\rTraining complete!\n') # Compute train and test accuracy train_accuracy = compute_accuracy(model, train_input, train_target) test_accuracy = compute_accuracy(model, test_input, test_target) agg_train_results[title].append(train_accuracy) agg_test_results[title].append(test_accuracy) sys.stdout.write(f'\rRound {i+1} finished for all models!\n') print('\n\n#######################\n\n') display_vals = [] for t, p in zip(titles, hyper_parameters): print() print(t) for k, v in p.items(): print(f'{k}: {v}') train_errors = agg_train_results[t] test_errors = agg_test_results[t] if BOOTSTRAP: train_bootstrap = bootstrapping(train_errors, size=1000) test_bootstrap = bootstrapping(test_errors, size=1000) else: train_bootstrap = torch.tensor(train_errors) test_bootstrap = torch.tensor(test_errors) display_vals.append(train_bootstrap) display_vals.append(test_bootstrap) print('Training accuracy: {:.2f}% ± {:.2f}%'.format(train_bootstrap.mean() * 100, test_bootstrap.std() * 100)) print('Test accuracy: {:.2f}% ± {:.2f}%'.format(test_bootstrap.mean() * 100, test_bootstrap.std() * 100)) if PLOT: performance_plot(display_vals, NUM_ROUNDS, BOOTSTRAP)
{"/network.py": ["/network_helpers.py"], "/test.py": ["/network.py", "/helpers.py", "/generate_plot.py"], "/tuning.py": ["/helpers.py"], "/helpers.py": ["/network.py"]}
39,856,154
valentinoli/deep-learning-project-1
refs/heads/master
/helpers.py
from __future__ import annotations import sys import torch from torch import nn, Tensor from network import NaiveNet, SharedWeightNet, BenchmarkNet import dlc_practical_prologue as prologue def create_dataloader(*tensors, batch_size = 10, shuffle = True): """Creates a PyTorch data loader from the given tensors""" dataset = torch.utils.data.TensorDataset(*tensors) dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=shuffle) return dataloader def train_model( model: nn.Module, inputs: Tensor, targets: Tensor, classes: Tensor, learning_rate: float = 1e-2, lambda_: float = 0.1, batch_size: int = 100, epochs: int = 25, auxiliary_loss: bool = False, verbose: bool = True ): """ Trains the given model with SGD with the given number of epochs and batch size """ # Create a data loader to iterate over minibatches loader = create_dataloader(inputs, targets, classes, batch_size=batch_size) # We use cross entropy loss, suitable for the binary classification task criterion = nn.CrossEntropyLoss() # SGD optimizer optim = torch.optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9) for epoch in range(epochs): for inputs_, targets_, classes_ in loader: # Forward pass # -> returns the binary output as well as 10 class predictions for each image output, class_0, class_1 = model(inputs_) loss = criterion(output, targets_) if auxiliary_loss: class_0_target = classes_.select(1, 0) class_1_target = classes_.select(1, 1) loss += lambda_ * (criterion(class_0, class_0_target) + criterion(class_1, class_1_target)) optim.zero_grad() # Back propagation loss.backward() # SGD step optim.step() if verbose: sys.stdout.write(f'\rEpoch {epoch+1}') sys.stdout.flush() @torch.no_grad() def predict(model: nn.Module, inputs: Tensor) -> Tensor: """ :param model: the model :param inputs: input tensor of dimension (N, 2, 14, 14), N is the number of pairs :returns: binary predictions of the model given the inputs """ # Pass the inputs through the model and get as output a tensor # of dimension (N, 2). For each pair we have # a probability distribution over 2 binary outputs outputs, _, _ = model(inputs) # We take the argmax of the two probabilities for each pair predictions = outputs.argmax(dim=1) return predictions def compute_num_correct(predictions: Tensor, targets: Tensor) -> int: """ :param predictions: see predict() return value :param targets: ground truth target values :returns: number of correct predictions """ return (predictions == targets).sum() def compute_accuracy(model: nn.Module, inputs: Tensor, targets: Tensor) -> float: """ :param model: the model :param inputs: input tensor of dimension (N, 2, 14, 14), N is the number of pairs :param targets: ground truth tensor of dimension N :returns: total accuracy """ num_correct = compute_num_correct(predict(model, inputs), targets) accuracy = num_correct / len(targets) return accuracy def compute_num_errors(model: nn.Module, inputs: Tensor, targets: Tensor) -> int: """ :param model: the model :param inputs: input tensor of dimension (N, 2, 14, 14), N is the number of pairs :param targets: ground truth tensor of dimension N :returns: number of incorrect predictions """ num_correct = compute_num_correct(predict(model, inputs), targets) num_errors = len(targets) - num_correct return num_errors def bootstrapping(values: list, size: int = 500) -> Tensor: """ :param values: list of values to bootstrap resample from :param size: number of bootstrap samples :returns: tensor of resampled values """ values = torch.tensor(values, dtype=torch.float) bootstrap_sample_indices = torch.randint(len(values), (size,)) return values[bootstrap_sample_indices] def k_fold_split(num_samples: int, k: int = 4) -> tuple[Tensor]: """ :param num_samples: number of samples :param k: number of folds to split the dataset for cross-validation :returns: k folds of indices """ fold_size = int(num_samples / k) indices_shuffled = torch.randperm(num_samples) indices_split = torch.split(indices_shuffled, fold_size) return indices_split def grid_search( constructor, inputs: Tensor, targets: Tensor, classes: Tensor, params: list[dict], hidden_layers: int, auxiliary_loss: bool = False, epochs: int = 25, k: int = 4, verbose: bool = True, ) -> tuple[list, list]: """ :param model: the model :param inputs: input tensor of dimension (N, 2, 14, 14), N is the number of pairs :param labels: ground truth tensor of dimension N :param classes: inputs classes tensor of dimensions (N, 2) :param params: set of combination of hyper-parameters :param hidden_layers: number of hidden layers in the model :param auxiliary_loss: whether to train with auxiliary loss :param epochs: number of epochs :param k: number of folds for the cross-validation :param verbose: switch for verbose output :returns: number of errors for each set of parameters """ kfolds = k_fold_split(len(inputs), k=k) train_error = [] valid_error = [] for param_dict in params: print(f'Params {param_dict}') kfold_train_error = [] kfold_valid_error = [] for i in range(k): print(f'Fold {i+1}') # create new model model = constructor(hidden_layers=hidden_layers) # compute train indices and validation indices train_idx = torch.cat(kfolds[:i] + kfolds[i+1:]) valid_idx = kfolds[i] # train the model on the train set train_model( model, inputs=inputs[train_idx], targets=targets[train_idx], classes=classes[train_idx], epochs=epochs, auxiliary_loss=auxiliary_loss, verbose=verbose, **param_dict ) # keep track of validation errors in each fold kfold_train_error.append(compute_num_errors(model, inputs[train_idx], targets[train_idx])) kfold_valid_error.append(compute_num_errors(model, inputs[valid_idx], targets[valid_idx])) # compute average error over the folds train_error.append(torch.tensor(kfold_train_error, dtype=torch.float).mean()) valid_error.append(torch.tensor(kfold_valid_error, dtype=torch.float).mean()) return train_error, valid_error def tune_hyperparameters(num_samples = 1000, k = 4, verbose = False, start = 0, end = 5): """ Tune hyperparameters of all the models using grid search :param num_samples: number of samples :param k: number of folds for cross validation :param start: start model index :param end: end model index (excluded) :returns: best parameters, training and test errors, parameters """ model_constructors = [NaiveNet, SharedWeightNet, SharedWeightNet, SharedWeightNet, BenchmarkNet][start:end] hidden_layers = [1, 1, 1, 2, 2][start:end] with_aux_loss = [False, False, True, True, True][start:end] learning_rates = [0.0002, 0.0005, 0.0031, 0.012, 0.1] lambdas = [0, 0.115, 0.23, 0.345] params_without_auxi_loss = [] params_with_auxi_loss = [] for lr in learning_rates: p = {'learning_rate': lr, 'batch_size': 100} params_without_auxi_loss.append(p) for lambda_ in lambdas: params_with_auxi_loss.append({**p, 'lambda_': lambda_}) inputs, targets, classes, _, _, _ = prologue.generate_pair_sets(num_samples) params_dict = { False: params_without_auxi_loss, True: params_with_auxi_loss } results = [] test_error = [] params_iterate = [] train_error = [] for m, hl, aux in zip(model_constructors, hidden_layers, with_aux_loss): print(f'Performing hyperparameter-tuning on {m.__name__} with {hl} hidden layers') print(f'Auxiliary loss: {aux}') params = params_dict[aux] train, test = grid_search( m, inputs, targets, classes, hidden_layers=hl, auxiliary_loss=aux, params=params, k=k, verbose=False ) test_error.append(test) train_error.append(train) params_iterate.append(params) best_params = params[torch.tensor(test, dtype=float).argmin()] results.append(best_params) print(best_params) if verbose: print(test, m(hidden_layers=hl)) return results, train_error, test_error, params_iterate
{"/network.py": ["/network_helpers.py"], "/test.py": ["/network.py", "/helpers.py", "/generate_plot.py"], "/tuning.py": ["/helpers.py"], "/helpers.py": ["/network.py"]}
39,856,155
valentinoli/deep-learning-project-1
refs/heads/master
/generate_plot.py
import matplotlib.pyplot as plt def performance_plot(display_vals, NUM_ROUNDS, BOOTSTRAP): labels= [ 'Naive(1)\ntrain', '(Naive(1)\ntest', 'Shared\nWeightNet(1)\ntrain', 'Shared\nWeightNet(1)\ntest', 'Shared\nWeightNet(1)\ntrain', 'Shared\nWeightNet(1)\ntest', 'Shared\nWeightNet(2)\ntrain', 'Shared\nWeightNet(2)\ntest', 'Benchmark\ntrain', 'Benchmark\ntest' ] fig = plt.figure(figsize=(15, 6), dpi=80) plt.boxplot(display_vals, labels=labels, zorder=1) if BOOTSTRAP: bootstrap_text = ': {} rounds w/ bootstrap'.format(NUM_ROUNDS) else: bootstrap_text = ': {} rounds'.format(NUM_ROUNDS) for i in range(len(display_vals)): plt.plot([i+1]*len(display_vals[0]),display_vals[i],'.', markersize=7, label=labels[i].replace('\n', ' ')) plt.hlines(0.85, xmin=0.5, xmax=11, ls='--', color='gray') plt.title('Models performance comparison' + bootstrap_text) plt.ylabel('Bootstrapped Accuracy [%]') plt.show() fig.savefig('models_accuracy_boxplot.png')
{"/network.py": ["/network_helpers.py"], "/test.py": ["/network.py", "/helpers.py", "/generate_plot.py"], "/tuning.py": ["/helpers.py"], "/helpers.py": ["/network.py"]}
39,856,156
valentinoli/deep-learning-project-1
refs/heads/master
/network.py
from __future__ import annotations import torch from torch import nn, Tensor from network_helpers import block_cnn, block_digit_classifier, block_output, leq class Net(nn.Module): def __init__(self, hidden_layers: int, weight_sharing: bool = False): super().__init__() # CNN block self.cnn = block_cnn() # Classification blocks self.dc1 = block_digit_classifier(hidden_layers) if not weight_sharing: self.dc2 = block_digit_classifier(hidden_layers) # Output block self.out = block_output() def forward(self, input_: Tensor) -> tuple[Tensor, Tensor, Tensor]: raise NotImplementedError def reset_parameters(self): for layer in self.cnn: if type(layer) == nn.Conv2d: layer.reset_parameters() for layer in self.dc1: if type(layer) == nn.Linear: layer.reset_parameters() if hasattr(self, 'dc2'): for layer in self.dc2: if type(layer) == nn.Linear: layer.reset_parameters() for layer in self.out: if type(layer) == nn.Linear: layer.reset_parameters() class NaiveNet(Net): """Naive implementation without shared weights""" def __init__(self, hidden_layers: int = 1): super().__init__(hidden_layers) def forward(self, input_): # Pass each image of every pair through the convolutional block output1 = self.cnn(input_.select(1, 0).unsqueeze(1)) output2 = self.cnn(input_.select(1, 1).unsqueeze(1)) # Predict implicitly the classes of the images, using 2 different networks # -> one network for the first image of each pair, and another for the second image output1 = self.dc1(output1.flatten(1)) output2 = self.dc2(output2.flatten(1)) # Predict the output from concatenated class predictions output = self.out(torch.cat((output1, output2), 1)) return output, output1, output2 class SharedWeightNet(Net): """Network with shared weights""" def __init__(self, hidden_layers: int = 1): super().__init__(hidden_layers, weight_sharing = True) def forward_one(self, input_: Tensor): """Forwards the one image of each pair through the CNN and classification blocks""" return self.dc1(self.cnn(input_).flatten(1)) def forward_both(self, input_: Tensor): """Forwards both images through the shared weight net""" output1 = self.forward_one(input_.select(1, 0).unsqueeze(1)) output2 = self.forward_one(input_.select(1, 1).unsqueeze(1)) return output1, output2 def forward(self, input_): """Forward pass of the input batch of image pairs""" # Forward both images in every pair through the first two blocks # -> shared weight output1, output2 = self.forward_both(input_) # Compute the final output by concatenating the intermediate outputs of each pair output = self.out(torch.cat((output1, output2), 1)) return output, output1, output2 class BenchmarkNet(SharedWeightNet): """Network with shared weights with simple boolean operator for output prediction""" def __init__(self, hidden_layers: int = 2): super().__init__(hidden_layers) def forward(self, input_): """Forward pass of the input batch of image pairs""" output1, output2 = self.forward_both(input_) # Compute the output binary distribution by directly computing # if the most likely digit 1 is lesser or equal to the most likely digit 2 output = leq(output1.argmax(1), output2.argmax(1)) return output, output1, output2
{"/network.py": ["/network_helpers.py"], "/test.py": ["/network.py", "/helpers.py", "/generate_plot.py"], "/tuning.py": ["/helpers.py"], "/helpers.py": ["/network.py"]}
39,861,824
phearnow11/CodeTranslater
refs/heads/main
/function.py
import string import sympy as sp def EncodeCeasarCode(text, shift, alphabets): def shift_alphabet(alphabet): return alphabet[shift:] + alphabet[:shift] shifted_alphabets = tuple(map(shift_alphabet, alphabets)) final_alphabet = ''.join(alphabets) final_shifted_alphabet = ''.join(shifted_alphabets) table = str.maketrans(final_alphabet, final_shifted_alphabet) return text.translate(table) def DecodeCeasarCode(text, alphabets): arr = [] for i in range(1,27): arr.append(EncodeCeasarCode(text, i, alphabets)) return arr def DecodeVigenege(code, key): codes = list(code) alphabetss = list(string.ascii_lowercase) keys = list(key) WhereIsCode = [] for i in range(0, len(key)): for j in range(0, 26): if (alphabetss[j] == keys[i]): WhereIsCode.append(j) break EncodedVigenege = [] for i in range(0, len(code)): EncodedVigenege.append(EncodeCeasarCode(codes[i], WhereIsCode[i],[string.ascii_uppercase, string.ascii_lowercase, string.punctuation])) return ''.join(EncodedVigenege) def daoham(n,bienso): if bienso == 1: x = sp.Symbol('x') return sp.diff(n, x) elif bienso == 2: x, y = sp.symbols('x y') return sp.diff(n, x)
{"/main.py": ["/function.py"]}
39,861,825
phearnow11/CodeTranslater
refs/heads/main
/main.py
import string import function import SudokuSolver import sympy as sp if __name__ == '__main__' : print("----------------------------------------------------------------------------------------------------------------") print("--------------------------------------------------Made by Phien-------------------------------------------------") print("Options: \n\n Encode Ceasar Code (1) \n\n Decode Ceasar Code (2) \n\n Encode VigenegeCode (3) \n\n SudokuSolver (4) \n\n DaoHam (5) \n\n Quit (9) \n\n") open = True while open : Option = int(input("Option: ")) if Option == 9: open = False if Option == 1: text = input("Text you want to encode: ") shift = int(input("Step to fall back: ")) print("Encoded CeasarCode:", function.EncodeCeasarCode(text,shift,[string.ascii_uppercase, string.ascii_lowercase, string.punctuation])) if Option == 2: text = input("Code you want to decode: ") print("Decoded CeasarCode:", function.DecodeCeasarCode(text,[string.ascii_lowercase, string.ascii_uppercase, string.punctuation])) if Option == 3: code = input("Code you want to decode: ") key = input("Key: ") if len(code) != len(key): print("Error!! Key has to equal to code !!") else: print("Decoded Vigenege Code:", function.DecodeVigenege(code, key)) if Option == 4: columns = 9 rows = 9 table = [] for i in range (0,rows): table.append([]) for j in range (0, columns): table[i].append(int(input())) print("Board: ") SudokuSolver.print_board(table) SudokuSolver.solve(table) print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$") print("Solved Board: ") SudokuSolver.print_board(table) if Option == 5: bienso = int(input("số biến: ")) if bienso == 1: x = sp.Symbol('x') n = input("nhap dao ham: ") print(function.daoham(n,bienso)) if bienso == 2: x, y = sp.symbols('x y') n = input("nhap dao ham: ") print(function.daoham(n,bienso))
{"/main.py": ["/function.py"]}
39,928,589
spiros26/Flask-Project
refs/heads/master
/echarge/cli/ev_group36/commands/cmd_logout.py
import click import requests url = "http://localhost:8765/evcharge/api/logout" class Context: def __init__(self, apikey): self.apikey = apikey @click.group() @click.option("--apikey") @click.pass_context def cli(ctx, apikey): ctx.obj = Context(apikey) @cli.command() @click.pass_context def logout(ctx): response = requests.post(url, headers = {'X-OBSERVATORY-AUTH':ctx.obj.apikey}) print(response.text)
{"/website/views.py": ["/website/models.py"], "/main.py": ["/echarge/__init__.py"], "/echarge/models.py": ["/echarge/__init__.py"], "/echarge/__init__.py": ["/echarge/backend/__init__.py", "/echarge/models.py"], "/echarge/backend/auth.py": ["/echarge/models.py", "/echarge/__init__.py"], "/echarge/backend/sessions.py": ["/echarge/backend/auth.py", "/echarge/models.py"], "/echarge/backend/admin.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/auth.py"], "/echarge/backend/__init__.py": ["/echarge/backend/views.py", "/echarge/backend/auth.py", "/echarge/backend/admin.py", "/echarge/backend/sessions.py"], "/echarge/backend/views.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/sessions.py"]}
39,928,590
spiros26/Flask-Project
refs/heads/master
/main.py
from echarge import create_app, db, initializer app = create_app() db.app = app initializer() if __name__ == '__main__': app.run(debug=True) #app.run(debug=True, ssl_context=('echarge/certificates/cert.prem','echarge/certificates/key.prem' ))
{"/website/views.py": ["/website/models.py"], "/main.py": ["/echarge/__init__.py"], "/echarge/models.py": ["/echarge/__init__.py"], "/echarge/__init__.py": ["/echarge/backend/__init__.py", "/echarge/models.py"], "/echarge/backend/auth.py": ["/echarge/models.py", "/echarge/__init__.py"], "/echarge/backend/sessions.py": ["/echarge/backend/auth.py", "/echarge/models.py"], "/echarge/backend/admin.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/auth.py"], "/echarge/backend/__init__.py": ["/echarge/backend/views.py", "/echarge/backend/auth.py", "/echarge/backend/admin.py", "/echarge/backend/sessions.py"], "/echarge/backend/views.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/sessions.py"]}
39,928,591
spiros26/Flask-Project
refs/heads/master
/echarge/cli/ev_group36/commands/cmd_login.py
import click import requests url = "http://localhost:8765/evcharge/api/login" class Context: def __init__(self, username, password): self.username = username self.password = password @click.group() @click.option("--username") @click.option("--password") @click.pass_context def cli(ctx, username, password): ctx.obj = Context(username, password) @cli.command() @click.pass_context def login(ctx): response = requests.post(url, data = {'username':ctx.obj.username, 'password':ctx.obj.password}) print(response.text)
{"/website/views.py": ["/website/models.py"], "/main.py": ["/echarge/__init__.py"], "/echarge/models.py": ["/echarge/__init__.py"], "/echarge/__init__.py": ["/echarge/backend/__init__.py", "/echarge/models.py"], "/echarge/backend/auth.py": ["/echarge/models.py", "/echarge/__init__.py"], "/echarge/backend/sessions.py": ["/echarge/backend/auth.py", "/echarge/models.py"], "/echarge/backend/admin.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/auth.py"], "/echarge/backend/__init__.py": ["/echarge/backend/views.py", "/echarge/backend/auth.py", "/echarge/backend/admin.py", "/echarge/backend/sessions.py"], "/echarge/backend/views.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/sessions.py"]}
39,928,592
spiros26/Flask-Project
refs/heads/master
/echarge/models.py
from . import db from flask_login import UserMixin from sqlalchemy.sql import func from sqlalchemy.dialects.postgresql import JSON class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) public_id = db.Column(db.String(50), unique=True) username = db.Column(db.String(40), unique=True) password = db.Column(db.String(60)) name = db.Column(db.String(80)) email = db.Column(db.String(80), unique=True) role = db.Column(db.String(20)) evs = db.relationship('Evehicle') class RevokedToken(db.Model): id = db.Column(db.Integer, primary_key=True) token = db.Column(db.String(150)) class Evehicle(db.Model): id = db.Column(db.Integer, primary_key=True) car_id = db.Column(db.String(100), unique=True) brand = db.Column(db.String(20)) car_type = db.Column(db.String(10)) brand_id = db.Column(db.String(100)) model = db.Column(db.String(40)) release_year = db.Column(db.Integer) variant = db.Column(db.String(20)) usable_battery_size = db.Column(db.Float) ac_charger = db.Column(JSON) dc_charger = db.Column(JSON) energy_consumption = db.Column(JSON) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) sessions = db.relationship('Session') class Operator(db.Model): id = db.Column(db.Integer, primary_key=True) operator_id = db.Column(db.Integer, unique=True) name = db.Column(db.String(100)) website = db.Column(db.String(150)) email = db.Column(db.String(150)) stations = db.relationship('Station') class Station(db.Model): id = db.Column(db.Integer, primary_key=True) station_id = db.Column(db.String(50), unique=True) name = db.Column(db.String(100)) email = db.Column(db.String(100)) phone = db.Column(db.String(15)) website = db.Column(db.String(100)) address = db.Column(db.String(120)) latitude = db.Column(db.String(25)) longitude = db.Column(db.String(25)) points = db.relationship('Point') operator_id = db.Column(db.Integer, db.ForeignKey('operator.id')) provider_id = db.Column(db.Integer, db.ForeignKey('energyprovider.id')) class Point(db.Model): id = db.Column(db.Integer, primary_key=True) point_id = db.Column(db.String(50), unique=True) station_id = db.Column(db.Integer, db.ForeignKey('station.id')) sessions = db.relationship('Session') class Energyprovider(db.Model): id = db.Column(db.Integer, primary_key=True) provider_id = db.Column(db.String(20), unique=True) name = db.Column(db.String(100), unique=True) stations = db.relationship('Station') class Session(db.Model): id = db.Column(db.Integer, primary_key=True) session_id = db.Column(db.String(100)) connection_date = db.Column(db.String(60)) connection_time = db.Column(db.String(60)) done_date = db.Column(db.String(60)) done_time = db.Column(db.String(60)) disconnection_date = db.Column(db.String(60)) disconnection_time = db.Column(db.String(60)) kWh_delivered = db.Column(db.Float) protocol = db.Column(db.String(40)) payment = db.Column(db.String(40)) point_id = db.Column(db.Integer, db.ForeignKey('point.id')) ev_id = db.Column(db.Integer, db.ForeignKey('evehicle.id'))
{"/website/views.py": ["/website/models.py"], "/main.py": ["/echarge/__init__.py"], "/echarge/models.py": ["/echarge/__init__.py"], "/echarge/__init__.py": ["/echarge/backend/__init__.py", "/echarge/models.py"], "/echarge/backend/auth.py": ["/echarge/models.py", "/echarge/__init__.py"], "/echarge/backend/sessions.py": ["/echarge/backend/auth.py", "/echarge/models.py"], "/echarge/backend/admin.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/auth.py"], "/echarge/backend/__init__.py": ["/echarge/backend/views.py", "/echarge/backend/auth.py", "/echarge/backend/admin.py", "/echarge/backend/sessions.py"], "/echarge/backend/views.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/sessions.py"]}
39,928,593
spiros26/Flask-Project
refs/heads/master
/echarge/__init__.py
from flask import Flask, jsonify from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from os import path from flask_login import LoginManager import uuid from werkzeug.security import generate_password_hash import pandas as pd import json import numpy as np import random db = SQLAlchemy() migrate = Migrate() DB_NAME = "Data.db" def create_app(): App = Flask(__name__, static_folder='./frontend/static', template_folder='./frontend/templates') App.config['SECRET_KEY'] = 'hjshjhdjh' App.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}' App.config['JSON_SORT_KEYS'] = False App.config['SERVER_NAME'] = 'localhost:8765' db.init_app(App) from echarge.backend import views, auth, admin, sessions App.register_blueprint(views, url_prefix='/evcharge/api/') App.register_blueprint(admin, url_prefix='/evcharge/api/') App.register_blueprint(auth, url_prefix='/evcharge/api/') App.register_blueprint(sessions, url_prefix='/evcharge/api/') from .models import User, RevokedToken, Evehicle, Point, Station, Operator, Session create_database(App) migrate.init_app(App, db) login_manager = LoginManager() login_manager.login_view = 'auth.Login' login_manager.init_app(App) @login_manager.user_loader def load_user(id): return User.query.get(int(id)) App.jinja_env.globals.update(energy_provider=energy_provider) App.jinja_env.globals.update(station_address=station_address) App.jinja_env.globals.update(round_cost=round_cost) App.jinja_env.globals.update(show_waiting_time=show_waiting_time) return App def create_database(app): if not path.exists('echarge/' + DB_NAME): db.create_all(app=app) print('Created Database!') def show_waiting_time(d): float_time = d/60000 # in minutes hours, seconds = divmod(float_time * 60, 3600) # split to hours and seconds minutes, seconds = divmod(seconds, 60) # split the seconds to minutes and seconds return [int(hours), int(minutes), int(seconds)] def round_cost(x): return round(x, 2) def energy_provider(point_id): from .models import Point, Station, Energyprovider point = Point.query.get(point_id) station = Station.query.get(point.station_id) provider = Energyprovider.query.get(station.provider_id) return provider.name def station_address(point_id): from .models import Point, Station point = Point.query.get(point_id) station = Station.query.get(point.station_id) return station.address def default_admin(username, password): from .models import User user = User.query.filter_by(username=username).first() if not user: hashed_password = generate_password_hash(password, method='sha256') admin = User(public_id=str(uuid.uuid4()), username=username, password=hashed_password, role="Admin") db.session.add(admin) db.session.commit() print('Default admin created!') else: user.password = generate_password_hash(password, method='sha256') db.session.add(user) db.session.commit() print('Default admin initialized') def default_evs(filename): from .models import Evehicle, User with open(filename) as jsdata: evs = json.load(jsdata) cont = pd.DataFrame(evs['data']) length = cont.shape[0] for x in range(0,500): check = Evehicle.query.filter_by(car_id=f"EV{x+1}").first() if not check: y = random.randint(0,length-1) user = User.query.filter_by(username=f"User{x+1}").first() new_ev = Evehicle(car_id=f"EV{x+1}", brand=cont["brand"][y], car_type=cont["type"][y], brand_id=cont["brand_id"][y], model=cont["model"][y], release_year=cont["release_year"][y], variant=cont["variant"][y], usable_battery_size=cont["usable_battery_size"][y], ac_charger=cont["ac_charger"][y], dc_charger=cont["dc_charger"][y], energy_consumption=cont["energy_consumption"][y], user_id=user.id) db.session.add(new_ev) db.session.commit() print('Default EVs are in') def default_operators(filename): from .models import Operator df = pd.read_csv(filename, sep=";") for a, x in df.iterrows(): check = Operator.query.filter_by(operator_id=x["ID"]).first() if not check: new_op = Operator(operator_id=x["ID"], name=x["Title"], website=x["WebsiteURL"], email=x["ContactEmail"]) db.session.add(new_op) db.session.commit() print('Default operators are in') def default_points_stations(filename): from .models import Station, Point, Operator, Energyprovider col_list = ["_id", "AddressInfo.ID", "AddressInfo.Title", "AddressInfo.AddressLine1", "AddressInfo.Latitude", "AddressInfo.Longitude", "AddressInfo.ContactTelephone1", "AddressInfo.ContactEmail", "AddressInfo.RelatedURL"] df = pd.read_csv(filename, sep=",", nrows=1000, usecols=col_list) #df = pd.read_csv(filename, sep=",", usecols=col_list) operator_table = Operator.query.all() provider_table = Energyprovider.query.all() for _, x in df.iterrows(): if isinstance(x["AddressInfo.AddressLine1"], str) and isinstance(x["AddressInfo.Title"], str) and isinstance(x["_id"], str): check = Station.query.filter_by(address=x["AddressInfo.AddressLine1"]).first() if not check: phone = x["AddressInfo.ContactTelephone1"] mail = x["AddressInfo.ContactEmail"] site = x["AddressInfo.RelatedURL"] operator = random.choice(operator_table) provider = random.choice(provider_table) new_station = Station(station_id=str(x["AddressInfo.ID"]), name=x["AddressInfo.Title"], email=mail, phone=phone, website=site, address=x["AddressInfo.AddressLine1"], latitude=x["AddressInfo.Latitude"], longitude=x["AddressInfo.Longitude"], operator_id=operator.id, provider_id=provider.id) this_station = new_station db.session.add(new_station) db.session.commit() else: this_station = check check2 = Point.query.filter_by(point_id=x["_id"]).first() if not check2: new_point = Point(point_id=x["_id"], station_id=this_station.id) db.session.add(new_point) db.session.commit() print('Points and Stations are in') def default_users(): from .models import User names = ["Liam", "Olivia", "Noah", "Emma", "Oliver", "Ava", "William", "Sophia", "Elijah", "Isabella", "James", "Charlotte", "Benjamin", "Amelia", "Lucas", "Mia", "Mason", "Harper", "Ethan", "Evelyn"] for x in range(1,501): username = f"User{x}" password = f"password{x}" name = names[x % 20] email = f"User{x}@gmail.com" hashed_password = generate_password_hash(password, method='sha256') check = User.query.filter_by(username=username).first() if not check: new_user = User(public_id=str(uuid.uuid4()), username=username, password=hashed_password, name=name, email=email, role="User") db.session.add(new_user) db.session.commit() for x in range(1,21): username = f"Privileged{x}" password = f"privypass{x}" name = "Privileged Stakeholder" email = f"Privileged{x}@gmail.com" hashed_password = generate_password_hash(password, method='sha256') check = User.query.filter_by(username=username).first() if not check: new_user = User(public_id=str(uuid.uuid4()), username=username, password=hashed_password, name=name, email=email, role="Privileged") db.session.add(new_user) db.session.commit() print('Default users are in') def default_sessions(filename): from .models import Session, Evehicle, Point with open(filename) as jsdata: sess = json.load(jsdata) cont = pd.DataFrame(sess['_items']) ev_table = Evehicle.query.all() point_table = Point.query.all() payment_table = ["Credit_Card", "Debit_Card", "Smartphone_Wallet", "Website_Payment", "QR_Code", "Cash"] for x in range(0,len(cont)): check = Session.query.filter_by(session_id=cont["_id"][x]).first() if not check and isinstance(cont["connectionTime"][x], str) and isinstance(cont["doneChargingTime"][x], str) and isinstance(cont["disconnectTime"][x], str): edit_start = cont["connectionTime"][x] year_start = edit_start[12:16] month_start = months_to_nums(edit_start[8:11]) day_start = edit_start[5:7] time_start = edit_start[17:19]+edit_start[20:22]+edit_start[23:25] edit_fin = cont["doneChargingTime"][x] year_fin = edit_fin[12:16] month_fin = months_to_nums(edit_fin[8:11]) day_fin = edit_fin[5:7] time_fin = edit_fin[17:19]+edit_fin[20:22]+edit_fin[23:25] edit_dis = cont["disconnectTime"][x] year_dis = edit_dis[12:16] month_dis = months_to_nums(edit_dis[8:11]) day_dis = edit_dis[5:7] time_dis = edit_dis[17:19]+edit_dis[20:22]+edit_dis[23:25] begin = int(time_start[:2])*60+int(time_start[2:4]) end = 0 if day_start!=day_fin: end = 1440 end = end + int(time_fin[:2])*60+int(time_fin[2:4]) space = end - begin if space==0: space = 1 rate = (cont["kWhDelivered"][x]*60)/space if rate < 5.0: protocol = "Level 1: Low" elif rate < 25.0: protocol = "Level 2: Medium" else: protocol = "Level 3: High" ev = random.choice(ev_table) point = random.choice(point_table) payment = random.choice(payment_table) new_session = Session(session_id=cont["_id"][x], connection_date=year_start+month_start+day_start, connection_time=time_start, done_date=year_fin+month_fin+day_fin, done_time=time_fin, disconnection_date=year_dis+month_dis+day_dis, disconnection_time=time_dis, kWh_delivered = cont["kWhDelivered"][x], protocol=protocol ,payment=payment ,ev_id=ev.id, point_id=point.id) db.session.add(new_session) db.session.commit() print('Sessions are in') def months_to_nums(x): switcher = { "Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06", "Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12" } return switcher.get(x, "???") def default_providers(): from .models import Energyprovider us_table = [ "4Change Energy", "AEP Energy", "Ambit energy", "Amigo Energy", "Beyond Power", "Bounce Energy", "Champion Energy Services", "Cirro Energy", "Constellation", "CPL Retail Energy", "Direct Energy", "FirstEnergy Solutions", "First Choice Power", "Gexa Energy", "Green Mountain Energy", "IGS Energy", "Infinite Energy", "Inspire Energy", "Just Energy", "Liberty Power", "North American Power", "Pennywise Power", "StarTex Power", "TriEagle Energy", "WGL Energy" ] for x in range(0,len(us_table)): prov = Energyprovider.query.filter_by(name=us_table[x]).first() if not prov: new_provider = Energyprovider(provider_id=f"0987654321{x+1}", name=us_table[x]) db.session.add(new_provider) db.session.commit() print("Default providers are in!") def initializer(): default_admin('admin','petrol4ever') default_providers() default_operators('echarge/backend/static/Operators_data.csv') default_points_stations('echarge/backend/static/points1.csv') #default_points_stations('echarge/backend/static/points2.csv') default_users() default_evs('echarge/backend/static/electric_vehicles_data.json') default_sessions('echarge/backend/static/caltech_acndata_sessions_12month.json')
{"/website/views.py": ["/website/models.py"], "/main.py": ["/echarge/__init__.py"], "/echarge/models.py": ["/echarge/__init__.py"], "/echarge/__init__.py": ["/echarge/backend/__init__.py", "/echarge/models.py"], "/echarge/backend/auth.py": ["/echarge/models.py", "/echarge/__init__.py"], "/echarge/backend/sessions.py": ["/echarge/backend/auth.py", "/echarge/models.py"], "/echarge/backend/admin.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/auth.py"], "/echarge/backend/__init__.py": ["/echarge/backend/views.py", "/echarge/backend/auth.py", "/echarge/backend/admin.py", "/echarge/backend/sessions.py"], "/echarge/backend/views.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/sessions.py"]}
39,928,594
spiros26/Flask-Project
refs/heads/master
/echarge/cli/ev_group36/commands/cmd_Admin.py
import click import requests url = "http://localhost:8765/evcharge/api/admin/usermod/" url2 = "http://localhost:8765/evcharge/api/admin/users/" url3 = "http://localhost:8765/evcharge/api/admin/healthcheck" url4 = "http://localhost:8765/evcharge/api/admin/resetsessions" url5 = "http://localhost:8765/evcharge/api/admin/system/sessionsupd" class Context: def __init__(self, username, password, source, role, format, apikey): self.username = username self.password = password self.source = source self.role = role self.format = format self.apikey = apikey @click.group() @click.option("--username") @click.option("--password") @click.option("--source") @click.option("--role") @click.option("--format", default="json", show_default=True) @click.option("--apikey") @click.pass_context def cli(ctx, username, password, source, role, format, apikey): ctx.obj = Context(username, password, source, role, format, apikey) @cli.command() @click.pass_context def usermod(ctx): try: response = requests.post(url + ctx.obj.username + "/" + ctx.obj.password + "/" + ctx.obj.role, headers = {'X-OBSERVATORY-AUTH':ctx.obj.apikey}) print(response.text) except: print('Invalid parameters.') print('Try ev_group36 Admin --help for help.') @cli.command() @click.pass_context def users(ctx): try: response = requests.get(url2 + ctx.obj.username + "?format=" + ctx.obj.format, headers = {'X-OBSERVATORY-AUTH':ctx.obj.apikey}) print(response.text) except: print('Invalid parameters.') print('Try ev_group36 Admin --help for help.') @cli.command() @click.pass_context def healthcheck(ctx): response = requests.get(url3, headers = {'X-OBSERVATORY-AUTH':ctx.obj.apikey}) print(response.text) @cli.command() @click.pass_context def resetsessions(ctx): response = requests.post(url4, headers = {'X-OBSERVATORY-AUTH':ctx.obj.apikey}) print(response.text) @cli.command() @click.pass_context def sessionsupd(ctx): if not ctx.obj.source: print('Source parameter is missing') else: response = requests.post(url5 + "?format=" + ctx.obj.format, data = {'file':ctx.obj.source}, headers = {'X-OBSERVATORY-AUTH':ctx.obj.apikey}) print(response.text)
{"/website/views.py": ["/website/models.py"], "/main.py": ["/echarge/__init__.py"], "/echarge/models.py": ["/echarge/__init__.py"], "/echarge/__init__.py": ["/echarge/backend/__init__.py", "/echarge/models.py"], "/echarge/backend/auth.py": ["/echarge/models.py", "/echarge/__init__.py"], "/echarge/backend/sessions.py": ["/echarge/backend/auth.py", "/echarge/models.py"], "/echarge/backend/admin.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/auth.py"], "/echarge/backend/__init__.py": ["/echarge/backend/views.py", "/echarge/backend/auth.py", "/echarge/backend/admin.py", "/echarge/backend/sessions.py"], "/echarge/backend/views.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/sessions.py"]}
39,928,595
spiros26/Flask-Project
refs/heads/master
/echarge/backend/testing/check_endpoints.py
import requests from requests.auth import HTTPBasicAuth import json import jsonpath import pytest def test_admin_usermod_users(): url = "http://localhost:8765/evcharge/api/login" file = open("admin_creds.json", 'r') json_input = file.read() request_json = json.loads(json_input) response = requests.post(url,request_json) assert response.status_code == 200 tok_en = (response.json())["token"] #admin/usermod #add new user with admin/usermod response = requests.post("http://localhost:8765/evcharge/api/admin/usermod/TestUser/TestPassword/User", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 #pass invalid role to admin/usermod response = requests.post("http://localhost:8765/evcharge/api/admin/usermod/TestUser/TestPassword/Writer", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 400 #change user's password and role with admin/usermod response = requests.post("http://localhost:8765/evcharge/api/admin/usermod/TestUser/TestPassword2/Privileged", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 #admin/users #check user's data with admin/users response = requests.get("http://localhost:8765/evcharge/api/admin/users/TestUser", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 #check user's data with admin/users response = requests.get("http://localhost:8765/evcharge/api/admin/users/TestUser" + "?format=" + "json", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 #check user's data with admin/users response = requests.get("http://localhost:8765/evcharge/api/admin/users/TestUser"+ "?format=" + "csv" , headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 #check user's data with admin/users response = requests.get("http://localhost:8765/evcharge/api/admin/users/TestUser" + "?format=" + "docx", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 400 #check invalid user's data with admin/users response = requests.get("http://localhost:8765/evcharge/api/admin/users/TestUser42", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 400 #logout response = requests.post("http://localhost:8765/evcharge/api/logout", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 def test_admin_sessionsupd(): url = "http://localhost:8765/evcharge/api/login" file = open("admin_creds.json", 'r') json_input = file.read() request_json = json.loads(json_input) response = requests.post(url,request_json) assert response.status_code == 200 tok_en = (response.json())["token"] #admin/system/sessionsupd #pass csv file when only json is supported response = requests.post("http://localhost:8765/evcharge/api/admin/system/sessionsupd", data={'file': 'echarge\\backend\\testing\\empty.csv'}, headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 400 #pass json file with wrong fields response = requests.post("http://localhost:8765/evcharge/api/admin/system/sessionsupd", data={'file': 'echarge\\backend\\testing\\user.json'}, headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 400 #pass right file with data in sessionsupd response = requests.post("http://localhost:8765/evcharge/api/admin/system/sessionsupd", data={'file': 'echarge\\backend\\testing\\dummy_sessions.json'}, headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 response = requests.post("http://localhost:8765/evcharge/api/admin/system/sessionsupd" + "?format=" + "json", data={'file': 'echarge\\backend\\testing\\dummy_sessions.json'}, headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 response = requests.post("http://localhost:8765/evcharge/api/admin/system/sessionsupd" + "?format=" + "csv", data={'file': 'echarge\\backend\\testing\\dummy_sessions.json'}, headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 response = requests.post("http://localhost:8765/evcharge/api/admin/system/sessionsupd" + "?format=" + "docx", data={'file': 'echarge\\backend\\testing\\dummy_sessions.json'}, headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 400 def test_sessions_per(): url = "http://localhost:8765/evcharge/api/login" file = open("dummy_user.json", 'r') json_input = file.read() request_json = json.loads(json_input) response = requests.post(url,request_json) assert response.status_code == 200 tok_en = (response.json())["token"] #SessionsPerPoint #check sessions for a point response = requests.get("http://localhost:8765/evcharge/api/SessionsPerPoint/5f6978b800355e4c01059523/00010101/30000101", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 response = requests.get("http://localhost:8765/evcharge/api/SessionsPerPoint/5f6978b800355e4c01059523/00010101/30000101" + "?format=" + "json", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 response = requests.get("http://localhost:8765/evcharge/api/SessionsPerPoint/5f6978b800355e4c01059523/00010101/30000101" + "?format=" + "csv", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 response = requests.get("http://localhost:8765/evcharge/api/SessionsPerPoint/5f6978b800355e4c01059523/00010101/30000101" + "?format=" + "docx", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 400 #SessionsPerStation #check sessions for a station response = requests.get("http://localhost:8765/evcharge/api/SessionsPerStation/2389/00010101/30000101", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 response = requests.get("http://localhost:8765/evcharge/api/SessionsPerStation/2389/00010101/30000101" + "?format=" + "json", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 response = requests.get("http://localhost:8765/evcharge/api/SessionsPerStation/2389/00010101/30000101" + "?format=" + "csv", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 response = requests.get("http://localhost:8765/evcharge/api/SessionsPerStation/2389/00010101/30000101" + "?format=" + "docx", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 400 #SessionsPerEV #check sessions for a e-vehicle response = requests.get("http://localhost:8765/evcharge/api/SessionsPerEV/EV1/00010101/30000101", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 response = requests.get("http://localhost:8765/evcharge/api/SessionsPerEV/EV1/00010101/30000101" + "?format=" + "json", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 response = requests.get("http://localhost:8765/evcharge/api/SessionsPerEV/EV1/00010101/30000101" + "?format=" + "csv", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 response = requests.get("http://localhost:8765/evcharge/api/SessionsPerEV/EV1/00010101/30000101" + "?format=" + "docx", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 400 #SessionsPerProvider #check sessions for a provider response = requests.get("http://localhost:8765/evcharge/api/SessionsPerProvider/09876543211/00010101/30000101", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 response = requests.get("http://localhost:8765/evcharge/api/SessionsPerProvider/09876543211/00010101/30000101" + "?format=" + "json", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 response = requests.get("http://localhost:8765/evcharge/api/SessionsPerProvider/09876543211/00010101/30000101" + "?format=" + "csv", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 response = requests.get("http://localhost:8765/evcharge/api/SessionsPerProvider/09876543211/00010101/30000101" + "?format=" + "docx", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 400 #logout response = requests.post("http://localhost:8765/evcharge/api/logout", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 def test_user_privs(): url = "http://localhost:8765/evcharge/api/login" file = open("admin_creds.json", 'r') json_input = file.read() request_json = json.loads(json_input) response = requests.post(url,request_json) assert response.status_code == 200 tok_en = (response.json())["token"] #admin/usermod #add new user with admin/usermod response = requests.post("http://localhost:8765/evcharge/api/admin/usermod/TestUser/TestPassword/User", headers={'X-OBSERVATORY-AUTH':tok_en}) assert response.status_code == 200 #response = requests.post("http://localhost:8765/evcharge/api/login", {'username': 'TestUser', 'password':'TestPassword'}) #assert response.status_code == 200 #tok_en = (response.json())["token"] #def test_continue_with_bad_user(): url = "http://localhost:8765/evcharge/api/login" file = open("bad_user.json", 'r') json_input = file.read() request_json = json.loads(json_input) response = requests.post(url,request_json) assert response.status_code == 200 tok_en2 = (response.json())["token"] #change user's password and role with admin/usermod response = requests.post("http://localhost:8765/evcharge/api/admin/usermod/TestUser/TestPassword2/Privileged", headers={'X-OBSERVATORY-AUTH':tok_en2}) assert response.status_code == 401 #check user's data with admin/users response = requests.get("http://localhost:8765/evcharge/api/admin/users/TestUser", headers={'X-OBSERVATORY-AUTH':tok_en2}) assert response.status_code == 401 #pass right file with data in sessionsupd response = requests.post("http://localhost:8765/evcharge/api/admin/system/sessionsupd", data={'file': 'echarge\\backend\\testing\\dummy_sessions.json'}, headers={'X-OBSERVATORY-AUTH':tok_en2}) assert response.status_code == 401 #check sessions for a point response = requests.get("http://localhost:8765/evcharge/api/SessionsPerPoint/5f6978b800355e4c01059523/00010101/30000101", headers={'X-OBSERVATORY-AUTH':tok_en2}) assert response.status_code == 401 #check sessions for a station response = requests.get("http://localhost:8765/evcharge/api/SessionsPerStation/2389/00010101/30000101", headers={'X-OBSERVATORY-AUTH':tok_en2}) assert response.status_code == 401 #check sessions for a e-vehicle response = requests.get("http://localhost:8765/evcharge/api/SessionsPerEV/EV1/00010101/30000101", headers={'X-OBSERVATORY-AUTH':tok_en2}) assert response.status_code == 401 #check sessions for a provider response = requests.get("http://localhost:8765/evcharge/api/SessionsPerProvider/09876543211/00010101/30000101", headers={'X-OBSERVATORY-AUTH':tok_en2}) assert response.status_code == 401 #logout response = requests.post("http://localhost:8765/evcharge/api/logout", headers={'X-OBSERVATORY-AUTH':tok_en2}) assert response.status_code == 200
{"/website/views.py": ["/website/models.py"], "/main.py": ["/echarge/__init__.py"], "/echarge/models.py": ["/echarge/__init__.py"], "/echarge/__init__.py": ["/echarge/backend/__init__.py", "/echarge/models.py"], "/echarge/backend/auth.py": ["/echarge/models.py", "/echarge/__init__.py"], "/echarge/backend/sessions.py": ["/echarge/backend/auth.py", "/echarge/models.py"], "/echarge/backend/admin.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/auth.py"], "/echarge/backend/__init__.py": ["/echarge/backend/views.py", "/echarge/backend/auth.py", "/echarge/backend/admin.py", "/echarge/backend/sessions.py"], "/echarge/backend/views.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/sessions.py"]}
39,928,596
spiros26/Flask-Project
refs/heads/master
/echarge/backend/auth.py
from flask import Blueprint, render_template, request, flash, redirect, url_for, jsonify, Response, make_response from ..models import User, RevokedToken, Evehicle from werkzeug.security import generate_password_hash, check_password_hash from .. import db from flask_login import login_user, login_required, logout_user, current_user import uuid import jwt import datetime from functools import wraps auth = Blueprint('auth', __name__) def token_made_black(f): @wraps(f) def decorated(*args, **kwargs): token = None if 'X-OBSERVATORY-AUTH' in request.headers: token = request.headers['X-OBSERVATORY-AUTH'] invalid = RevokedToken.query.filter_by(token=token).first() if not token: return make_response('Token not found', 400) if invalid: return make_response('Invalid Token', 400) return f(token, *args, **kwargs) return decorated def token_required(f): @wraps(f) def decorated(*args, **kwargs): token = None if 'X-OBSERVATORY-AUTH' in request.headers: token = request.headers['X-OBSERVATORY-AUTH'] invalid = RevokedToken.query.filter_by(token=token).first() if not token: return make_response('Token not found', 400) if invalid: return make_response('Invalid Token', 400) try: data = jwt.decode(token, 'hjshjhdjh') current_user = User.query.filter_by(public_id=data['public_id']).first() except: return make_response('Invalid Token', 400) return f(current_user, *args, **kwargs) return decorated @auth.route('/login', methods=['POST']) def login(): username = request.form.get('username') password = request.form.get('password') user = User.query.filter_by(username=username).first() if not user: return make_response('Could not verify', 400) if check_password_hash(user.password, password): token = jwt.encode({'public_id' : user.public_id, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, 'hjshjhdjh') res = token.decode('UTF-8') return jsonify({'token' : res}) return make_response('Could not verify', 400) @auth.route('/logout', methods=['POST']) @token_made_black def logout(token): try: black_token = RevokedToken(token=token) db.session.add(black_token) db.session.commit() return Response(status=200) except: return Response(status=402) @auth.route('/Login', methods=['GET', 'POST']) def Login(): status=200 if request.method == 'POST': username = request.form.get('username') password = request.form.get('password') user = User.query.filter_by(username=username).first() if user: if check_password_hash(user.password, password): flash('Logged in successfully!', category='success') login_user(user, remember=True) return redirect(url_for('views.home')) else: flash('Incorrect password, try again.', category='error') status=400 else: flash('User does not exist.', category='error') status=400 return render_template("login.html", user=current_user), status @auth.route('/Logout') @login_required def Logout(): logout_user() return redirect(url_for('auth.Login')) @auth.route('/sign-up', methods=['GET', 'POST']) def sign_up(): status=200 if request.method == 'POST': username = request.form.get('username') name = request.form.get('Name') email = request.form.get('email') car_brand = request.form.get('car_brand') car_model = request.form.get('car_model') car_id = request.form.get('car_id') password1 = request.form.get('password1') password2 = request.form.get('password2') ev = Evehicle.query.filter_by(car_id=car_id).first() user = User.query.filter_by(username=username).first() if ev: flash('EV already exists.', category='error') status=400 elif user: flash('Username already exists.', category='error') status=400 elif len(username) < 4: flash('Username must be greater than 3 characters.', category='error') status=400 elif len(name) < 2: flash('Name must be greater than 1 character.', category='error') status=400 elif len(car_brand) < 2: flash('Car Brand must be greater than 1 character.', category='error') status=400 elif len(car_model) < 2: flash('Car Model must be greater than 1 character.', category='error') status=400 elif password1 != password2: flash('Passwords don\'t match.', category='error') status=400 elif len(password1) < 4: flash('Password must be at least 4 characters.', category='error') status=400 else: new_user = User(username=username, password=generate_password_hash( password1, method='sha256'), name=name, email=email, role="User") db.session.add(new_user) db.session.commit() new_ev = Evehicle(car_id=car_id, brand=car_brand, model=car_model, user_id=new_user.id) db.session.add(new_ev) db.session.commit() login_user(new_user, remember=True) flash('Account created!', category='success') return redirect(url_for('views.home')) return render_template("sign_up.html", user=current_user), status
{"/website/views.py": ["/website/models.py"], "/main.py": ["/echarge/__init__.py"], "/echarge/models.py": ["/echarge/__init__.py"], "/echarge/__init__.py": ["/echarge/backend/__init__.py", "/echarge/models.py"], "/echarge/backend/auth.py": ["/echarge/models.py", "/echarge/__init__.py"], "/echarge/backend/sessions.py": ["/echarge/backend/auth.py", "/echarge/models.py"], "/echarge/backend/admin.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/auth.py"], "/echarge/backend/__init__.py": ["/echarge/backend/views.py", "/echarge/backend/auth.py", "/echarge/backend/admin.py", "/echarge/backend/sessions.py"], "/echarge/backend/views.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/sessions.py"]}
39,928,597
spiros26/Flask-Project
refs/heads/master
/echarge/backend/testing/test_in_chrome.py
import pytest #driver.get('http://www.thetestingworld.com/testings') from selenium import webdriver from selenium.webdriver import Chrome options = webdriver.ChromeOptions() options.add_argument('--ignore-ssl-errors=yes') options.add_argument('--ignore-certificate-errors') #driver = webdriver.Chrome(options=options) @pytest.fixture(scope="module") def set_path(): global driver #Place the path for the driver for your own machine below path = "driver//chromedriver.exe" driver = Chrome(executable_path=path, options=options) yield driver.close() def test_registration_valid_data(set_path): driver.get('http://localhost:8765/evcharge/api/Login?next=%2Fevcharge%2Fapi%2F') driver.maximize_window() assert "Login" == driver.title def test_registration_invalid_data(set_path): driver.get('http://localhost:8765/evcharge/api/Login?next=%2Fevcharge%2Fapi%2F') driver.maximize_window() assert driver.current_url == "http://localhost:8765/evcharge/api/Login?next=%2Fevcharge%2Fapi%2F" def test_valid_data(set_path): driver.get('http://localhost:8765/evcharge/api/Login?next=%2Fevcharge%2Fapi%2F') driver.maximize_window()
{"/website/views.py": ["/website/models.py"], "/main.py": ["/echarge/__init__.py"], "/echarge/models.py": ["/echarge/__init__.py"], "/echarge/__init__.py": ["/echarge/backend/__init__.py", "/echarge/models.py"], "/echarge/backend/auth.py": ["/echarge/models.py", "/echarge/__init__.py"], "/echarge/backend/sessions.py": ["/echarge/backend/auth.py", "/echarge/models.py"], "/echarge/backend/admin.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/auth.py"], "/echarge/backend/__init__.py": ["/echarge/backend/views.py", "/echarge/backend/auth.py", "/echarge/backend/admin.py", "/echarge/backend/sessions.py"], "/echarge/backend/views.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/sessions.py"]}
39,928,598
spiros26/Flask-Project
refs/heads/master
/echarge/backend/sessions.py
from flask import Blueprint, jsonify, request, make_response from .auth import token_required from ..models import Session, Point, Evehicle, Station, Operator, Energyprovider import json, datetime import pandas as pd import flask_csv as fcsv sessions = Blueprint('sessions', __name__) def sort_criteria(json): try: return (json.connection_date+json.connection_time) except KeyError: return 0 def nums_to_months(x): switcher = { "01": "Jan", "02": "Feb", "03": "Mar", "04": "Apr", "05": "May", "06": "Jun", "07": "Jul", "08": "Aug", "09": "Sep", "10": "Oct", "11": "Nov", "12": "Dec" } return switcher.get(x, "???") @sessions.route('/SessionsPerPoint/<pointID>/<date_from>/<date_to>', methods=['GET']) @token_required def ses_per_point(current_user, pointID, date_from, date_to): if current_user.role == "User": return make_response('Not allowed to perform this action!', 401) askformat = request.args.get('format', default='json', type=str) if askformat!='json' and askformat!='csv': return make_response('Cannot accept format. Supported formats are json (default) and csv.', 400) ses_list = [] objl = [] indexl = [] sessionl = [] startl = [] finishl = [] energyl = [] protocoll = [] paymentl = [] vehiclel = [] aa = 1 timestamp = datetime.datetime.now() point = Point.query.filter_by(point_id=pointID).first() station = Station.query.get(point.station_id) operator = Operator.query.get(station.operator_id) pool = Session.query.filter((Session.point_id==point.id) & (Session.connection_date>=date_from) & (Session.done_date<=date_to)).all() pool.sort(key=sort_criteria) for sample in pool: started_on = sample.connection_date[:4] + "-" + sample.connection_date[4:6] + "-" + sample.connection_date[6:] + " " + sample.connection_time[:2] + ":" + sample.connection_time[2:4] + ":" + sample.connection_time[4:] done_on = sample.done_date[:4] + "-" + sample.done_date[4:6] + "-" + sample.done_date[6:] + " " + sample.done_time[:2] + ":" + sample.done_time[2:4] + ":" + sample.done_time[4:] ev = Evehicle.query.get(sample.ev_id) if askformat=='json': ses_list.append({'SessionIndex': aa, 'SessionID': sample.session_id, 'StartedOn': started_on, 'FinishedOn': done_on, 'EnergyDelivered': sample.kWh_delivered, 'Protocol': sample.protocol, 'Payment': sample.payment ,'VehicleType': ev.car_type}) else: indexl.append(aa) sessionl.append(sample.session_id) startl.append(started_on) finishl.append(done_on) energyl.append(sample.kWh_delivered) protocoll.append(sample.protocol) paymentl.append(sample.payment) vehiclel.append(ev.car_type) aa = aa + 1 if askformat=='json': return jsonify({'Point': pointID, 'PointOperator': operator.name, 'RequestTimestamp': timestamp, 'PeriodFrom': date_from[:4]+" "+nums_to_months(date_from[4:6])+" "+date_from[6:], 'PeriodTo': date_to[:4]+" "+nums_to_months(date_to[4:6])+" "+date_to[6:], 'NumberOfChargingSessions': len(ses_list), 'ChargingSessionsList:': ses_list}) else: for x in range(0,len(pool)): objl.append({'Point': pointID, 'PointOperator': operator.name, 'RequestTimestamp': timestamp, 'PeriodFrom': date_from[:4]+" "+nums_to_months(date_from[4:6])+" "+date_from[6:], 'PeriodTo': date_to[:4]+" "+nums_to_months(date_to[4:6])+" "+date_to[6:], 'NumberOfChargingSessions': len(indexl), 'SessionIndex': indexl[x], 'SessionID': sessionl[x], 'StartedOn': startl[x], 'FinishedOn': finishl[x], 'EnergyDelivered': energyl[x], 'Protocol': protocoll[x], 'Payment': paymentl[x] ,'VehicleType': vehiclel[x]}) return fcsv.send_csv(objl, "reply.csv", ["Point", "PointOperator", "RequestTimestamp", "PeriodFrom", "PeriodTo", "NumberOfChargingSessions", "SessionIndex", "SessionID", "StartedOn", "FinishedOn", "EnergyDelivered", "Protocol", "Payment", "VehicleType"], delimiter=';') @sessions.route('/SessionsPerStation/<stationID>/<date_from>/<date_to>', methods=['GET']) @token_required def ses_per_station(current_user, stationID, date_from, date_to): if current_user.role == "User": return make_response('Not allowed to perform this action!', 401) askformat = request.args.get('format', default='json', type=str) if askformat!='json' and askformat!='csv': return make_response('Cannot accept format. Supported formats are json (default) and csv.', 400) points_list = [] objl = [] pointidl = [] pointsessionsl = [] energyl = [] timestamp = datetime.datetime.now() station = Station.query.filter_by(station_id=stationID).first() operator = Operator.query.get(station.operator_id) total_kWh_station = 0 total_sessions = 0 for point in station.points: total_kWh_point = 0 pool = Session.query.filter((Session.point_id==point.id) & (Session.connection_date>=date_from) & (Session.done_date<=date_to)).all() if len(pool) != 0: pool.sort(key=sort_criteria) for sample in pool: total_kWh_point = total_kWh_point + sample.kWh_delivered if askformat=='json': points_list.append({'PointID' : point.point_id, 'Sessions' : len(pool), 'EnergyDelivered' : total_kWh_point }) else: pointidl.append(point.point_id) pointsessionsl.append(len(pool)) energyl.append(total_kWh_point) total_kWh_station = total_kWh_station + total_kWh_point total_sessions = total_sessions + len(pool) if askformat=='json': return jsonify({'StationID': stationID, 'Operator': operator.name, 'RequestTimestamp': timestamp, 'PeriodFrom': date_from[:4]+" "+nums_to_months(date_from[4:6])+" "+date_from[6:], 'PeriodTo': date_to[:4]+" "+nums_to_months(date_to[4:6])+" "+date_to[6:], 'TotalEnergyDelivered' : total_kWh_station, 'NumberOfChargingSessions' : total_sessions, 'NumberOfActivePoints' : len(points_list), 'SessionsSummaryList': points_list}) else: for x in range(0,len(pointidl)): objl.append({'StationID': stationID, 'Operator': operator.name, 'RequestTimestamp': timestamp, 'PeriodFrom': date_from[:4]+" "+nums_to_months(date_from[4:6])+" "+date_from[6:], 'PeriodTo': date_to[:4]+" "+nums_to_months(date_to[4:6])+" "+date_to[6:], 'TotalEnergyDelivered' : total_kWh_station, 'NumberOfChargingSessions' : total_sessions, 'NumberOfActivePoints' : len(pointidl), 'PointID' : pointidl[x], 'PointsSessions' : pointsessionsl[x], 'EnergyDelivered' : energyl[x]}) return fcsv.send_csv(objl, "reply.csv", ["StationID", "Operator", "RequestTimestamp", "PeriodFrom", "PeriodTo", "TotalEnergyDelivered", "NumberOfChargingSessions", "NumberOfActivePoints", "PointID", "PointsSessions", "EnergyDelivered"], delimiter=';') @sessions.route('/SessionsPerEV/<vehicleID>/<date_from>/<date_to>', methods=['GET']) @token_required def ses_per_ev(current_user, vehicleID, date_from, date_to): if current_user.role == "User": return make_response('Not allowed to perform this action!', 401) askformat = request.args.get('format', default='json', type=str) if askformat!='json' and askformat!='csv': return make_response('Cannot accept format. Supported formats are json (default) and csv.', 400) ses_list = [] objl = [] indexl = [] sessionl = [] providerl = [] startl = [] finishl = [] energyl = [] pprl = [] kwhcost = [] sesscostl = [] ev = Evehicle.query.filter_by(car_id=vehicleID).first() timestamp = datetime.datetime.now() total_kWh = 0 costPerKWh = 0.15 aa = 1 visited_points = [] pool = Session.query.filter((Session.ev_id==ev.id) & (Session.connection_date>=date_from) & (Session.done_date<=date_to)).all() pool.sort(key=sort_criteria) for sample in pool: point = Point.query.get(sample.point_id) station = Station.query.get(point.station_id) provider = Energyprovider.query.get(station.provider_id) total_kWh = total_kWh + sample.kWh_delivered if sample.point_id not in visited_points: visited_points.append(sample.point_id) started_on = sample.connection_date[:4] + "-" + sample.connection_date[4:6] + "-" + sample.connection_date[6:] + " " + sample.connection_time[:2] + ":" + sample.connection_time[2:4] + ":" + sample.connection_time[4:] done_on = sample.done_date[:4] + "-" + sample.done_date[4:6] + "-" + sample.done_date[6:] + " " + sample.done_time[:2] + ":" + sample.done_time[2:4] + ":" + sample.done_time[4:] if sample.protocol == "Level 1: Low": cost_rate = 1 elif sample.protocol == "Level 2: Medium": cost_rate = 2 elif sample.protocol == "Level 3: High": cost_rate = 3 if askformat=='json': ses_list.append({'SessionIndex': aa, 'SessionID': sample.session_id, 'EnergyProvider' : provider.name, 'StartedOn': started_on, 'FinishedOn': done_on, 'EnergyDelivered': sample.kWh_delivered, 'PricePolicyRef': "Standard Pricing based on KWh delivered and Session Protocol. " + "e.g: Session cost = cost_rate*kWh_delivered*costPerKWh " + "where cost_rate = 1 (Session Protocol = Level 1: Low) / cost_rate = 2 (Session Protocol = Level 2: Medium) / cost_rate = 3 (Session Protocol = Level 3: High)", 'CostPerKWh': costPerKWh ,'SessionCost': round(cost_rate*costPerKWh*sample.kWh_delivered, 2)}) else: indexl.append(aa) sessionl.append(sample.session_id) providerl.append(provider.name) startl.append(started_on) finishl.append(done_on) energyl.append(sample.kWh_delivered) pprl.append("Standard Pricing based on KWh delivered and Session Protocol. " + "e.g: Session cost = cost_rate*kWh_delivered*costPerKWh " + "where cost_rate = 1 (Session Protocol = Level 1: Low) / cost_rate = 2 (Session Protocol = Level 2: Medium) / cost_rate = 3 (Session Protocol = Level 3: High)") kwhcost.append(costPerKWh) sesscostl.append(round(cost_rate*costPerKWh*sample.kWh_delivered, 2)) aa = aa + 1 if askformat=='json': return jsonify({'VehicleID': vehicleID, 'RequestTimestamp': timestamp, 'PeriodFrom': date_from[:4]+" "+nums_to_months(date_from[4:6])+" "+date_from[6:], 'PeriodTo': date_to[:4]+" "+nums_to_months(date_to[4:6])+" "+date_to[6:], 'TotalEnergyConsumed' : total_kWh, 'NumberOfVisitedPoints' : len(visited_points), 'NumberOfVehicleChargingSessions' : len(ses_list), 'VehicleChargingSessionsList': ses_list}) else: for x in range(0,len(pool)): objl.append({'VehicleID': vehicleID, 'RequestTimestamp': timestamp, 'PeriodFrom': date_from[:4]+" "+nums_to_months(date_from[4:6])+" "+date_from[6:], 'PeriodTo': date_to[:4]+" "+nums_to_months(date_to[4:6])+" "+date_to[6:], 'TotalEnergyConsumed' : total_kWh, 'NumberOfVisitedPoints' : len(visited_points), 'NumberOfVehicleChargingSessions' : len(pool), 'SessionIndex': indexl[x], 'SessionID': sessionl[x], 'EnergyProvider' : providerl[x], 'StartedOn': startl[x], 'FinishedOn': finishl[x], 'EnergyDelivered': energyl[x], 'PricePolicyRef': pprl[x], 'CostPerKWh': kwhcost[x] ,'SessionCost': round(sesscostl[x],2)}) return fcsv.send_csv(objl, "reply.csv", ["VehicleID", "RequestTimestamp", "PeriodFrom", "PeriodTo", "TotalEnergyConsumed", "NumberOfVisitedPoints", "NumberOfVehicleChargingSessions", "SessionIndex", "SessionID", "EnergyProvider", "StartedOn", "FinishedOn", "EnergyDelivered", "PricePolicyRef", "CostPerKWh", "SessionCost"], delimiter=';') @sessions.route('/SessionsPerProvider/<providerID>/<date_from>/<date_to>', methods=['GET']) @token_required def ses_per_provider(current_user, providerID, date_from, date_to): if current_user.role == "User": return make_response('Not allowed to perform this action!', 401) askformat = request.args.get('format', default='json', type=str) if askformat!='json' and askformat!='csv': return make_response('Cannot accept format. Supported formats are json (default) and csv.', 400) sess_list = [] costPerKWh = 0.15 poolall = [] objl = [] stationidl = [] sessionidl = [] vehicleidl = [] startl = [] finishl = [] energyl = [] pprl = [] kwhcostl = [] totalcostl = [] provider = Energyprovider.query.filter_by(provider_id=providerID).first() for station in provider.stations: for point in station.points: pool = Session.query.filter((Session.point_id==point.id) & (Session.connection_date>=date_from) & (Session.done_date<=date_to)).all() poolall = poolall + pool poolall.sort(key=sort_criteria) for sample in poolall: point = Point.query.filter_by(id=sample.point_id).first() station = Station.query.filter_by(id=point.station_id).first() ev = Evehicle.query.filter_by(id=sample.ev_id).first() if sample.protocol == "Level 1: Low": cost_rate = 1 elif sample.protocol == "Level 2: Medium": cost_rate = 2 elif sample.protocol == "Level 3: High": cost_rate = 3 started_on = sample.connection_date[:4] + "-" + sample.connection_date[4:6] + "-" + sample.connection_date[6:] + " " + sample.connection_time[:2] + ":" + sample.connection_time[2:4] + ":" + sample.connection_time[4:] done_on = sample.done_date[:4] + "-" + sample.done_date[4:6] + "-" + sample.done_date[6:] + " " + sample.done_time[:2] + ":" + sample.done_time[2:4] + ":" + sample.done_time[4:] if askformat=='json': sess_list.append({ 'StationID': station.station_id, 'SessionID': sample.session_id, 'VehicleID': ev.car_id, 'StartedOn': started_on, 'FinishedOn': done_on, 'EnergyDelivered': sample.kWh_delivered, 'PricePolicyRef': "Standard Pricing based on KWh delivered and Session Protocol. " + "e.g: Session cost = cost_rate*kWh_delivered*costPerKWh " + "where cost_rate = 1 (Session Protocol = Level 1: Low) / cost_rate = 2 (Session Protocol = Level 2: Medium) / cost_rate = 3 (Session Protocol = Level 3: High)", 'CostPerKWh': costPerKWh, 'TotalCost': round(cost_rate*costPerKWh*sample.kWh_delivered, 2)}) else: stationidl.append(station.station_id) sessionidl.append(sample.session_id) vehicleidl.append(ev.car_id) startl.append(started_on) finishl.append(done_on) energyl.append(sample.kWh_delivered) pprl.append("Standard Pricing based on KWh delivered and Session Protocol. " + "e.g: Session cost = cost_rate*kWh_delivered*costPerKWh " + "where cost_rate = 1 (Session Protocol = Level 1: Low) / cost_rate = 2 (Session Protocol = Level 2: Medium) / cost_rate = 3 (Session Protocol = Level 3: High)") kwhcostl.append(costPerKWh) totalcostl.append(round(cost_rate*costPerKWh*sample.kWh_delivered, 2)) if askformat=='json': return jsonify({'ProviderID': providerID, 'ProviderName': provider.name, 'ProviderChargingSessionsList': sess_list}) else: for x in range(0,len(poolall)): objl.append({'ProviderID': providerID, 'ProviderName': provider.name, 'StationID': stationidl[x], 'SessionID': sessionidl[x], 'VehicleID': vehicleidl[x], 'StartedOn': startl[x], 'FinishedOn': finishl[x], 'EnergyDelivered': energyl[x], 'PricePolicyRef': pprl[x], 'CostPerKWh': kwhcostl[x], 'TotalCost': round(totalcostl[x], 2)}) return fcsv.send_csv(objl, "reply.csv", ["ProviderID", "ProviderName", "StationID", "SessionID", "VehicleID", "StartedOn", "FinishedOn", "EnergyDelivered", "PricePolicyRef", "CostPerKWh", "TotalCost"], delimiter=';')
{"/website/views.py": ["/website/models.py"], "/main.py": ["/echarge/__init__.py"], "/echarge/models.py": ["/echarge/__init__.py"], "/echarge/__init__.py": ["/echarge/backend/__init__.py", "/echarge/models.py"], "/echarge/backend/auth.py": ["/echarge/models.py", "/echarge/__init__.py"], "/echarge/backend/sessions.py": ["/echarge/backend/auth.py", "/echarge/models.py"], "/echarge/backend/admin.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/auth.py"], "/echarge/backend/__init__.py": ["/echarge/backend/views.py", "/echarge/backend/auth.py", "/echarge/backend/admin.py", "/echarge/backend/sessions.py"], "/echarge/backend/views.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/sessions.py"]}
39,928,599
spiros26/Flask-Project
refs/heads/master
/echarge/backend/admin.py
from flask import Blueprint, render_template, request, flash, redirect, url_for, jsonify, Response, make_response from ..models import User, Session, Evehicle, Point from werkzeug.security import generate_password_hash, check_password_hash from .. import db, default_admin, months_to_nums import uuid import json import pandas as pd from .auth import token_required import random import os import flask_csv as fcsv admin = Blueprint('admin', __name__) @admin.route('/admin/usermod/<username>/<password>/<role>', methods=['POST']) @token_required def usermod(current_user, username, password, role): if current_user.role != "Admin": return make_response('Not allowed to perform this action!', 401) if role not in ["User", "Privileged", "Admin"]: return make_response('Not valid role! Valid roles are: User, Privileged, Admin', 400) user = User.query.filter_by(username=username).first() hashed_password = generate_password_hash(password, method='sha256') if not user: new_user = User(public_id=str(uuid.uuid4()), username=username, password=hashed_password, role=role) db.session.add(new_user) db.session.commit() return make_response('New stakeholder successfully created!') user.password = hashed_password user.role = role db.session.commit() return make_response('Stakeholder\'s password/role updated successfully!') @admin.route('/admin/users/<username>', methods=['GET']) @token_required def users(current_user, username): if current_user.role != "Admin": return make_response('Not allowed to perform this action!', 401) askformat = request.args.get('format', default='json', type=str) if askformat!='json' and askformat!='csv': return make_response('Cannot accept format. Supported formats are json (default) and csv.', 400) user = User.query.filter_by(username=username).first() if not user: return make_response('The user was not found!', 400) if askformat=='json': return jsonify({'username' : user.username, 'hashed_password' : user.password, 'name' : user.name, 'email' : user.email, 'role' : user.role}) else: return fcsv.send_csv([{'username' : user.username, 'hashed_password' : user.password, 'name' : user.name, 'email' : user.email, 'role' : user.role}], "reply.csv", ["username", "hashed_password", "name", "email", "role"], delimiter=';') @admin.route('/admin/healthcheck', methods=['GET']) @token_required def healthcheck(current_user): if current_user.role != "Admin": return make_response('Not allowed to perform this action!', 401) try: cnt = User.query.count() return jsonify({'status' : 'OK'}) except: return jsonify({'status' : 'failed'}), 400 @admin.route('/admin/resetsessions', methods=['POST']) @token_required def resetsessions(current_user): if current_user.role != "Admin": return make_response('Not allowed to perform this action!', 401) try: num_sessions_deleted = db.session.query(Session).delete() db.session.commit() default_admin('admin','petrol4ever') return jsonify({'status' : 'OK'}) except: return jsonify({'status' : 'failed'}), 400 @admin.route('/admin/system/sessionsupd', methods=['POST']) @token_required def sessions_update(current_user): if current_user.role != "Admin": return make_response('Not allowed to perform this action!', 401) askformat = request.args.get('format', default='json', type=str) if askformat!='json' and askformat!='csv': return make_response('Cannot accept format. Supported formats are json (default) and csv.', 400) filename = request.form.get('file') if filename.endswith("json"): with open(filename) as jsdata: sess = json.load(jsdata) try: cont = pd.DataFrame(sess['_items']) length = cont.shape[0] sessions_imported = 0 sessions_in_db = 0 ev_table = Evehicle.query.all() point_table = Point.query.all() payment_table = ["Credit_Card", "Debit_Card", "Smartphone_Wallet", "Website_Payment", "QR_Code", "Cash"] for x in range(0,length): check = Session.query.filter_by(session_id=cont["_id"][x]).first() if not check and isinstance(cont["connectionTime"][x], str) and isinstance(cont["doneChargingTime"][x], str) and isinstance(cont["disconnectTime"][x], str): edit_start = cont["connectionTime"][x] year_start = edit_start[12:16] month_start = months_to_nums(edit_start[8:11]) day_start = edit_start[5:7] time_start = edit_start[17:19]+edit_start[20:22]+edit_start[23:25] edit_fin = cont["doneChargingTime"][x] year_fin = edit_fin[12:16] month_fin = months_to_nums(edit_fin[8:11]) day_fin = edit_fin[5:7] time_fin = edit_fin[17:19]+edit_fin[20:22]+edit_fin[23:25] edit_dis = cont["disconnectTime"][x] year_dis = edit_dis[12:16] month_dis = months_to_nums(edit_dis[8:11]) day_dis = edit_dis[5:7] time_dis = edit_dis[17:19]+edit_dis[20:22]+edit_dis[23:25] begin = int(time_start[:2])*60+int(time_start[2:4]) end = 0 if day_start!=day_fin: end = 1440 end = end + int(time_fin[:2])*60+int(time_fin[2:4]) space = end - begin if space==0: space = 1 rate = (cont["kWhDelivered"][x]*60)/space if rate < 5.0: protocol = "Level 1: Low" elif rate < 25.0: protocol = "Level 2: Medium" else: protocol = "Level 3: High" ev = random.choice(ev_table) point = random.choice(point_table) payment = random.choice(payment_table) new_session = Session(session_id=cont["_id"][x], connection_date=year_start+month_start+day_start, connection_time=time_start, done_date=year_fin+month_fin+day_fin, done_time=time_fin, disconnection_date=year_dis+month_dis+day_dis, disconnection_time=time_dis, kWh_delivered = cont["kWhDelivered"][x], protocol=protocol ,payment=payment ,ev_id=ev.id, point_id=point.id) db.session.add(new_session) db.session.commit() sessions_imported = sessions_imported + 1 sessions_in_db = Session.query.count() if askformat=='json': return jsonify({'SessionsInUploadedFile' : length, 'SessionsImported' : sessions_imported, 'TotalSessionsInDatabase' : sessions_in_db}) else: return fcsv.send_csv([{'SessionsInUploadedFile' : length, 'SessionsImported' : sessions_imported, 'TotalSessionsInDatabase' : sessions_in_db}], "reply.csv", ["SessionsInUploadedFile", "SessionsImported", "TotalSessionsInDatabase"], delimiter=';') except: return make_response('Data in this file are not in the supported format. Please try again with a file with valid data.', 400) else: return make_response('Cannot accept this file type. Supported file type is json', 400)
{"/website/views.py": ["/website/models.py"], "/main.py": ["/echarge/__init__.py"], "/echarge/models.py": ["/echarge/__init__.py"], "/echarge/__init__.py": ["/echarge/backend/__init__.py", "/echarge/models.py"], "/echarge/backend/auth.py": ["/echarge/models.py", "/echarge/__init__.py"], "/echarge/backend/sessions.py": ["/echarge/backend/auth.py", "/echarge/models.py"], "/echarge/backend/admin.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/auth.py"], "/echarge/backend/__init__.py": ["/echarge/backend/views.py", "/echarge/backend/auth.py", "/echarge/backend/admin.py", "/echarge/backend/sessions.py"], "/echarge/backend/views.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/sessions.py"]}
39,928,600
spiros26/Flask-Project
refs/heads/master
/echarge/backend/testing/test_create_user.py
import requests import json import jsonpath import pytest def test_create_new_user(): url = "http://localhost:8765/evcharge/api/sign-up" file = open("user.json", 'r') json_input = file.read() request_json = json.loads(json_input) response = requests.post(url,request_json) assert response.status_code == 400 def test_login_user(): url = "http://localhost:8765/evcharge/api/Login" file = open("user2.json", 'r') json_input = file.read() request_json = json.loads(json_input) response = requests.post(url,request_json) assert response.status_code == 200 def test_failed_login_user(): url = "http://localhost:8765/evcharge/api/Login" file = open("user3.json", 'r') json_input = file.read() request_json = json.loads(json_input) response = requests.post(url,request_json) assert response.status_code == 400 def test_logout(): url = "http://localhost:8765/evcharge/api/Logout" response = requests.get(url) assert response.status_code == 200
{"/website/views.py": ["/website/models.py"], "/main.py": ["/echarge/__init__.py"], "/echarge/models.py": ["/echarge/__init__.py"], "/echarge/__init__.py": ["/echarge/backend/__init__.py", "/echarge/models.py"], "/echarge/backend/auth.py": ["/echarge/models.py", "/echarge/__init__.py"], "/echarge/backend/sessions.py": ["/echarge/backend/auth.py", "/echarge/models.py"], "/echarge/backend/admin.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/auth.py"], "/echarge/backend/__init__.py": ["/echarge/backend/views.py", "/echarge/backend/auth.py", "/echarge/backend/admin.py", "/echarge/backend/sessions.py"], "/echarge/backend/views.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/sessions.py"]}
39,928,601
spiros26/Flask-Project
refs/heads/master
/echarge/backend/__init__.py
from .views import views from .auth import auth from .admin import admin from .sessions import sessions
{"/website/views.py": ["/website/models.py"], "/main.py": ["/echarge/__init__.py"], "/echarge/models.py": ["/echarge/__init__.py"], "/echarge/__init__.py": ["/echarge/backend/__init__.py", "/echarge/models.py"], "/echarge/backend/auth.py": ["/echarge/models.py", "/echarge/__init__.py"], "/echarge/backend/sessions.py": ["/echarge/backend/auth.py", "/echarge/models.py"], "/echarge/backend/admin.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/auth.py"], "/echarge/backend/__init__.py": ["/echarge/backend/views.py", "/echarge/backend/auth.py", "/echarge/backend/admin.py", "/echarge/backend/sessions.py"], "/echarge/backend/views.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/sessions.py"]}
39,928,602
spiros26/Flask-Project
refs/heads/master
/echarge/backend/views.py
from flask import Blueprint, render_template, request, flash, jsonify, redirect, url_for from flask_login import login_required, current_user from ..models import Session, User, Evehicle, Point, Station from .. import db import json, uuid, random from datetime import datetime, date, timedelta from .sessions import sort_criteria views = Blueprint('views', __name__) def cost_rate(protocol): if protocol =="Level 1: Low": return 1 elif protocol =="Level 2: Medium": return 2 return 3 def station_cords(): reply = [] stationlist = Station.query.all() for station in stationlist: if isinstance(station.website, str) and len(station.website)>5: reply.append({'type': 'Feature', 'properties': { 'description': f'<strong>{station.name}</strong><p> <br> Address: {station.address} <br> Number of charging points: {len(station.points)} <br> Point Ids List: {[x.point_id for x in station.points]} <br> Telephone: {station.phone} <br> E-mail: {station.email} <br> Website: <a href={station.website} target="_blank" title="Opens in a new window">{station.website}</a></p>', 'icon': 'charging-station' }, 'geometry': { 'type': 'Point', 'coordinates': [float(station.longitude), float(station.latitude)] } }) else: reply.append({'type': 'Feature', 'properties': { 'description': f'<strong>{station.name}</strong><p> <br> Address: {station.address} <br> Number of charging points: {len(station.points)} <br> Point Ids List: {[x.point_id for x in station.points]} <br> Telephone: {station.phone} <br> E-mail: {station.email}</p>', 'icon': 'charging-station' }, 'geometry': { 'type': 'Point', 'coordinates': [float(station.longitude), float(station.latitude)] } }) return reply @views.route('/', methods=['GET', 'POST']) @login_required def home(): status=200 if request.method == 'POST': car_id = request.form.get('car_id') kWh_Requested = request.form.get('kWh_Requested') protocol = request.form.get('protocol') payment = request.form.get('payment') point_id = request.form.get('point') car = Evehicle.query.filter_by(car_id=car_id).first() point = Point.query.filter_by(point_id=point_id).first() if car not in current_user.evs: flash('Car id is invalid!', category='error') status=400 elif protocol not in ["Level 1: Low", "Level 2: Medium", "Level 3: High"]: flash('Protocol is invalid!', category='error') status=400 elif payment not in ["Credit_Card", "Debit_Card", "Smartphone_Wallet", "Website_Payment", "QR_Code", "Cash"]: flash('Payment Method is invalid!', category='error') status=400 elif not point: flash('Point id is invalid!', category='error') status=400 else: if protocol == "Level 1: Low": rate = random.uniform(2.0, 5.0) elif protocol == "Level 2: Medium": rate = random.uniform(10.0, 25.0) elif protocol == "Level 3: High": rate = random.uniform(40.0, 60.0) connection_time = datetime.now().strftime("%H%M%S") connection_date = datetime.now().strftime("%Y%m%d") done_time = (datetime.now() + timedelta(seconds=int(float(kWh_Requested)*3600/rate))).strftime("%H%M%S") done_date = (datetime.now() + timedelta(seconds=int(float(kWh_Requested)*3600/rate))).strftime("%Y%m%d") new_charging_session = Session(session_id=str(uuid.uuid4()), connection_date=connection_date, connection_time=connection_time, done_date=done_date, done_time=done_time, disconnection_date="??????", disconnection_time="??????", kWh_delivered=float(kWh_Requested), protocol=protocol, payment=payment, point_id=point.id, ev_id=car.id) db.session.add(new_charging_session) db.session.commit() flash('Wait for charging process!', category='success') return redirect(url_for('views.charging', sessionID=new_charging_session.session_id)) return render_template("home.html", user=current_user), status @views.route('/charging/<sessionID>', methods=['GET', 'POST']) @login_required def charging(sessionID): current_session = Session.query.filter_by(session_id=sessionID).first() if request.method == 'POST': current_session.disconnection_date = (datetime.now()).strftime("%Y%m%d") current_session.disconnection_time = (datetime.now()).strftime("%H%M%S") if current_session.disconnection_time < current_session.done_time and current_session.disconnection_date <= current_session.done_date: current_session.kWh_delivered = current_session.kWh_delivered*(int(datetime.now().strftime("%H%M%S"))-int(current_session.connection_time))/(int(current_session.done_time)-int(current_session.connection_time)) current_session.done_time = datetime.now().strftime("%H%M%S") current_session.done_date = current_session.disconnection_date db.session.commit() flash('Charging stopped!', category='success') return redirect(url_for('views.home')) connection = 1000*int(datetime(int(current_session.connection_date[:4]), int(current_session.connection_date[4:6]), int(current_session.connection_date[6:8]), int(current_session.connection_time[:2]), int(current_session.connection_time[2:4]), int(current_session.connection_time[4:6]) ).timestamp()) finish = 1000*int(datetime(int(current_session.done_date[:4]), int(current_session.done_date[4:6]), int(current_session.done_date[6:8]), int(current_session.done_time[:2]), int(current_session.done_time[2:4]), int(current_session.done_time[4:6]) ).timestamp()) duration = finish - connection return render_template("charging.html", user=current_user, duration=duration, session=current_session, connection=connection) @views.route('/issue-statement/<datefrom>/<dateto>', methods=['GET', 'POST']) @login_required def view_sessions(datefrom, dateto): if request.method == 'POST': if request.form.get("opta"): flash('The statement has been successfully issued!', category='success') return redirect(url_for('views.home')) elif request.form.get("optb"): return redirect(url_for('views.chart', datefrom=datefrom, dateto=dateto)) sessions = [] date_from = datefrom[:4] + datefrom[5:7] + datefrom[8:] date_to = dateto[:4] + dateto[5:7] + dateto[8:] for i in range(len(current_user.evs)): pool = Session.query.filter((Session.ev_id==current_user.evs[i].id) & (Session.connection_date>=date_from) & (Session.done_date<=date_to)).all() sessions = sessions + pool sessions.sort(key=sort_criteria) return render_template("view_sessions.html", user=current_user, sessions=sessions, datefrom=datefrom, dateto=dateto) @views.route('/statement_filters', methods=['GET', 'POST']) @login_required def statement_filters(): status=200 if request.method == 'POST': datefrom = request.form.get('datefrom') dateto = request.form.get('dateto') if not datefrom or not dateto: flash('Select filters', category='error') status=400 else: flash('Statement filters have been applied!', category='success') return redirect(url_for('views.view_sessions', datefrom=datefrom, dateto=dateto)) return render_template("statement_filters.html", user=current_user), status @views.route('/delete-session', methods=['POST']) def delete_session(): session = json.loads(request.data) sessionId = session['sessionId'] session = Session.query.get(sessionId) ev = Evehicle.query.get(session.ev_id) if session: if ev.user_id == current_user.id: db.session.delete(session) db.session.commit() return jsonify({}) @views.route('/find_station_near_you', methods=['GET']) def my_maps(): mapbox_access_token = 'pk.eyJ1IjoidGhhbm9zYmIzIiwiYSI6ImNrbTduZGEwYzBrb2cyb2xhOXI5MXowcnEifQ.Yj-JHpwSZreC1Z1-FVhIsA' return render_template('map_index.html', user = current_user, mapbox_access_token=mapbox_access_token, POIs=station_cords()) @views.route('/chart/<datefrom>/<dateto>', methods=['GET', 'POST']) @login_required def chart(datefrom, dateto): if request.method == 'POST': if request.form.get("back"): return redirect(url_for('views.view_sessions', datefrom=datefrom, dateto=dateto)) elif request.form.get("plot"): y = request.form.get('axis_y') x = request.form.get('axis_x') sessions = [] date_from = datefrom[:4] + datefrom[5:7] + datefrom[8:] date_to = dateto[:4] + dateto[5:7] + dateto[8:] #startdate = datefrom[8:] + "/" + datefrom[5:7] + "/" + datefrom[:4] for i in range(len(current_user.evs)): pool = Session.query.filter((Session.ev_id==current_user.evs[i].id) & (Session.connection_date>=date_from) & (Session.done_date<=date_to)).all() sessions = sessions + pool sessions.sort(key=sort_criteria) hor = [] ver = [] if x=="Index": temp = 1 for item in sessions: hor.append(temp) temp = temp + 1 money_spent = 0 kwh = 0 if y=="total_money": for item in sessions: money_spent = round(money_spent + cost_rate(item.protocol)*0.15*item.kWh_delivered, 2) ver.append(money_spent) title = "Total Money Paid for Sessions" elif y=="money": for item in sessions: ver.append(round(cost_rate(item.protocol)*0.15*item.kWh_delivered,2)) title = "Money Paid for Each Session" elif y=="total_kwh": for item in sessions: kwh = round(kwh + item.kWh_delivered, 2) ver.append(kwh) title = "Total KWh Delivered during Sessions" else: for item in sessions: ver.append(round(item.kWh_delivered, 2)) title = "KWh Delivered during Each Session" else: item = sessions[0] check = item.connection_date[6:8]+"/"+item.connection_date[4:6]+"/"+item.connection_date[:4] hor.append(check) for item in sessions: new = item.connection_date[6:8]+"/"+item.connection_date[4:6]+"/"+item.connection_date[:4] if check!=new: hor.append(new) check = new money_spent = 0 kwh = 0 index = 0 check = "0" if y=="total_money": for item in sessions: money_spent = round(money_spent + cost_rate(item.protocol)*0.15*item.kWh_delivered, 2) if check!=item.connection_date: ver.append(money_spent) if check!="0": index = index + 1 check = item.connection_date else: ver[index] = money_spent title = "Total Money Paid for Sessions" elif y=="money": for item in sessions: if check!=item.connection_date: ver.append(round(cost_rate(item.protocol)*0.15*item.kWh_delivered,2)) if check!="0": index = index + 1 check = item.connection_date else: ver[index] = (round(ver[index] + cost_rate(item.protocol)*0.15*item.kWh_delivered, 2)) title = "Money Paid on Each Date" elif y=="total_kwh": for item in sessions: kwh = round(kwh + item.kWh_delivered, 2) if check!= item.connection_date: ver.append(kwh) if check!="0": index = index + 1 check = item.connection_date else: ver[index] = kwh title = "Total KWh Delivered during Sessions" else: for item in sessions: if check!= item.connection_date: ver.append(round(item.kWh_delivered,2)) if check!="0": index = index + 1 check = item.connection_date else: ver[index] = round(ver[index] + item.kWh_delivered,2) title = "KWh Delivered on Date" return render_template('chart.html', user = current_user, title=title, max=max(ver), labels=hor, values=ver, y=y, x=x) sessions = [] date_from = datefrom[:4] + datefrom[5:7] + datefrom[8:] date_to = dateto[:4] + dateto[5:7] + dateto[8:] for i in range(len(current_user.evs)): pool = Session.query.filter((Session.ev_id==current_user.evs[i].id) & (Session.connection_date>=date_from) & (Session.done_date<=date_to)).all() sessions = sessions + pool sessions.sort(key=sort_criteria) y = 1 money_spent = 0 cost = [] sesindex = [] for x in sessions: sesindex.append(y) money_spent = round(money_spent + cost_rate(x.protocol)*0.15*x.kWh_delivered, 2) cost.append(money_spent) y = y + 1 return render_template('chart.html', user = current_user, title="Total Money Paid", max=money_spent, labels=sesindex, values=cost, y=y, x=x)
{"/website/views.py": ["/website/models.py"], "/main.py": ["/echarge/__init__.py"], "/echarge/models.py": ["/echarge/__init__.py"], "/echarge/__init__.py": ["/echarge/backend/__init__.py", "/echarge/models.py"], "/echarge/backend/auth.py": ["/echarge/models.py", "/echarge/__init__.py"], "/echarge/backend/sessions.py": ["/echarge/backend/auth.py", "/echarge/models.py"], "/echarge/backend/admin.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/auth.py"], "/echarge/backend/__init__.py": ["/echarge/backend/views.py", "/echarge/backend/auth.py", "/echarge/backend/admin.py", "/echarge/backend/sessions.py"], "/echarge/backend/views.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/sessions.py"]}
39,928,603
spiros26/Flask-Project
refs/heads/master
/echarge/cli/ev_group36/commands/cmd_SessionsPerPoint.py
import click import requests url = "http://localhost:8765/evcharge/api/SessionsPerPoint/" class Context: def __init__(self, point, datefrom, dateto, format, apikey): self.point = point self.datefrom = datefrom self.dateto = dateto self.format = format self.apikey = apikey @click.group() @click.option("--point") @click.option("--datefrom") @click.option("--dateto") @click.option("--format", default="json", show_default=True) @click.option("--apikey") @click.pass_context def cli(ctx, point, datefrom, dateto, format, apikey): ctx.obj = Context(point, datefrom, dateto, format, apikey) @cli.command() @click.pass_context def show(ctx): response = requests.get(url + ctx.obj.point + "/" + ctx.obj.datefrom + "/" + ctx.obj.dateto + "?format=" + ctx.obj.format, headers = {'X-OBSERVATORY-AUTH':ctx.obj.apikey}) print(response.text)
{"/website/views.py": ["/website/models.py"], "/main.py": ["/echarge/__init__.py"], "/echarge/models.py": ["/echarge/__init__.py"], "/echarge/__init__.py": ["/echarge/backend/__init__.py", "/echarge/models.py"], "/echarge/backend/auth.py": ["/echarge/models.py", "/echarge/__init__.py"], "/echarge/backend/sessions.py": ["/echarge/backend/auth.py", "/echarge/models.py"], "/echarge/backend/admin.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/auth.py"], "/echarge/backend/__init__.py": ["/echarge/backend/views.py", "/echarge/backend/auth.py", "/echarge/backend/admin.py", "/echarge/backend/sessions.py"], "/echarge/backend/views.py": ["/echarge/models.py", "/echarge/__init__.py", "/echarge/backend/sessions.py"]}
39,972,364
Ernir/ernir.net
refs/heads/main
/homepage/schema.py
import graphene from graphene_django.types import DjangoObjectType from homepage.models import FrontPageSection class FrontPageSectionType(DjangoObjectType): class Meta: model = FrontPageSection class Query(object): all_frontpage_sections = graphene.List(FrontPageSectionType) def resolve_all_frontpage_sections(self, info, **kwargs): return FrontPageSection.objects.all()
{"/photos/schema.py": ["/photos/models.py"], "/recipes/models.py": ["/recipes/managers.py"], "/asylum/schema.py": ["/asylum/models.py"], "/recipes/schema.py": ["/recipes/models.py"], "/schema.py": ["/asylum/schema.py", "/homepage/schema.py", "/photos/schema.py", "/recipes/schema.py"], "/recipes/admin.py": ["/recipes/models.py"], "/homepage/schema.py": ["/homepage/models.py"], "/photos/management/commands/read_photos.py": ["/photos/models.py"], "/homepage/admin.py": ["/homepage/models.py"], "/asylum/admin.py": ["/asylum/models.py"]}
39,972,365
Ernir/ernir.net
refs/heads/main
/homepage/models.py
from adminsortable.models import SortableMixin from django.db import models from markdownx.models import MarkdownxField class FrontPageSection(SortableMixin): main_text = MarkdownxField() # A field the model should be ordered by the_order = models.PositiveIntegerField(default=0, editable=False, db_index=True) def __str__(self): return self.main_text.split("\n")[0] class Meta: ordering = ("the_order",)
{"/photos/schema.py": ["/photos/models.py"], "/recipes/models.py": ["/recipes/managers.py"], "/asylum/schema.py": ["/asylum/models.py"], "/recipes/schema.py": ["/recipes/models.py"], "/schema.py": ["/asylum/schema.py", "/homepage/schema.py", "/photos/schema.py", "/recipes/schema.py"], "/recipes/admin.py": ["/recipes/models.py"], "/homepage/schema.py": ["/homepage/models.py"], "/photos/management/commands/read_photos.py": ["/photos/models.py"], "/homepage/admin.py": ["/homepage/models.py"], "/asylum/admin.py": ["/asylum/models.py"]}
39,972,366
Ernir/ernir.net
refs/heads/main
/homepage/admin.py
from adminsortable.admin import SortableAdmin from django.contrib import admin from markdownx.admin import MarkdownxModelAdmin from .models import FrontPageSection @admin.register(FrontPageSection) class FrontPageAdmin(SortableAdmin, MarkdownxModelAdmin): pass
{"/photos/schema.py": ["/photos/models.py"], "/recipes/models.py": ["/recipes/managers.py"], "/asylum/schema.py": ["/asylum/models.py"], "/recipes/schema.py": ["/recipes/models.py"], "/schema.py": ["/asylum/schema.py", "/homepage/schema.py", "/photos/schema.py", "/recipes/schema.py"], "/recipes/admin.py": ["/recipes/models.py"], "/homepage/schema.py": ["/homepage/models.py"], "/photos/management/commands/read_photos.py": ["/photos/models.py"], "/homepage/admin.py": ["/homepage/models.py"], "/asylum/admin.py": ["/asylum/models.py"]}
39,972,367
Ernir/ernir.net
refs/heads/main
/schema.py
import graphene import homepage.schema import photos.schema import asylum.schema class Query( asylum.schema.Query, photos.schema.Query, homepage.schema.Query, graphene.ObjectType ): pass schema = graphene.Schema(query=Query)
{"/photos/schema.py": ["/photos/models.py"], "/recipes/models.py": ["/recipes/managers.py"], "/asylum/schema.py": ["/asylum/models.py"], "/recipes/schema.py": ["/recipes/models.py"], "/schema.py": ["/asylum/schema.py", "/homepage/schema.py", "/photos/schema.py", "/recipes/schema.py"], "/recipes/admin.py": ["/recipes/models.py"], "/homepage/schema.py": ["/homepage/models.py"], "/photos/management/commands/read_photos.py": ["/photos/models.py"], "/homepage/admin.py": ["/homepage/models.py"], "/asylum/admin.py": ["/asylum/models.py"]}