yandex_metrika_views.py 2.0 KB

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