From edcfd3e9f4aa6cae8ca257cfca706060238581fb Mon Sep 17 00:00:00 2001 From: Siarhei Puhach Date: Thu, 29 Jun 2017 17:34:40 +0300 Subject: [PATCH 01/14] Added Flake8 lib and fixed PEP8 violations --- .travis.yml | 6 +- alplora/admin.py | 2 +- alplora/models.py | 2 +- alplora/tests.py | 2 +- alplora/urls.py | 4 +- alplora/views.py | 6 +- datacenterlight/forms.py | 2 +- datacenterlight/templatetags/custom_tags.py | 8 +- datacenterlight/tests.py | 2 +- datacenterlight/views.py | 37 +++--- digitalglarus/admin.py | 2 +- digitalglarus/cms_plugins.py | 18 +-- digitalglarus/forms.py | 3 +- digitalglarus/management/commands/list.py | 3 +- digitalglarus/management/commands/plans.py | 14 +-- digitalglarus/models.py | 9 +- digitalglarus/test_views.py | 3 +- digitalglarus/views.py | 7 +- dynamicweb/settings-test/__init__.py | 9 +- dynamicweb/settings/__init__.py | 2 +- dynamicweb/settings/base.py | 23 ++-- dynamicweb/settings/local.py | 10 +- dynamicweb/settings/prod.py | 11 +- dynamicweb/urls.py | 31 ++--- dynamicweb/wsgi.py | 10 +- hosting/admin.py | 4 - hosting/forms.py | 9 +- .../management/commands/create_vm_types.py | 20 ++-- hosting/models.py | 11 +- hosting/templates/hosting/payment.html | 14 +-- hosting/test_views.py | 2 +- hosting/tests.py | 8 +- hosting/views.py | 42 +++---- membership/calendar/calendar.py | 22 ++-- membership/forms.py | 7 +- membership/models.py | 13 ++- membership/payment.py | 8 +- membership/tests.py | 4 +- membership/urls.py | 4 +- membership/views.py | 38 ++++--- nosystemd/tests.py | 2 +- opennebula_api/admin.py | 2 +- opennebula_api/exceptions.py | 3 +- opennebula_api/models.py | 106 +++++++----------- opennebula_api/serializers.py | 63 ++++++----- opennebula_api/tests.py | 35 +++--- opennebula_api/views.py | 24 ++-- requirements.txt | 3 +- setup.cfg | 3 + ungleich/admin.py | 1 + ungleich/cms_toolbar.py | 3 +- ungleich/models.py | 7 +- ungleich/templates/cms/ungleichch/__init__.py | 2 +- ungleich/tests.py | 2 +- ungleich/views.py | 1 + ungleich_page/admin.py | 2 +- ungleich_page/models.py | 2 +- ungleich_page/tests.py | 2 +- ungleich_page/views.py | 5 +- utils/admin.py | 2 +- utils/fields.py | 3 +- utils/forms.py | 4 +- utils/mailer.py | 1 - utils/models.py | 3 +- utils/stripe_utils.py | 14 +-- 65 files changed, 340 insertions(+), 387 deletions(-) create mode 100755 setup.cfg diff --git a/.travis.yml b/.travis.yml index 1e92e42e..a1d0aacc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,8 +4,10 @@ python: - "3.6" env: - # Set a dummy secret key + # Set a dummy secret key - DJANGO_SECRET_KEY=0 # install dependencies install: "pip install -r requirements.txt" -script: python manage.py test +script: +- flake8 +- python manage.py test diff --git a/alplora/admin.py b/alplora/admin.py index 8c38f3f3..4185d360 100644 --- a/alplora/admin.py +++ b/alplora/admin.py @@ -1,3 +1,3 @@ -from django.contrib import admin +# from django.contrib import admin # Register your models here. diff --git a/alplora/models.py b/alplora/models.py index 71a83623..0b4331b3 100644 --- a/alplora/models.py +++ b/alplora/models.py @@ -1,3 +1,3 @@ -from django.db import models +# from django.db import models # Create your models here. diff --git a/alplora/tests.py b/alplora/tests.py index 7ce503c2..a79ca8be 100644 --- a/alplora/tests.py +++ b/alplora/tests.py @@ -1,3 +1,3 @@ -from django.test import TestCase +# from django.test import TestCase # Create your tests here. diff --git a/alplora/urls.py b/alplora/urls.py index f792f13f..071bb2ac 100644 --- a/alplora/urls.py +++ b/alplora/urls.py @@ -7,6 +7,6 @@ urlpatterns = [ url(r'^/?$', IndexView.as_view(), name='index'), url(r'/login/', LoginView.as_view(), name='login'), url(r'/contact', ContactView.as_view(), name='contact'), -# url(r'^/beta-program/?$', BetaProgramView.as_view(), name='beta'), -# url(r'^/landing/?$', LandingProgramView.as_view(), name='landing'), + # url(r'^/beta-program/?$', BetaProgramView.as_view(), name='beta'), + # url(r'^/landing/?$', LandingProgramView.as_view(), name='landing'), ] diff --git a/alplora/views.py b/alplora/views.py index ba249887..0a10b4e0 100644 --- a/alplora/views.py +++ b/alplora/views.py @@ -4,11 +4,11 @@ from django.utils.translation import get_language, get_language_info from django.utils.translation import ugettext_lazy as _ from django.views.generic.edit import FormView from django.contrib import messages -from django.core.urlresolvers import reverse_lazy, reverse from django.shortcuts import render from utils.forms import ContactUsForm + class IndexView(TemplateView): template_name = "alplora/index.html" @@ -18,6 +18,7 @@ class IndexView(TemplateView): context.update(languages) return context + class ContactView(FormView): template_name = 'alplora/contact.html' form_class = ContactUsForm @@ -33,7 +34,8 @@ class ContactView(FormView): form.save() form.send_email(email_to='info@alplora.ch') messages.add_message(self.request, messages.SUCCESS, self.success_message) - return render(self.request, 'alplora/contact_success.html', {}) + return render(self.request, 'alplora/contact_success.html', {}) + class LoginView(TemplateView): template_name = "alplora/login.html" diff --git a/datacenterlight/forms.py b/datacenterlight/forms.py index 90340e8d..33d95c29 100644 --- a/datacenterlight/forms.py +++ b/datacenterlight/forms.py @@ -1,6 +1,6 @@ from django import forms -from .models import BetaAccess, BetaAccessVM +from .models import BetaAccess class BetaAccessForm(forms.ModelForm): diff --git a/datacenterlight/templatetags/custom_tags.py b/datacenterlight/templatetags/custom_tags.py index 915e68fe..edbda197 100644 --- a/datacenterlight/templatetags/custom_tags.py +++ b/datacenterlight/templatetags/custom_tags.py @@ -5,20 +5,18 @@ from django.utils.translation import activate, get_language register = template.Library() - @register.simple_tag(takes_context=True) def change_lang(context, lang=None, *args, **kwargs): path = context['request'].path - url_parts = resolve( path ) + url_parts = resolve(path) url = path cur_language = get_language() try: activate(lang) - url = reverse( url_parts.view_name, kwargs=url_parts.kwargs ) + url = reverse(url_parts.view_name, kwargs=url_parts.kwargs) finally: activate(cur_language) - - return "%s" % url \ No newline at end of file + return "%s" % url diff --git a/datacenterlight/tests.py b/datacenterlight/tests.py index 7ce503c2..a79ca8be 100644 --- a/datacenterlight/tests.py +++ b/datacenterlight/tests.py @@ -1,3 +1,3 @@ -from django.test import TestCase +# from django.test import TestCase # Create your tests here. diff --git a/datacenterlight/views.py b/datacenterlight/views.py index 427f8c70..75b05d72 100644 --- a/datacenterlight/views.py +++ b/datacenterlight/views.py @@ -3,7 +3,7 @@ from django.http import HttpResponseRedirect from .forms import BetaAccessForm from .models import BetaAccess, BetaAccessVMType, BetaAccessVM from django.contrib import messages -from django.core.urlresolvers import reverse_lazy, reverse +from django.core.urlresolvers import reverse from django.core.mail import EmailMessage from utils.mailer import BaseEmail from django.shortcuts import render @@ -14,12 +14,15 @@ from django.core.exceptions import ValidationError from opennebula_api.models import OpenNebulaManager from opennebula_api.serializers import VirtualMachineTemplateSerializer + class LandingProgramView(TemplateView): template_name = "datacenterlight/landing.html" + class SuccessView(TemplateView): template_name = "datacenterlight/success.html" + class PricingView(TemplateView): template_name = "datacenterlight/pricing.html" @@ -32,17 +35,16 @@ class PricingView(TemplateView): 'templates': VirtualMachineTemplateSerializer(templates, many=True).data, } except: - messages.error( request, - 'We have a temporary problem to connect to our backend. \ - Please try again in a few minutes' - ) + messages.error(request, + 'We have a temporary problem to connect to our backend. \ + Please try again in a few minutes' + ) context = { - 'error' : 'connection' + 'error': 'connection' } return render(request, self.template_name, context) - def post(self, request): cores = request.POST.get('cpu') @@ -61,7 +63,7 @@ class PricingView(TemplateView): request.session['next'] = reverse('hosting:payment') request.session['specs'] = { - 'cpu':cores, + 'cpu': cores, 'memory': memory, 'disk_size': storage, 'price': price, @@ -111,6 +113,7 @@ class BetaAccessView(FormView): messages.add_message(self.request, messages.SUCCESS, self.success_message) return render(self.request, 'datacenterlight/beta_success.html', {}) + class BetaProgramView(CreateView): template_name = "datacenterlight/beta.html" model = BetaAccessVM @@ -169,7 +172,7 @@ class IndexView(CreateView): form_class = BetaAccessForm success_url = "/datacenterlight#requestform" success_message = "Thank you, we will contact you as soon as possible" - + def get(self, request, *args, **kwargs): try: manager = OpenNebulaManager() @@ -178,12 +181,12 @@ class IndexView(CreateView): 'templates': VirtualMachineTemplateSerializer(templates, many=True).data, } except: - messages.error( request, - 'We have a temporary problem to connect to our backend. \ - Please try again in a few minutes' - ) + messages.error(request, + 'We have a temporary problem to connect to our backend. \ + Please try again in a few minutes' + ) context = { - 'error' : 'connection' + 'error': 'connection' } return render(request, self.template_name, context) @@ -196,7 +199,7 @@ class IndexView(CreateView): manager = OpenNebulaManager() template = manager.get_template(template_id) template_data = VirtualMachineTemplateSerializer(template).data - + name = request.POST.get('name') email = request.POST.get('email') name_field = forms.CharField() @@ -207,7 +210,7 @@ class IndexView(CreateView): messages.add_message(self.request, messages.ERROR, '%(value) is not a proper name.'.format(name)) return HttpResponseRedirect(reverse('datacenterlight:index')) - try: + try: email = email_field.clean(email) except ValidationError as err: messages.add_message(self.request, messages.ERROR, '%(value) is not a proper email.'.format(email)) @@ -230,7 +233,7 @@ class IndexView(CreateView): 'reply_to': [context['email']], } email = EmailMessage(**email_data) - email.send() + email.send() return HttpResponseRedirect(reverse('datacenterlight:order_success')) diff --git a/digitalglarus/admin.py b/digitalglarus/admin.py index 4f8bdcfa..c887e8d2 100644 --- a/digitalglarus/admin.py +++ b/digitalglarus/admin.py @@ -1,5 +1,5 @@ from django.contrib import admin -from .models import Supporter, DGGallery, DGPicture, Booking, BookingPrice,\ +from .models import DGGallery, DGPicture, Booking, BookingPrice,\ MembershipOrder, Membership, MembershipType, BookingOrder, BookingCancellation from django.core.urlresolvers import reverse diff --git a/digitalglarus/cms_plugins.py b/digitalglarus/cms_plugins.py index e58dffb9..7c61bea6 100644 --- a/digitalglarus/cms_plugins.py +++ b/digitalglarus/cms_plugins.py @@ -1,9 +1,9 @@ from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool -from cms.wizards import wizard_base from .models import DGGalleryPlugin, DGSupportersPlugin, Supporter from django.utils.translation import ugettext as _ -# + + class CMSGalleryPlugin(CMSPluginBase): model = DGGalleryPlugin name = _("Digital Glarus Gallery") @@ -11,12 +11,13 @@ class CMSGalleryPlugin(CMSPluginBase): def render(self, context, instance, placeholder): context.update({ - 'gallery':instance.dgGallery, - 'object':instance, - 'placeholder':placeholder + 'gallery': instance.dgGallery, + 'object': instance, + 'placeholder': placeholder }) return context + class CMSSupportersPlugin(CMSPluginBase): name = _("Digital Glarus Supporters") model = DGSupportersPlugin @@ -26,11 +27,10 @@ class CMSSupportersPlugin(CMSPluginBase): context.update({ 'supporters': Supporter.objects.all().order_by('name'), 'object': instance, - 'placeholder':placeholder + 'placeholder': placeholder }) return context -# -# -# + + plugin_pool.register_plugin(CMSGalleryPlugin) plugin_pool.register_plugin(CMSSupportersPlugin) diff --git a/digitalglarus/forms.py b/digitalglarus/forms.py index 90a1024e..a0e685f8 100644 --- a/digitalglarus/forms.py +++ b/digitalglarus/forms.py @@ -1,7 +1,6 @@ from django import forms from django.db.models import Q from django.utils.translation import ugettext_lazy as _ -from datetime import datetime from utils.models import BillingAddress @@ -92,7 +91,7 @@ class CancelBookingForm(forms.ModelForm): class BookingDateForm(forms.Form): start_date = forms.DateField(required=False, widget=forms.TextInput(attrs={'id': 'booking-date-1', - 'value': 'Select your date'})) + 'value': 'Select your date'})) end_date = forms.DateField(required=False, widget=forms.TextInput(attrs={'id': 'booking-date-2'})) diff --git a/digitalglarus/management/commands/list.py b/digitalglarus/management/commands/list.py index e2d6b1b3..653966e8 100644 --- a/digitalglarus/management/commands/list.py +++ b/digitalglarus/management/commands/list.py @@ -3,6 +3,7 @@ from django.conf import settings import stripe stripe.api_key = settings.STRIPE_API_PRIVATE_KEY + class Command(BaseCommand): help = "Record payment plans for Digital Glarus on stripe" @@ -10,5 +11,3 @@ class Command(BaseCommand): print("Available plans:") for plan in stripe.Plan.all(): print(plan) - - diff --git a/digitalglarus/management/commands/plans.py b/digitalglarus/management/commands/plans.py index 2104cc1d..9e6dbc01 100644 --- a/digitalglarus/management/commands/plans.py +++ b/digitalglarus/management/commands/plans.py @@ -11,11 +11,11 @@ PAYMENT_PLANS = [ 'id': "spontaneus" }), ('committed', { - 'amount':36000, - 'interval':'year', - 'name':'The Committed', - 'currency':'chf', - 'id':'committed' + 'amount': 36000, + 'interval': 'year', + 'name': 'The Committed', + 'currency': 'chf', + 'id': 'committed' }) ] @@ -26,8 +26,6 @@ class Command(BaseCommand): def handle(self, *args, **options): for payment_plan, data in PAYMENT_PLANS: try: - res = stripe.Plan.create(**data) + stripe.Plan.create(**data) except stripe.InvalidRequestError as e: print(e) - - diff --git a/digitalglarus/models.py b/digitalglarus/models.py index 2e12e265..16d6b639 100644 --- a/digitalglarus/models.py +++ b/digitalglarus/models.py @@ -105,7 +105,7 @@ class Membership(models.Model): has_order_current_month = Q(membershiporder__customer__user=user, membershiporder__created_at__month=datetime.today().month) # has_order_past_month = Q(membershiporder__customer__user=user, - # membershiporder__created_at__month=past_month) + # membershiporder__created_at__month=past_month) active_membership = Q(active=True) # return cls.objects.filter(has_order_past_month | has_order_current_month).\ return cls.objects.filter(has_order_current_month).\ @@ -316,17 +316,20 @@ class DGGallery(models.Model): class Meta: verbose_name_plural = 'dgGallery' -# + + class DGPicture(models.Model): gallery = models.ForeignKey(DGGallery) - image = FilerImageField(related_name='dg_gallery') + image = FilerImageField(related_name='dg_gallery') description = models.CharField(max_length=60) def __str__(self): return "%s" % (self.image.name) + class DGGalleryPlugin(CMSPlugin): dgGallery = models.ForeignKey(DGGallery) + class DGSupportersPlugin(CMSPlugin): pass diff --git a/digitalglarus/test_views.py b/digitalglarus/test_views.py index 63b2cc06..f3e427ba 100644 --- a/digitalglarus/test_views.py +++ b/digitalglarus/test_views.py @@ -1,4 +1,3 @@ -import json from model_mommy import mommy from unittest import mock @@ -150,7 +149,7 @@ class MembershipPaymentViewTest(BaseTestCase): # self.assertTrue(HostingOrder.objects.filter(customer=stripe_customer).exists()) # hosting_order = HostingOrder.objects.filter(customer=stripe_customer)[0] # vm_plan = { - # 'cores': hosting_order.vm_plan.cores, + # 'cores': hosting_order.vm_plan.cores, # 'memory': hosting_order.vm_plan.memory, # 'disk_size': hosting_order.vm_plan.disk_size, # 'price': hosting_order.vm_plan.price, diff --git a/digitalglarus/views.py b/digitalglarus/views.py index a33775c9..87c1ccd2 100644 --- a/digitalglarus/views.py +++ b/digitalglarus/views.py @@ -720,7 +720,9 @@ class ContactView(FormView): messages.add_message(self.request, messages.SUCCESS, self.success_message) return super(ContactView, self).form_valid(form) -############## OLD VIEWS + +# OLD VIEWS + def blog(request): tags = ["digitalglarus"] @@ -751,6 +753,3 @@ def supporters(request): 'supporters': Supporter.objects.order_by('name') } return render(request, 'supporters.html', context) - - - diff --git a/dynamicweb/settings-test/__init__.py b/dynamicweb/settings-test/__init__.py index 22ef8531..1a8babdd 100644 --- a/dynamicweb/settings-test/__init__.py +++ b/dynamicweb/settings-test/__init__.py @@ -9,12 +9,15 @@ from django.utils.translation import ugettext_lazy as _ # dotenv import dotenv -gettext = lambda s: s + +def gettext(s): + return s def env(env_name): return os.environ.get(env_name) + BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_DIR = os.path.abspath( @@ -83,7 +86,7 @@ INSTALLED_APPS = ( 'django_select2', 'meta', 'meta_mixin', -# 'admin_enhancer', + # 'admin_enhancer', 'djangocms_blog', 'bootstrap3', 'compressor', @@ -433,5 +436,5 @@ MANAGERS = ADMINS ALLOWED_HOSTS = [ ".ungleich.ch", - "digital.glarus.ungleich.ch" , + "digital.glarus.ungleich.ch", ] diff --git a/dynamicweb/settings/__init__.py b/dynamicweb/settings/__init__.py index 9b5ed21c..3a9877ad 100644 --- a/dynamicweb/settings/__init__.py +++ b/dynamicweb/settings/__init__.py @@ -1 +1 @@ -from .base import * +# from .base import * diff --git a/dynamicweb/settings/base.py b/dynamicweb/settings/base.py index ec240691..33910930 100644 --- a/dynamicweb/settings/base.py +++ b/dynamicweb/settings/base.py @@ -11,7 +11,9 @@ from django.utils.translation import ugettext_lazy as _ # dotenv import dotenv -gettext = lambda s: s + +def gettext(s): + return s def env(env_name): @@ -186,7 +188,11 @@ CMS_TEMPLATES = ( DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', - 'NAME': 'app' + 'NAME': 'app', + 'HOST': 'localhost', + 'USER': 'ubuntu', + 'PASSWORD': 'Qwerty123', + } } @@ -462,17 +468,20 @@ STRIPE_DESCRIPTION_ON_PAYMENT = "Payment for ungleich GmbH services" # EMAIL MESSAGES REGISTRATION_MESSAGE = {'subject': "Validation mail", - 'message': 'Thank You for registering for account on Digital Glarus.\nPlease verify Your account under following link http://{host}/en-us/digitalglarus/login/validate/{slug}', + 'message': 'Thank You for registering for account on Digital Glarus.\n' + 'Please verify Your account under following link ' + 'http://{host}/en-us/digitalglarus/login/validate/{slug}', } STRIPE_API_PRIVATE_KEY = env('STRIPE_API_PRIVATE_KEY') STRIPE_API_PUBLIC_KEY = env('STRIPE_API_PUBLIC_KEY') DEBUG = True -if DEBUG: - from .local import * -else: - from .prod import * +# not used +# if DEBUG: +# from .local import * +# # else: +# # from .prod import * ANONYMOUS_USER_NAME = 'anonymous@ungleich.ch' diff --git a/dynamicweb/settings/local.py b/dynamicweb/settings/local.py index 799df594..1b03f3fe 100644 --- a/dynamicweb/settings/local.py +++ b/dynamicweb/settings/local.py @@ -1,5 +1,7 @@ -from .base import * -REGISTRATION_MESSAGE['message'] = REGISTRATION_MESSAGE['message'].format(host='dynamicweb-development.ungleich.ch',slug='{slug}') +from .base import * # flake8: noqa + +REGISTRATION_MESSAGE['message'] = REGISTRATION_MESSAGE['message'].format(host='dynamicweb-development.ungleich.ch', + slug='{slug}') ALLOWED_HOSTS = [ "*" ] @@ -13,9 +15,9 @@ CACHES = { } } -MIDDLEWARE_CLASSES+=("debug_toolbar.middleware.DebugToolbarMiddleware",) +MIDDLEWARE_CLASSES += ("debug_toolbar.middleware.DebugToolbarMiddleware",) -INSTALLED_APPS+=( +INSTALLED_APPS += ( 'django_extensions', 'debug_toolbar' ) diff --git a/dynamicweb/settings/prod.py b/dynamicweb/settings/prod.py index 4f96593f..e449e3cb 100644 --- a/dynamicweb/settings/prod.py +++ b/dynamicweb/settings/prod.py @@ -1,15 +1,16 @@ -from .base import * +from .base import * # flake8: noqa # List of people that get admin messages -ADMINS = ( (x, x + "@ungleich.ch") for x in ["web-team"] ) +ADMINS = ((x, x + "@ungleich.ch") for x in ["web-team"]) -DEBUG=False +DEBUG = False EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' -#MANAGERS = ADMINS +# MANAGERS = ADMINS -REGISTRATION_MESSAGE['message'] = REGISTRATION_MESSAGE['message'].format(host='digitalglarus.ungleich.ch',slug='{slug}') +REGISTRATION_MESSAGE['message'] = REGISTRATION_MESSAGE['message'].format(host='digitalglarus.ungleich.ch', + slug='{slug}') # flake8: noqa ALLOWED_HOSTS = [ ".ungleich.ch", diff --git a/dynamicweb/urls.py b/dynamicweb/urls.py index 0b1a0844..5ae11689 100644 --- a/dynamicweb/urls.py +++ b/dynamicweb/urls.py @@ -12,30 +12,31 @@ from django.views.generic import RedirectView from django.core.urlresolvers import reverse_lazy import debug_toolbar -urlpatterns = [ url(r'^index.html$', LandingView.as_view()), - url(r'^hosting/', include('hosting.urls', namespace="hosting")), - url(r'^open_api/', include('opennebula_api.urls', - namespace='opennebula_api')), - url(r'^railshosting/', RailsHostingView.as_view(), name="rails.hosting"), - url(r'^nodehosting/', NodeJSHostingView.as_view(), name="node.hosting"), - url(r'^djangohosting/', DjangoHostingView.as_view(), name="django.hosting"), - url(r'^nosystemd/', include('nosystemd.urls', namespace="nosystemd")), - url(r'^taggit_autosuggest/', include('taggit_autosuggest.urls')), - url(r'^jsi18n/(?P\S+?)/$', - 'django.views.i18n.javascript_catalog'), - ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) +urlpatterns = [url(r'^index.html$', LandingView.as_view()), + url(r'^hosting/', include('hosting.urls', namespace="hosting")), + url(r'^open_api/', include('opennebula_api.urls', + namespace='opennebula_api')), + url(r'^railshosting/', RailsHostingView.as_view(), name="rails.hosting"), + url(r'^nodehosting/', NodeJSHostingView.as_view(), name="node.hosting"), + url(r'^djangohosting/', DjangoHostingView.as_view(), name="django.hosting"), + url(r'^nosystemd/', include('nosystemd.urls', namespace="nosystemd")), + url(r'^taggit_autosuggest/', include('taggit_autosuggest.urls')), + url(r'^jsi18n/(?P\S+?)/$', + 'django.views.i18n.javascript_catalog'), + ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # note the django CMS URLs included via i18n_patterns urlpatterns += i18n_patterns('', url(r'^/?$', LandingView.as_view()), url(r'^admin/', include(admin.site.urls)), url(r'^datacenterlight', include('datacenterlight.urls', namespace="datacenterlight")), - url(r'^hosting/', RedirectView.as_view(url=reverse_lazy('hosting:login')), name='redirect_hosting_login'), + url(r'^hosting/', RedirectView.as_view( + url=reverse_lazy('hosting:login')), name='redirect_hosting_login'), url(r'^alplora', include('alplora.urls', namespace="alplora")), url(r'^membership/', include(membership_urls)), url(r'^digitalglarus/', include('digitalglarus.urls', namespace="digitalglarus")), - #url(r'^blog/', include('ungleich.urls', namespace='ungleich')), + # url(r'^blog/', include('ungleich.urls', namespace='ungleich')), url(r'^', include('ungleich_page.urls', namespace='ungleich_page'), name='ungleich_page'), @@ -50,4 +51,4 @@ if settings.DEBUG: 'document_root': settings.MEDIA_ROOT, }), ) - urlpatterns += patterns('',url(r'^__debug__/', include(debug_toolbar.urls))) + urlpatterns += patterns('', url(r'^__debug__/', include(debug_toolbar.urls))) diff --git a/dynamicweb/wsgi.py b/dynamicweb/wsgi.py index 69d05eb9..8b8d9981 100644 --- a/dynamicweb/wsgi.py +++ b/dynamicweb/wsgi.py @@ -7,13 +7,13 @@ For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ -import os,sys -#sys.path.append(os.path.dirname(__file__)) +import os +import sys +from django.core.wsgi import get_wsgi_application + +# sys.path.append(os.path.dirname(__file__)) sys.path.append('/home/app/pyvenv/lib/python3.4/site-packages/') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dynamicweb.settings.prod") -from django.core.wsgi import get_wsgi_application - - application = get_wsgi_application() diff --git a/hosting/admin.py b/hosting/admin.py index c38fa8d0..6ebe461d 100644 --- a/hosting/admin.py +++ b/hosting/admin.py @@ -1,8 +1,4 @@ from django.contrib import admin -from django.utils.html import format_html -from django.core.urlresolvers import reverse - -from utils.mailer import BaseEmail from .models import HostingOrder, HostingBill, HostingPlan diff --git a/hosting/forms.py b/hosting/forms.py index d9a3b985..505ecbce 100644 --- a/hosting/forms.py +++ b/hosting/forms.py @@ -1,14 +1,11 @@ -import random -import string from django import forms from membership.models import CustomUser from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ -from utils.stripe_utils import StripeUtils +from .models import UserHostingKey -from .models import HostingOrder, UserHostingKey class HostingUserLoginForm(forms.Form): @@ -62,9 +59,9 @@ class HostingUserSignupForm(forms.ModelForm): class UserHostingKeyForm(forms.ModelForm): private_key = forms.CharField(widget=forms.HiddenInput(), required=False) public_key = forms.CharField(widget=forms.Textarea(), required=False, - help_text=_('Paste here your public key')) + help_text=_('Paste here your public key')) user = forms.models.ModelChoiceField(queryset=CustomUser.objects.all(), - required=False, widget=forms.HiddenInput()) + required=False, widget=forms.HiddenInput()) name = forms.CharField(required=True) def __init__(self, *args, **kwargs): diff --git a/hosting/management/commands/create_vm_types.py b/hosting/management/commands/create_vm_types.py index f92cc3a1..0b5f8df5 100644 --- a/hosting/management/commands/create_vm_types.py +++ b/hosting/management/commands/create_vm_types.py @@ -1,4 +1,4 @@ -from django.core.management.base import BaseCommand, CommandError +from django.core.management.base import BaseCommand from hosting.models import VirtualMachineType @@ -55,15 +55,15 @@ class Command(BaseCommand): }, ] - - hetzner = { - 'base_price': 10, - 'core_price': 5, - 'memory_price': 2, - 'disk_size_price': 0.6, - 'description': 'VM auf einzelner HW, Raid1, kein HA', - 'location': 'DE' - } + # not used + # hetzner = { + # 'base_price': 10, + # 'core_price': 5, + # 'memory_price': 2, + # 'disk_size_price': 0.6, + # 'description': 'VM auf einzelner HW, Raid1, kein HA', + # 'location': 'DE' + # } # return { # # 'hetzner_nug': { diff --git a/hosting/models.py b/hosting/models.py index 25f852f1..bb53589d 100644 --- a/hosting/models.py +++ b/hosting/models.py @@ -1,22 +1,16 @@ import os -import socket import logging -import oca from django.db import models -from django.utils.translation import ugettext_lazy as _ from django.utils.functional import cached_property -from django.conf import settings from Crypto.PublicKey import RSA -from stored_messages.settings import stored_messages_settings from membership.models import StripeCustomer, CustomUser from utils.models import BillingAddress from utils.mixins import AssignPermissionsMixin -from .managers import VMPlansManager logger = logging.getLogger(__name__) @@ -29,7 +23,7 @@ class HostingPlan(models.Model): def serialize(self): return { 'id': self.id, - 'cpu':self.cpu_cores, + 'cpu': self.cpu_cores, 'memory': self.memory, 'disk_size': self.disk_size, 'price': self.price(), @@ -46,6 +40,7 @@ class HostingPlan(models.Model): price += self.memory * 2 return price + class HostingOrder(AssignPermissionsMixin, models.Model): ORDER_APPROVED_STATUS = 'Approved' @@ -128,6 +123,7 @@ class UserHostingKey(models.Model): # self.save(update_fields=['public_key']) return private_key, public_key + class HostingBill(AssignPermissionsMixin, models.Model): customer = models.ForeignKey(StripeCustomer) billing_address = models.ForeignKey(BillingAddress) @@ -147,4 +143,3 @@ class HostingBill(AssignPermissionsMixin, models.Model): def create(cls, customer=None, billing_address=None): instance = cls.objects.create(customer=customer, billing_address=billing_address) return instance - diff --git a/hosting/templates/hosting/payment.html b/hosting/templates/hosting/payment.html index e41f57d7..91d209fb 100644 --- a/hosting/templates/hosting/payment.html +++ b/hosting/templates/hosting/payment.html @@ -1,6 +1,6 @@ {% extends "hosting/base_short.html" %} {% load staticfiles bootstrap3 i18n %} -{% block content %} +{% block content %}
@@ -29,7 +29,7 @@
- +

