yandex_metrika_views.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from django.conf.urls import url
  2. from django.contrib import messages
  3. try:
  4. from django.core.urlresolvers import reverse
  5. except ImportError: # Django 1.11
  6. from django.urls import reverse
  7. from django.http import HttpResponse
  8. from django.shortcuts import redirect
  9. from jet.dashboard.dashboard_modules.yandex_metrika import YandexMetrikaClient
  10. from jet.dashboard.models import UserDashboardModule
  11. from jet.dashboard import dashboard
  12. from django.utils.translation import ugettext_lazy as _
  13. def yandex_metrika_grant_view(request, pk):
  14. client = YandexMetrikaClient()
  15. return redirect(client.get_oauth_authorize_url(pk))
  16. def yandex_metrika_revoke_view(request, pk):
  17. try:
  18. module = UserDashboardModule.objects.get(pk=pk)
  19. module.pop_settings(('access_token', 'expires_in', 'token_type', 'counter'))
  20. return redirect(reverse('jet-dashboard:update_module', kwargs={'pk': module.pk}))
  21. except UserDashboardModule.DoesNotExist:
  22. return HttpResponse(_('Module not found'))
  23. def yandex_metrika_callback_view(request):
  24. try:
  25. state = request.GET['state']
  26. code = request.GET['code']
  27. module = UserDashboardModule.objects.get(pk=state)
  28. client = YandexMetrikaClient()
  29. result, exception = client.oath_token_request(code)
  30. if result is None:
  31. messages.error(request, _('API request failed.'))
  32. else:
  33. module.update_settings(result)
  34. return redirect(reverse('jet-dashboard:update_module', kwargs={'pk': module.pk}))
  35. except KeyError:
  36. return HttpResponse(_('Bad arguments'))
  37. except UserDashboardModule.DoesNotExist:
  38. return HttpResponse(_('Module not found'))
  39. dashboard.urls.register_urls([
  40. url(
  41. r'^yandex-metrika/grant/(?P<pk>\d+)/$',
  42. yandex_metrika_grant_view,
  43. name='yandex-metrika-grant'
  44. ),
  45. url(
  46. r'^yandex-metrika/revoke/(?P<pk>\d+)/$',
  47. yandex_metrika_revoke_view,
  48. name='yandex-metrika-revoke'
  49. ),
  50. url(
  51. r'^yandex-metrika/callback/$',
  52. yandex_metrika_callback_view,
  53. name='yandex-metrika-callback'
  54. ),
  55. ])