Projet

Général

Profil

0001-api-use-dedicated-django-views-for-session-less-APIs.patch

Frédéric Péters, 07 avril 2018 09:34

Télécharger (6,01 ko)

Voir les différences:

Subject: [PATCH] api: use dedicated django views for session-less APIs
 (#23023)

 wcs/api.py  | 92 +++++++++++++++++++++++++----------------------------
 wcs/urls.py |  5 +++
 2 files changed, 49 insertions(+), 48 deletions(-)
wcs/api.py
22 22
from quixote import get_request, get_publisher, get_response
23 23
from quixote.directory import Directory
24 24

  
25
from django.http import HttpResponse, HttpResponseBadRequest
26

  
25 27
from qommon import _
26 28
from qommon import misc
27 29
from qommon.evalutils import make_datetime
......
667 669

  
668 670

  
669 671
class ApiDirectory(Directory):
670
    _q_exports = ['forms', 'roles', ('reverse-geocoding', 'reverse_geocoding'),
671
            'formdefs', 'categories', 'user', 'users', 'code',
672
            ('validate-expression', 'validate_expression'),
673
            ('validate-condition', 'validate_condition')]
672
    _q_exports = ['forms', 'roles', 'formdefs', 'categories', 'user', 'users', 'code']
674 673

  
675 674
    forms = ApiFormsDirectory()
676 675
    formdefs = ApiFormdefsDirectory()
......
679 678
    users = ApiUsersDirectory()
680 679
    code = ApiTrackingCodeDirectory()
681 680

  
682
    def reverse_geocoding(self):
683
        get_response().set_content_type('application/json')
684
        try:
685
            lat = get_request().form['lat']
686
            lon = get_request().form['lon']
687
        except KeyError:
688
            raise QueryError
689
        url = get_publisher().get_reverse_geocoding_service_url()
690
        if '?' in url:
691
            url += '&'
692
        else:
693
            url += '?'
694
        url += 'format=json&addressdetails=1&lat=%s&lon=%s' % (lat, lon)
695
        url += '&accept-language=%s' % (get_publisher().get_site_language() or 'en')
696
        return misc.urlopen(url).read()
697

  
698 681
    def roles(self):
699 682
        get_response().set_content_type('application/json')
700 683
        if not (is_url_signed() or (
......
707 690
        get_response().set_content_type('application/json')
708 691
        return json.dumps({'err': 0, 'data': list_roles})
709 692

  
710
    def validate_expression(self):
711
        get_response().set_content_type('application/json')
712
        expression = get_request().form.get('expression')
713
        hint = {'klass': None, 'msg': ''}
714
        try:
715
            ComputedExpressionWidget.validate(expression)
716
        except ValidationError as e:
717
            hint['klass'] = 'error'
718
            hint['msg'] = str(e)
719
        else:
720
            if expression and re.match(r'^=.*\[[a-zA-Z_]\w*\]', expression):
721
                hint['klass'] = 'warning'
722
                hint['msg'] = _('Make sure you want a Python expression, not a simple template string.')
723
        return json.dumps(hint)
724

  
725
    def validate_condition(self):
726
        get_response().set_content_type('application/json')
727
        condition = {}
728
        condition['type'] = get_request().form.get('type') or ''
729
        condition['value'] = get_request().form.get('value_' + condition['type'])
730
        hint = {'klass': None, 'msg': ''}
731
        try:
732
            Condition(condition).validate()
733
        except ValidationError as e:
734
            hint['klass'] = 'error'
735
            hint['msg'] = str(e)
736
        return json.dumps(hint)
737

  
738 693
    def _q_traverse(self, path):
739 694
        get_request().is_json_marker = True
740 695
        return super(ApiDirectory, self)._q_traverse(path)
696

  
697

  
698
def reverse_geocoding(request, *args, **kwargs):
699
    if not ('lat' in request.GET and 'lon' in request.GET):
700
        return HttpResponseBadRequest()
701
    lat = request.GET['lat']
702
    lon = request.GET['lon']
703
    url = get_publisher().get_reverse_geocoding_service_url()
704
    if '?' in url:
705
        url += '&'
706
    else:
707
        url += '?'
708
    url += 'format=json&addressdetails=1&lat=%s&lon=%s' % (lat, lon)
709
    url += '&accept-language=%s' % (get_publisher().get_site_language() or 'en')
710
    return HttpResponse(misc.urlopen(url).read(), content_type='application/json')
711

  
712
def validate_expression(request, *args, **kwargs):
713
    expression = request.GET.get('expression')
714
    hint = {'klass': None, 'msg': ''}
715
    try:
716
        ComputedExpressionWidget.validate(expression)
717
    except ValidationError as e:
718
        hint['klass'] = 'error'
719
        hint['msg'] = str(e)
720
    else:
721
        if expression and re.match(r'^=.*\[[a-zA-Z_]\w*\]', expression):
722
            hint['klass'] = 'warning'
723
            hint['msg'] = _('Make sure you want a Python expression, not a simple template string.')
724
    return HttpResponse(json.dumps(hint), content_type='application/json')
725

  
726
def validate_condition(request, *args, **kwargs):
727
    condition = {}
728
    condition['type'] = request.GET.get('type') or ''
729
    condition['value'] = request.GET.get('value_' + condition['type']) or ''
730
    hint = {'klass': None, 'msg': ''}
731
    try:
732
        Condition(condition).validate()
733
    except ValidationError as e:
734
        hint['klass'] = 'error'
735
        hint['msg'] = str(e)
736
    return HttpResponse(json.dumps(hint), content_type='application/json')
wcs/urls.py
19 19

  
20 20
from . import compat
21 21
from . import views
22
from . import api
22 23

  
23 24
urlpatterns = [
24 25
    url(r'^$', views.home, name='home'),
25 26
    url(r'^backoffice/', views.backoffice),
26 27

  
28
    url(r'^api/validate-condition$', api.validate_condition, name='api-validate-condition'),
29
    url(r'^api/validate-expression$', api.validate_expression, name='api-validate-expression'),
30
    url(r'^api/reverse-geocoding$', api.reverse_geocoding, name='api-reverse-geocoding'),
31

  
27 32
    # provide django.contrib.auth view names for compatibility with
28 33
    # templates created for classic django applications.
29 34
    url(r'^login/$', compat.quixote, name='auth_login'),
30
-