{%trans "Billing Address"%}

@@ -56,7 +56,7 @@
Last 4: *****{{credit_card_data.last4}}
Type: {{credit_card_data.cc_brand}}
- +
-
+
@@ -128,7 +128,7 @@
{% endif %} - + {% endif %} @@ -143,7 +143,7 @@ {% if stripe_key %} {% get_current_language as LANGUAGE_CODE %} - diff --git a/hosting/test_views.py b/hosting/test_views.py index c3777840..aa9a9ace 100644 --- a/hosting/test_views.py +++ b/hosting/test_views.py @@ -4,7 +4,7 @@ from django.test import TestCase from django.core.urlresolvers import reverse from django.core.urlresolvers import resolve from django.contrib.auth.tokens import default_token_generator -from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode +from django.utils.http import urlsafe_base64_encode from django.utils.encoding import force_bytes diff --git a/hosting/tests.py b/hosting/tests.py index d9b5da5b..70e47dd2 100644 --- a/hosting/tests.py +++ b/hosting/tests.py @@ -1,7 +1,7 @@ -from django.test import TestCase +# from django.test import TestCase # Create your tests here. -test_user_can_add_ssh_key() - -test_user_can_delete_ssh_ke() +# test_user_can_add_ssh_key() +# +# test_user_can_delete_ssh_ke() diff --git a/hosting/views.py b/hosting/views.py index 45e23df4..4cd552e0 100644 --- a/hosting/views.py +++ b/hosting/views.py @@ -1,5 +1,3 @@ -from collections import namedtuple - from django.shortcuts import render from django.http import Http404 from django.core.urlresolvers import reverse_lazy, reverse @@ -7,7 +5,6 @@ from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import View, CreateView, FormView, ListView, DetailView,\ DeleteView, TemplateView, UpdateView from django.http import HttpResponseRedirect -from django.contrib.auth import authenticate, login from django.contrib import messages from django.conf import settings from django.shortcuts import redirect @@ -35,7 +32,6 @@ from opennebula_api.serializers import VirtualMachineSerializer,\ from django.utils.translation import ugettext_lazy as _ -from oca.exceptions import OpenNebulaException from oca.pool import WrongNameError, WrongIdError CONNECTION_ERROR = "Your VMs cannot be displayed at the moment due to a backend \ @@ -205,31 +201,35 @@ class SignupView(CreateView): return HttpResponseRedirect(reverse_lazy('hosting:signup-validate')) + class SignupValidateView(TemplateView): template_name = "hosting/signup_validate.html" - + def get_context_data(self, **kwargs): context = super(SignupValidateView, self).get_context_data(**kwargs) login_url = reverse('hosting:login') - message= _("Thank you for signing up. We have sent an email to you. Please follow the instructions in it to activate your account. Once activated, you can login using ") + 'login' - section_title='Sign up' + message = _("Thank you for signing up. We have sent an email to you. " + "Please follow the instructions in it to activate your account. " + "Once activated, you can login using ") + 'login' + section_title = 'Sign up' context['message'] = mark_safe(message) context['section_title'] = section_title return context + class SignupValidatedView(SignupValidateView): template_name = "hosting/signup_validate.html" - + def get_context_data(self, **kwargs): context = super(SignupValidateView, self).get_context_data(**kwargs) validated = CustomUser.validate_url(self.kwargs['validate_slug']) login_url = reverse('hosting:login') if validated: - message= _("Your account has been activated. You can now ") + 'login' - section_title=_('Account activation') + message = _("Your account has been activated. You can now ") + 'login' + section_title = _('Account activation') else: - message= _("Sorry. Your request is invalid.") + 'login' - section_title=_('Account activation') + message = _("Sorry. Your request is invalid.") + 'login' + section_title = _('Account activation') context['message'] = mark_safe(message) context['section_title'] = section_title return context @@ -338,6 +338,7 @@ class SSHKeyDeleteView(LoginRequiredMixin, DeleteView): return super(SSHKeyDeleteView, self).delete(request, *args, **kwargs) + class SSHKeyListView(LoginRequiredMixin, ListView): template_name = "hosting/user_keys.html" login_url = reverse_lazy('hosting:login') @@ -346,7 +347,6 @@ class SSHKeyListView(LoginRequiredMixin, ListView): paginate_by = 10 ordering = '-id' - def get_queryset(self): user = self.request.user self.queryset = UserHostingKey.objects.filter(user=user) @@ -366,7 +366,6 @@ class SSHKeyCreateView(LoginRequiredMixin, FormView): context_object_name = "virtual_machine" success_url = reverse_lazy('hosting:ssh_keys') - def get_form_kwargs(self): kwargs = super(SSHKeyCreateView, self).get_form_kwargs() kwargs.update({'request': self.request}) @@ -463,7 +462,7 @@ class PaymentVMView(LoginRequiredMixin, FormView): return context def get(self, request, *args, **kwargs): - if not UserHostingKey.objects.filter( user=self.request.user).exists(): + if not UserHostingKey.objects.filter(user=self.request.user).exists(): messages.success( request, 'In order to create a VM, you create/upload your SSH KEY first.' @@ -525,7 +524,7 @@ class PaymentVMView(LoginRequiredMixin, FormView): manager = OpenNebulaManager(email=owner.email, password=owner.password) # Get user ssh key - if not UserHostingKey.objects.filter( user=self.request.user).exists(): + if not UserHostingKey.objects.filter(user=self.request.user).exists(): context.update({ 'sshError': 'error', 'form': form @@ -534,7 +533,7 @@ class PaymentVMView(LoginRequiredMixin, FormView): # For now just get first one user_key = UserHostingKey.objects.filter( user=self.request.user).first() - + # Create a vm using logged user vm_id = manager.create_vm( template_id=vm_template_id, @@ -552,8 +551,9 @@ class PaymentVMView(LoginRequiredMixin, FormView): ) # Create a Hosting Bill - bill = HostingBill.create( - customer=customer, billing_address=billing_address) + # variable bill is not used + # bill = HostingBill.create( + # customer=customer, billing_address=billing_address) # Create Billing Address for User if he does not have one if not customer.user.billing_addresses.count(): @@ -686,7 +686,7 @@ class CreateVirtualMachinesView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): - if not UserHostingKey.objects.filter( user=self.request.user).exists(): + if not UserHostingKey.objects.filter(user=self.request.user).exists(): messages.success( request, 'In order to create a VM, you need to create/upload your SSH KEY first.' @@ -710,7 +710,7 @@ class CreateVirtualMachinesView(LoginRequiredMixin, View): ) context = { 'error': 'connection' - } + } return render(request, self.template_name, context) diff --git a/membership/calendar/calendar.py b/membership/calendar/calendar.py index 94416d55..ae4428f1 100644 --- a/membership/calendar/calendar.py +++ b/membership/calendar/calendar.py @@ -38,26 +38,26 @@ class CustomHTMLCalendar(CustomCalendar): self.requested_month = requested_month super(CustomHTMLCalendar, self).__init__() - def formatday(self, day, weekday, month=None,year=None): + def formatday(self, day, weekday, month=None, year=None): """ Return a day as a table cell. """ booked = CalendarModel.objects.filter(user_id=self.user.id) - is_booked= booked.filter(datebooked=datetime.date(day=day,month=month,year=year)) + is_booked = booked.filter(datebooked=datetime.date(day=day, month=month, year=year)) if month < int(self.requested_month): - return '%d' % ("selected" if is_booked else "",day) + return '%d' % ("selected" if is_booked else "", day) elif month > int(self.requested_month): - return '%d' % ("selected" if is_booked else "",day) + return '%d' % ("selected" if is_booked else "", day) else: - return '%d' % ("selected" if is_booked else "",day) + return '%d' % ("selected" if is_booked else "", day) - def formatweek(self, theweek,year): + def formatweek(self, theweek, year): """ Return a complete week as a table row. """ - s = ''.join(self.formatday(d, wd, month,year) for (d, wd, month) in theweek) + s = ''.join(self.formatday(d, wd, month, year) for (d, wd, month) in theweek) return '%s' % s def formatmonthname(self, theyear, themonth, withyear=True): @@ -93,7 +93,7 @@ class CustomHTMLCalendar(CustomCalendar): a(self.formatweekheader()) a('\n') for week in self.monthdays2calendar(theyear, themonth): - a(self.formatweek(week,theyear)) + a(self.formatweek(week, theyear)) a('\n') a('') a('\n') @@ -102,8 +102,8 @@ class CustomHTMLCalendar(CustomCalendar): class BookCalendar(CustomHTMLCalendar): - def __init__(self, user,requested_month): - self.user=user + def __init__(self, user, requested_month): + self.user = user super(BookCalendar, self).__init__(requested_month) def formatmonth(self, year, month): @@ -111,7 +111,7 @@ class BookCalendar(CustomHTMLCalendar): return super(BookCalendar, self).formatmonth(year, month) def day_cell(self, cssclass, body): - return '%s' % body + return '%s' % body def formatmonthname(self, theyear, themonth, withyear): """ diff --git a/membership/forms.py b/membership/forms.py index 13899d97..a70b109d 100644 --- a/membership/forms.py +++ b/membership/forms.py @@ -1,7 +1,7 @@ __author__ = 'tomislav' from django import forms from django.utils.translation import ugettext_lazy as _ -from django.contrib.auth import authenticate,login +from django.contrib.auth import authenticate from .models import CreditCards @@ -25,7 +25,7 @@ class LoginForm(forms.Form): raise forms.ValidationError("Sorry, that login was invalid. Please try again.") return self.cleaned_data - def login(self,request): + def login(self, request): username = self.cleaned_data.get('email') password = self.cleaned_data.get('password') user = authenticate(email=username, password=password) @@ -36,6 +36,7 @@ class RegisterForm(SignupFormMixin): password = forms.CharField(widget=forms.PasswordInput()) confirm_password = forms.CharField(widget=forms.PasswordInput()) + class PaymentForm(forms.ModelForm): class Meta: model = CreditCards @@ -58,7 +59,7 @@ class PaymentForm(forms.ModelForm): # if CreditCards.objects.filter(card_number=data.get("card_number")): # raise forms.ValidationError({'card_number': _('Credit card is used before.')}) - return self.cleaned_data + return data def save(self, user_id): self.instance.user_id = user_id diff --git a/membership/models.py b/membership/models.py index 8bd9feec..bcce2f39 100644 --- a/membership/models.py +++ b/membership/models.py @@ -1,10 +1,9 @@ from datetime import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ -from django.contrib.auth.models import User, AbstractBaseUser, BaseUserManager, AbstractUser, PermissionsMixin +from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.contrib.auth.hashers import make_password from django.core.validators import RegexValidator -from django.contrib.auth.models import User from django.contrib.sites.models import Site from utils.stripe_utils import StripeUtils @@ -13,11 +12,12 @@ from django.core.urlresolvers import reverse from utils.mailer import BaseEmail REGISTRATION_MESSAGE = {'subject': "Validation mail", - 'message': 'Please validate Your account under this link http://localhost:8000/en-us/digitalglarus/login/validate/{}', + 'message': 'Please validate Your account under this link ' + 'http://localhost:8000/en-us/digitalglarus/login/validate/{}', 'from': 'test@test.com'} -def get_anonymous_user_instance(User): +def get_anonymous_user_instance(): return CustomUser(name='Anonymous', email='anonymous@ungleich.ch', validation_slug=make_password(None)) @@ -87,8 +87,9 @@ class CustomUser(AbstractBaseUser, PermissionsMixin): 'subject': _('Activate your Data Center Light account'), 'from_address': '(Data Center Light) Data Center Light Support ', 'to': user.email, - 'context': {'base_url' : base_url, - 'activation_link' : reverse('hosting:validate', kwargs={'validate_slug': user.validation_slug})}, + 'context': {'base_url': base_url, + 'activation_link': reverse('hosting:validate', + kwargs={'validate_slug': user.validation_slug})}, 'template_name': 'user_activation', 'template_path': 'datacenterlight/emails/' } diff --git a/membership/payment.py b/membership/payment.py index 08245d8e..a5466998 100644 --- a/membership/payment.py +++ b/membership/payment.py @@ -7,7 +7,7 @@ stripe.api_key = settings.STRIPE_API_PRIVATE_KEY class StripePayment(object): @classmethod - def make_payment(cls,user,amount,token,time): + def make_payment(cls, user, amount, token, time): try: print(amount) print(amount) @@ -19,7 +19,7 @@ class StripePayment(object): source=token, description=settings.STRIPE_DESCRIPTION_ON_PAYMENT ) - if charge['status'] =='succeeded': + if charge['status'] == 'succeeded': obj = CreditCards.objects.filter(user_id=user.id).first() obj.payment_type = time obj.save() @@ -42,7 +42,7 @@ class StripePayment(object): return "Currently its not possible to make payments." except stripe.error.StripeError as e: return "Currently its not possible to make payments." - #maybe send email + # maybe send email except Exception as e: return "Currently its not possible to make payments." - #maybe send email + # maybe send email diff --git a/membership/tests.py b/membership/tests.py index 42fd3ebe..2f2b8c04 100644 --- a/membership/tests.py +++ b/membership/tests.py @@ -26,6 +26,4 @@ class LoginTestCase(TestCase): # check fail login res4 = self.client.post(url, data={'email': 'test@gmail.com', 'password': 'falsepassword'}) - self.assertContains(res4,'Sorry, that login was invalid.',1,200) - - + self.assertContains(res4, 'Sorry, that login was invalid.', 1, 200) diff --git a/membership/urls.py b/membership/urls.py index 65be6868..e4219d8d 100644 --- a/membership/urls.py +++ b/membership/urls.py @@ -8,7 +8,7 @@ urlpatterns = ( url(r"^$", views.LoginRegistrationView.as_view(), name='login_glarus'), url(r"^validate/(?P.*)/$", views.validate_email), url(r"^membership/$", login_required(views.MembershipView.as_view()), name='membership'), - url(r'logout/?$',views.logout_glarus,name='logout_glarus'), + url(r'logout/?$', views.logout_glarus, name='logout_glarus'), url(r"^buy/(?P