transifex / transifex / resources / api.py

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
# -*- coding: utf-8 -*-
import os
import tempfile
import urllib
from itertools import ifilter
from django.db import transaction, IntegrityError, DatabaseError
from django.conf import settings
from django.forms import ValidationError
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
from django.utils import simplejson
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _

from piston.handler import BaseHandler, AnonymousBaseHandler
from piston.utils import rc, throttle, require_mime

from transifex.txcommon.decorators import one_perm_required_or_403
from transifex.txcommon.log import logger
from transifex.txcommon.exceptions import FileCheckError
from transifex.txcommon.utils import paginate
from transifex.projects.permissions import *
from transifex.languages.models import Language
from transifex.projects.models import Project
from transifex.projects.permissions.project import ProjectPermission
from transifex.projects.signals import post_submit_translation, post_resource_save

from transifex.resources.decorators import method_decorator
from transifex.resources.models import Resource, SourceEntity, \
        Translation as TranslationModel, RLStats
from transifex.resources.backends import ResourceBackend, FormatsBackend, \
        ResourceBackendError, content_from_uploaded_file, \
        filename_of_uploaded_file
from transifex.resources.formats import Mode
from transifex.resources.formats.registry import registry
from transifex.resources.formats.core import ParseError
from transifex.resources.formats.pseudo import get_pseudo_class
from transifex.teams.models import Team

from transifex.resources.handlers import invalidate_stats_cache

from transifex.api.utils import BAD_REQUEST


class BadRequestError(Exception):
    pass


class NoContentError(Exception):
    pass


class NotFoundError(Exception):
    pass


class ResourceHandler(BaseHandler):
    """
    Resource Handler for CRUD operations.
    """
    @classmethod
    def project_slug(cls, sfk):
        """
        This is a work around to include the project slug in the resource API
        details, so that it is shown as a normal field.
        """
        if sfk.project:
            return sfk.project.slug
        return None

    @classmethod
    def mimetype(cls, r):
        """
        Return the mimetype in a GET request instead of the i18n_type.
        """
        return registry.mimetypes_for(r.i18n_method)[0]

    @classmethod
    def source_language_code(cls, r):
        """
        Return just the code of the source language.
        """
        return r.source_language.code

    allowed_methods = ('GET', 'POST', 'PUT', 'DELETE')
    default_fields = (
        'slug', 'name', 'i18n_type', 'source_language_code', 'category',
    )
    details_fields = (
        'slug', 'name', 'created', 'available_languages', 'i18n_type',
        'source_language_code', 'project_slug', 'wordcount', 'total_entities',
        'accept_translations', 'last_update', 'category',
    )
    fields = default_fields
    allowed_fields = (
        'slug', 'name', 'accept_translations', 'i18n_type',
        'content', 'category',
    )
    written_fields = (
        'slug', 'name', 'accept_translations', 'content', 'category',
    )

    apiv1_fields = ('slug', 'name', 'created', 'available_languages', 'i18n_type',
                    'source_language', 'project_slug')
    exclude = ()

    def read(self, request, project_slug, resource_slug=None, api_version=1):
        """
        Get details of a resource.
        """
        # Reset fields to default value
        ResourceHandler.fields = self.default_fields
        if "details" in request.GET:
            if resource_slug is None:
                return rc.NOT_IMPLEMENTED
            ResourceHandler.fields = ResourceHandler.details_fields
        return self._read(request, project_slug, resource_slug)

    @method_decorator(one_perm_required_or_403(pr_resource_add_change,
        (Project, 'slug__exact', 'project_slug')))
    def create(self, request, project_slug, resource_slug=None, api_version=1):
        """
        Create new resource under project `project_slug` via POST
        """
        data = getattr(request, 'data', None)
        if resource_slug is not None:
            return BAD_REQUEST("POSTing to this url is not allowed.")
        if data is None:
            return BAD_REQUEST(
                "At least parameters 'slug', 'name', 'i18n_type' "
                "and 'source_language' must be specified,"
                " as well as the source strings."
            )
        try:
            res = self._create(request, project_slug, data)
        except BadRequestError, e:
            return BAD_REQUEST(unicode(e))
        except NotFoundError, e:
            return rc.NOT_FOUND
        t = Translation.get_object("create", request)
        res = t.__class__.to_http_for_create(t, res)
        if res.status_code == 200:
            res.status_code = 201
        return res

    @require_mime('json')
    @method_decorator(one_perm_required_or_403(pr_resource_add_change,
        (Project, 'slug__exact', 'project_slug')))
    def update(self, request, project_slug, resource_slug=None, api_version=1):
        """
        API call to update resource details via PUT
        """
        if resource_slug is None:
            return BAD_REQUEST("No resource specified in url")
        return self._update(request, project_slug, resource_slug)

    @method_decorator(one_perm_required_or_403(pr_resource_delete,
        (Project, 'slug__exact', 'project_slug')))
    def delete(self, request, project_slug, resource_slug=None, api_version=1):
        """
        API call to delete resources via DELETE.
        """
        if resource_slug is None:
            return BAD_REQUEST("No resource provided.")
        return self._delete(request, project_slug, resource_slug)

    def _read(self, request, project_slug, resource_slug):
        if resource_slug is None:
            try:
                p = Project.objects.get(slug=project_slug)
            except Project.DoesNotExist:
                return rc.NOT_FOUND
            if not self._has_perm(request.user, p):
                return rc.FORBIDDEN
            return p.resources.all()
        try:
            resource = Resource.objects.get(
                slug=resource_slug, project__slug=project_slug
            )
        except Resource.DoesNotExist:
            return rc.NOT_FOUND
        if not self._has_perm(request.user, resource.project):
            return rc.FORBIDDEN
        return resource

    def _has_perm(self, user, project):
        """
        Check that the user has access to this resource.
        """
        perm = ProjectPermission(user)
        if not perm.private(project):
            return False
        return True

    @transaction.commit_on_success
    def _create(self, request, project_slug, data):
        # Check for unavailable fields
        try:
            self._check_fields(data.iterkeys(), self.allowed_fields)
        except AttributeError, e:
            msg = "Field '%s' is not allowed." % e
            logger.warning(msg)
            raise BadRequestError(msg)
        # Check for obligatory fields
        for field in ('name', 'slug', 'i18n_type', ):
            if field not in data:
                msg = "Field '%s' must be specified." % field
                logger.warning(msg)
                raise BadRequestError(msg)

        try:
            project = Project.objects.get(slug=project_slug)
        except Project.DoesNotExist, e:
            logger.warning(unicode(e), exc_info=True)
            raise NotFoundError(unicode(e))

        # In multipart/form-encode request variables have lists
        # as values. So we use __getitem__ isntead of pop, which returns
        # the last value
        method = data['i18n_type']; del data['i18n_type']
        if not registry.is_supported(method):
            msg = "i18n_type %s is not supported." % method
            logger.warning(msg)
            raise BadRequestError(msg)
        try:
            slug = data['slug']; del data['slug']
            name = data['name']; del data['name']
            # TODO for all fields
        except KeyError, e:
            msg = "Required field is missing: %s" % e
            logger.warning(msg)
            raise BadRequestError(msg)
        if len(slug) > 50:
            raise BadRequestError(
                "The value for slug is too long. It should be less than "
                "50 characters."
            )

        try:
            content = self._get_content(request, data)
            filename = self._get_filename(request, data)
        except NoContentError, e:
            raise BadRequestError(unicode(e))

        try:
            rb = ResourceBackend()
            rb_create =  rb.create(
                project, slug, name, method, project.source_language, content,
                extra_data={'filename': filename}
            )
            post_resource_save.send(sender=None, instance=Resource.objects.get(
                slug=slug, project=project),
                    created=True, user=request.user)
            return rb_create
        except ResourceBackendError, e:
            raise BadRequestError(unicode(e))

    def _update(self, request, project_slug, resource_slug):
        data = getattr(request, 'data', None)
        if not data:            # Check for {} as well
            return BAD_REQUEST("Empty request")
        try:
            self._check_fields(data.iterkeys(), self.written_fields)
        except AttributeError, e:
            return BAD_REQUEST("Field '%s' is not allowed." % e)

        try:
            project = Project.objects.get(slug=project_slug)
        except Project.DoesNotExist:
            return rc.NOT_FOUND
        i18n_type = data.pop('i18n_type', None)

        try:
            resource = Resource.objects.get(project=project, slug=resource_slug)
        except Resource.DoesNotExist:
            return BAD_REQUEST("Resource %s does not exist" % resource_slug)
        try:
            for key, value in data.iteritems():
                setattr(resource, key, value)
            # if i18n_type is not None:
            #     resource.i18n_method = i18n_typ
            resource.full_clean()
            resource.save()
        except:
            return rc.BAD_REQUEST
        return rc.ALL_OK

    def _delete(self, request, project_slug, resource_slug):
        try:
            resource = Resource.objects.get(
                slug=resource_slug, project__slug=project_slug
            )
        except Resource.DoesNotExist:
            return rc.NOT_FOUND
        try:
            resource.delete()
        except:
            return rc.INTERNAL_ERROR
        return rc.DELETED

    def _check_fields(self, fields, allowed_fields):
        for field in fields:
            if not field in allowed_fields:
                raise AttributeError(field)

    def _get_content(self, request, data):
        """Get the content from the request.

        If it is file-based, return the contents of the file.

        Args:
            request: The django request object.
        Returns:
            The content of the string/file.
        """
        if 'application/json' in request.content_type:
            try:
                return data['content']
            except KeyError, e:
                msg = "No content provided"
                logger.warning(msg)
                raise NoContentError(msg)
        elif 'multipart/form-data' in request.content_type:
            if not request.FILES:
                msg = "No file has been uploaded."
                logger.warning(msg)
                raise NoContentError(msg)
            return content_from_uploaded_file(request.FILES)
        else:
            msg = "No content or file found"
            logger.warning(msg)
            raise NoContentError(msg)

    def _get_filename(self, request, data):
        """Get the filename of the uploaded file.

        Returns:
            The filename or None, if the request used json.
        """
        if 'application/json' in request.content_type:
            return None
        elif 'multipart/form-data' in request.content_type:
            if not request.FILES:
                msg = "No file has been uploaded."
                logger.warning(msg)
                raise NoContentError(msg)
            return filename_of_uploaded_file(request.FILES)
        else:
            msg = "No content or file found"
            logger.warning(msg)
            raise NoContentError(msg)


class StatsHandler(BaseHandler):
    allowed_methods = ('GET', )

    def read(self, request, project_slug, resource_slug,
             lang_code=None, api_version=1):
        """
        This is an API handler to display translation statistics for individual
        resources.
        """
        if api_version == 2:
            return self._get_stats(request=request, pslug=project_slug,
            rslug=resource_slug, lang_code=lang_code)

        # API v1 code
        try:
            resource = Resource.objects.get( project__slug = project_slug,
                slug= resource_slug)
        except Resource.DoesNotExist:
            return BAD_REQUEST("Unknown resource %s" % resource_slug)

        language = None
        if lang_code:
            try:
                language = Language.objects.by_code_or_alias(lang_code)
            except Language.DoesNotExist:
                return BAD_REQUEST("Unknown language %s" % lang_code)


        stats = RLStats.objects.by_resource(resource)
        # TODO: If we're gonna use this as a generic stats generator, we should
        # include more info in the json.
        if language:
            retval = {}
            for stat in stats.by_language(language):
                retval.update({stat.language.code:{"completed": "%s%%" %
                    (stat.translated_perc),
                    "translated_entities": stat.translated, "last_update":
                    stat.last_update}})
        else:
            retval = []
            for stat in stats:
                retval.append({stat.language.code:{"completed": "%s%%" %
                    (stat.translated_perc),
                    "translated_entities": stat.translated}})
        return retval

    def _get_stats(self, request, pslug, rslug, lang_code):
        try:
            resource = Resource.objects.get(project__slug=pslug, slug=rslug)
        except Resource.DoesNotExist, e:
            logger.debug(
                "Resource %s.%s requested, but it does not exist" % (pslug, rslug),
                exc_info=True
            )
            return rc.NOT_FOUND
        language = None
        if lang_code is not None:
            try:
                language = Language.objects.by_code_or_alias(lang_code)
            except Language.DoesNotExist, e:
                logger.debug(
                    "Language %s was requested, but it does not exist." % lang_code,
                    exc_info=True
                )
                return BAD_REQUEST("Unknown language code %s" % lang_code)

        stats = RLStats.objects.by_resource(resource)
        if language is not None:
            stat = stats.by_language(language)[0]
            return {
                'completed': '%s%%' % stat.translated_perc,
                'translated_entities': stat.translated,
                'translated_words': stat.translated_wordcount,
                'untranslated_entities': stat.untranslated,
                'untranslated_words': stat.untranslated_wordcount,
                'last_update': stat.last_update,
                'last_commiter': stat.last_committer.username if stat.last_committer else '',
                'reviewed': stat.reviewed,
                'reviewed_percentage': '%s%%' % stat.reviewed_perc,
            }
        # statistics requested for all languages
        res = {}
        for stat in stats:
            res[stat.language.code] = {
                    'completed': '%s%%' % stat.translated_perc,
                    'translated_entities': stat.translated,
                    'translated_words': stat.translated_wordcount,
                    'untranslated_entities': stat.untranslated,
                    'untranslated_words': stat.untranslated_wordcount,
                    'last_update': stat.last_update,
                    'last_commiter': stat.last_committer.username if stat.last_committer else '',
                    'reviewed': stat.reviewed,
                    'reviewed_percentage': '%s%%' % stat.reviewed_perc,
            }
        return res


class TranslationBaseHandler(BaseHandler):
    allowed_methods = ('GET', 'PUT')
    def _generate_translations_dict(self, translations, field_map={},
            single=False):
        """Generate result to returned to the user for the related
        translations"""
        result = []
        buf = {}
        for count, translation in enumerate(translations):
            d = {}
            append = True
            pluralized = False
            index = -1
            if translation.get('source_entity__pluralized'):
                if buf.get(translation.get('source_entity__id')) != None:
                    index = buf.get(translation.get('source_entity__id'))
                    d = result[index]
                    append = False
                else:
                    buf[translation.get('source_entity__id')] = count
                pluralized = True
            for key in field_map.keys():
                if pluralized:
                    if key == 'string':
                        if append:
                            d[field_map[key]] = {translation['rule']:\
                                    translation['string']}
                        else:
                            d[field_map[key]][translation['rule']] =\
                                    translation['string']
                    elif key == 'wordcount':
                        if append:
                            d[field_map[key]] = translation['wordcount']
                        else:
                            d[field_map[key]] += translation['wordcount']
                    else:
                        d[field_map[key]] = translation[key]
                else:
                    d[field_map[key]] = translation[key]

            if append:
                result.append(d)
            else:
               result[index] = d
        if single:
            if result:
                result = result[0]
            else:
                result = ""
        return result

    def _get_fieldmap_and_fields(self, request):
        fields = [
                'source_entity__id', 'source_entity__string',
                'source_entity__context', 'string',
                'source_entity__pluralized',
                'rule',
        ]

        field_map = {
                'source_entity__id': 'source_entity_id',
                'source_entity__string': 'key',
                'source_entity__context': 'context',
                'string': 'translation',
        }

        if request.GET.has_key('details'):
            fields.extend([
                'reviewed', 'wordcount', 'last_update', 'user__username',
                'source_entity__position', 'source_entity__occurrences',
            ])
            field_map.update({
                'reviewed': 'reviewed',
                'wordcount': 'wordcount',
                'last_update': 'last_update',
                'user__username': 'user',
                'source_entity__position': 'position',
                'source_entity__occurrences': 'occurrences',
                'source_entity__pluralized': 'pluralized'
            })

        return (field_map, fields)

    def _get_filters(self, request, resource, language):

        filters = {
                'resource': resource,
                'language': language,
        }

        if request.GET.get('key'):
            filters.update({'source_entity__string__contains': \
                    request.GET.get('key')})

        if request.GET.get('context'):
            filters.update({'source_entity__context__contains':\
                    request.GET.get('context')})

        return filters

    def _check_read_perms(self, project_slug, resource_slug,
            language_code):
        try:
            project = Project.objects.get(slug=project_slug)
        except Project.DoesNotExist, e:
            return rc.NOT_FOUND
        try:
            resource = Resource.objects.get(slug=resource_slug,
                    project=project)
        except Resource.DoesNotExist, e:
            return rc.NOT_FOUND
        try:
            language = Language.objects.by_code_or_alias(language_code)
        except Language.DoesNotExist, e:
            return rc.NOT_FOUND
        return (project, resource, language)

    def _check_update_perms(self, project_slug, resource_slug,
            language_code):
        read_perms = self._check_read_perms(project_slug, resource_slug,
                language_code)
        if not isinstance(read_perms, tuple):
            return read_perms

        if read_perms[2] == read_perms[1].source_language:
            return rc.FORBIDDEN
        return read_perms

    def _check_data(self, translations):
        if not translations:
            return rc.NOT_FOUND
        if not isinstance(translations, list):
            return rc.BAD_REQUEST

    def _get_trans_obj_dict(self, translations, language):
        se_ids = []
        for translation in translations:
            se_id = translation.get('source_entity_id')
            if se_id:
                se_ids.append(se_id)

        trans_obj_dict = {}
        for t in TranslationModel.objects.filter(
                source_entity__id__in=se_ids, language=language
                ).select_related('source_entity', 'user').iterator():
            if trans_obj_dict.get(t.source_entity.id):
                trans_obj_dict.get(t.source_entity.id).append(t)
            else:
                trans_obj_dict[t.source_entity.id] = [t]

        return trans_obj_dict

    def _check_user_perms(self, can_submit_translations=False,
            accept_translations=False, is_maintainer=False,
            can_review=False, translation_objs=[]):
        if (not can_submit_translations or\
            not accept_translations) and not\
                is_maintainer:
            return False
        if not translation_objs:
            return False
        reviewed = translation_objs[0].reviewed
        if reviewed and not can_review:
            return False
        return True

    def _collect_updated_translations(self, translation, trans_obj_dict,
            se_id, updated_translations, user, pluralized):
        for t in trans_obj_dict.get(se_id):
            t.user = user
            if translation.has_key('reviewed'):
                t.reviewed = translation.get('reviewed')
            if pluralized:
                t.string = translation['translation'].get(str(t.rule))
            else:
                t.string = translation['translation']

            updated_translations.append(t)

    def _check_plural_forms(self, translation, nplurals):
        result = {'pluralized': False, 'error':False}
        if isinstance(translation.get('translation'), dict):
            result['pluralized'] = True
            plural_forms = translation.get('translation').keys()
            for rule in plural_forms:
                if not translation.get('translation').get(rule).strip():
                    plural_forms.pop(rule)
            plural_forms = [int(r) for r in plural_forms]
            plural_forms.sort()
            if plural_forms != nplurals:
                result['error'] = True
        else:
            if not translation.get('translation').strip():
                result['error'] = True
        return result

    @transaction.commit_manually
    def _update_translations(self, updated_translations):
        try:
            TranslationModel.objects.bulk_update(updated_translations)
            transaction.commit()
        except Exception, e:
            transaction.rollback()
            return BAD_REQUEST(unicode(e))

    def _get_update_fieldmap_and_fields(self, keys):
        field_map = {
                'source_entity__id': 'source_entity_id',
                'source_entity__string': 'key',
                'source_entity__context': 'context',
                'string': 'translation',
                'reviewed': 'reviewed',
                'wordcount': 'wordcount',
                'last_update': 'last_update',
                'user__username': 'user',
                'source_entity__position': 'position',
                'source_entity__occurrences': 'occurrences',
                'source_entity__pluralized': 'pluralized'
        }

        fields = []
        field_map_ = {}
        for f in field_map.viewitems():
            if f[1] in keys:
                fields.append(f[0])
                field_map_[f[0]] = f[1]

        if 'source_entity__pluralized' not in fields:
            fields.append('source_entity__pluralized')
        if 'rule' not in fields:
            fields.append('rule')

        return (field_map_, fields)


class SingleTranslationHandler(TranslationBaseHandler):
    """Read and update a single translation"""
    allowed_methods = ('GET', 'PUT')

    @throttle(settings.API_MAX_REQUESTS, settings.API_THROTTLE_INTERVAL)
    @method_decorator(one_perm_required_or_403(
            pr_project_private_perm,
            (Project, 'slug__exact', 'project_slug')
    ))
    def read(self, request, project_slug, resource_slug,
            language_code, source_hash, api_version=2):
        try:
            project = Project.objects.get(slug=project_slug)
        except Project.DoesNotExist, e:
            return rc.NOT_FOUND
        try:
            resource = Resource.objects.get(slug=resource_slug,
                    project=project)
        except Resource.DoesNotExist, e:
            return rc.NOT_FOUND
        try:
            source_entity = SourceEntity.objects.get(string_hash=source_hash,
                    resource=resource)
        except SourceEntity.DoesNotExist, e:
            return rc.NOT_FOUND
        try:
            language = Language.objects.by_code_or_alias(language_code)
        except Language.DoesNotExist, e:
            return rc.NOT_FOUND

        translations = TranslationModel.objects.filter(
                source_entity=source_entity, language=language)

        if not translations:
            return rc.NOT_FOUND

        field_map = {
                'source_entity__id': 'source_entity_id',
                'source_entity__string': 'key',
                'source_entity__context': 'context',
                'string': 'translation',
                'reviewed': 'reviewed',
                'wordcount': 'wordcount',
                'last_update': 'last_update',
                'user__username': 'user',
                'source_entity__position': 'position',
                'source_entity__occurrences': 'occurrences',
                'source_entity__pluralized': 'pluralized'
        }

        fields = field_map.keys()
        fields.append('rule')

        return self._generate_translations_dict(
                translations.values(*fields),
                field_map, True)

    @require_mime('json')
    @throttle(settings.API_MAX_REQUESTS, settings.API_THROTTLE_INTERVAL)
    @method_decorator(one_perm_required_or_403(
            pr_project_private_perm,
            (Project, 'slug__exact', 'project_slug')
    ))
    def update(self, request, project_slug, resource_slug,
            language_code, source_hash, api_version=2):
        try:
            project = Project.objects.get(slug=project_slug)
        except Project.DoesNotExist, e:
            return rc.NOT_FOUND
        try:
            resource = Resource.objects.get(slug=resource_slug,
                    project=project)
        except Resource.DoesNotExist, e:
            return rc.NOT_FOUND
        try:
            source_entity = SourceEntity.objects.get(string_hash=source_hash,
                    resource=resource)
        except SourceEntity.DoesNotExist, e:
            return rc.NOT_FOUND
        try:
            language = Language.objects.by_code_or_alias(language_code)
        except Language.DoesNotExist, e:
            return rc.NOT_FOUND

        if language == source_entity.resource.source_language:
            return rc.FORBIDDEN
        data = request.data
        user = data.get('user') and User.objects.get(username=data.get(
            'user')) or request.user

        team = Team.objects.get_or_none(project, language.code)
        if request.user not in project.maintainers.all() and not (team\
                and request.user in team.coordinators.all()):
            return rc.FORBIDDEN

        check = ProjectPermission(user)
        if (not check.submit_translations(team or resource.project) or\
            not resource.accept_translations) and not\
                check.maintain(resource.project):
            return rc.FORBIDDEN

        translations = TranslationModel.objects.filter(
                source_entity=source_entity, language=language)

        if not translations:
            return rc.NOT_FOUND

        reviewed = translations[0].reviewed

        update_fields = {}
        if check.proofread(project, language):
            if data.get('reviewed') != None:
                update_fields['reviewed'] = data.get('reviewed')
        else:
            if reviewed:
                return rc.FORBIDDEN

        translation_strings = data.get('translation')

        update_fields['user'] = user

        if not source_entity.pluralized:
            update_fields['string']=translation_strings
            translations.filter(rule=5).update(**update_fields)
        else:
            nplurals = language.get_pluralrules_numbers()
            for rule in translation_strings.keys():
                if not translation_strings.get(rule, '').strip():
                    translation_strings.pop(rule)
            plural_forms = translation_strings.keys()
            plural_forms = [int(r) for r in plural_forms]
            plural_forms.sort()
            if nplurals != plural_forms:
                return rc.BAD_REQUEST
            for rule in translation_strings.keys():
                update_fields['string'] = translation_strings[rule]
                translations.filter(rule=rule).update(**update_fields)

        field_map = {
                'source_entity__id': 'source_entity_id',
                'source_entity__string': 'key',
                'source_entity__context': 'context',
                'string': 'translation',
                'reviewed': 'reviewed',
                'wordcount': 'wordcount',
                'last_update': 'last_update',
                'user__username': 'user',
                'source_entity__position': 'position',
                'source_entity__occurrences': 'occurrences',
                'source_entity__pluralized': 'pluralized'
        }

        fields = field_map.keys()
        fields.append('rule')

        return self._generate_translations_dict(
                translations.values(*fields),
                field_map, True)


class TranslationObjectsHandler(TranslationBaseHandler):
    """
    Read and update a set of translations in
    a language for a resource.
    """
    allowed_methods = ('GET', 'PUT')

    @throttle(settings.API_MAX_REQUESTS, settings.API_THROTTLE_INTERVAL)
    @method_decorator(one_perm_required_or_403(
            pr_project_private_perm,
            (Project, 'slug__exact', 'project_slug')
    ))
    def read(self, request, project_slug, resource_slug,
            language_code, api_version=2):
        read_perms = self._check_read_perms(project_slug, resource_slug,
                language_code)
        if isinstance(read_perms, tuple):
            project, resource, language = read_perms
        else:
            return read_perms

        field_map, fields =\
                self._get_fieldmap_and_fields(request)

        filters = self._get_filters(request, resource, language)

        translations = TranslationModel.objects.filter(**filters
                ).values(*fields)
        return self._generate_translations_dict(translations, field_map)

    @require_mime('json')
    @throttle(settings.API_MAX_REQUESTS, settings.API_THROTTLE_INTERVAL)
    @method_decorator(one_perm_required_or_403(
            pr_project_private_perm,
            (Project, 'slug__exact', 'project_slug')
    ))
    def update(self, request, project_slug, resource_slug,
            language_code, api_version=2):
        update_perms = self._check_update_perms(project_slug,
                resource_slug, language_code)
        if not isinstance(update_perms, tuple):
            return update_perms
        else:
            project, resource, language = update_perms
        translations = request.data

        checked_data =  self._check_data(translations)
        if checked_data:
            return checked_data

        team = Team.objects.get_or_none(project, language.code)

        if request.user not in project.maintainers.all() or (team and\
                request.user not in team.coordinators.all()):
            return rc.FORBIDDEN

        nplurals = language.get_pluralrules_numbers()
        keys = translations[0].keys()

        trans_obj_dict = self._get_trans_obj_dict(translations, language)

        updated_translations = []
        se_ids = []

        for translation in translations:
            try:
                se_id = translation.get('source_entity_id')
                user = translation.get('user') and \
                        User.objects.get(trasnlation.get('user')) or\
                        request.user

                check = ProjectPermission(user)
                can_review = check.proofread(project, language)
                can_submit_translations = check.submit_translations(
                        team or resource.project)
                accept_translations = resource.accept_translations
                is_maintainer = check.maintain(resource.project)

                translation_objs = trans_obj_dict.get(se_id)

                kwargs = {
                    'can_review': can_review,
                    'can_submit_translations': can_submit_translations,
                    'accept_translations': accept_translations,
                    'is_maintainer': is_maintainer,
                    'translation_objs': translation_objs
                }

                if not self._check_user_perms(**kwargs):
                    continue

                plurals_check = self._check_plural_forms(translation, nplurals)
                if plurals_check['error']:
                    continue
                pluralized = plurals_check['pluralized']

                self._collect_updated_translations(
                        translation, trans_obj_dict, se_id,
                        updated_translations, user, pluralized)

            except User.DoesNotExist, e:
                return BAD_REQUEST(unicode(e))
            except Exception, e:
                return BAD_REQUEST(unicode(e))
            se_ids.append(se_id)

        error = self._update_translations(updated_translations)
        if error:
            return error
        field_map, fields = self._get_update_fieldmap_and_fields(keys)

        return self._generate_translations_dict(
                TranslationModel.objects.filter(source_entity__id__in=se_ids,
                    language=language).values(*fields),
                field_map)



class TranslationHandler(BaseHandler):
    allowed_methods = ('GET', 'PUT', 'DELETE',)

    @throttle(settings.API_MAX_REQUESTS, settings.API_THROTTLE_INTERVAL)
    @method_decorator(one_perm_required_or_403(
            pr_project_private_perm,
            (Project, 'slug__exact', 'project_slug')
    ))
    def read(self, request, project_slug, resource_slug,
             lang_code=None, is_pseudo=None, api_version=2):
        return self._read(request, project_slug, resource_slug, lang_code, is_pseudo)

    @throttle(settings.API_MAX_REQUESTS, settings.API_THROTTLE_INTERVAL)
    def update(self, request, project_slug, resource_slug,
               lang_code, api_version=2):
        return self._update(request, project_slug, resource_slug, lang_code)

    @method_decorator(one_perm_required_or_403(
            pr_resource_translations_delete,
            (Project, "slug__exact", "project_slug")))
    def delete(self, request, project_slug, resource_slug,
               lang_code=None, api_version=2):
        return self._delete(request, project_slug, resource_slug, lang_code)

    def _read(self, request, project_slug, resource_slug, lang_code, is_pseudo):
        try:
            r = Resource.objects.get(
                slug=resource_slug, project__slug=project_slug
            )
        except Resource.DoesNotExist:
            return rc.NOT_FOUND

        if lang_code == "source":
            language = r.source_language
        else:
            try:
                language = Language.objects.by_code_or_alias(lang_code)
            except Language.DoesNotExist:
                return rc.NOT_FOUND

        # Check whether the request asked for a pseudo file, if so check if
        # a ``pseudo_type`` GET var was passed with a valid pseudo type.
        if is_pseudo:
            ptype = request.GET.get('pseudo_type', None)
            if not ptype in settings.PSEUDO_TYPES.keys():
                return rc.NOT_FOUND
            # Instantiate Pseudo type object
            pseudo_type = get_pseudo_class(ptype)(r.i18n_type)
        else:
            pseudo_type = None

        # Get the mode the user requested, if any
        mode = request.GET.get('mode', None)
        if mode is not None:
            try:
                mode = getattr(Mode, mode.upper())
            except AttributeError, e:
                return BAD_REQUEST(unicode(e))

        translation = Translation.get_object("get", request, r, language)
        try:
            res = translation.get(pseudo_type=pseudo_type, mode=mode)
        except BadRequestError, e:
            return BAD_REQUEST(unicode(e))
        except FormatsBackendError, e:
            return BAD_REQUEST(unicode(e))
        return translation.__class__.to_http_for_get(
            translation, res
        )

    def _update(self, request, project_slug, resource_slug, lang_code=None):
        # Permissions handling
        try:
            resource = Resource.objects.select_related('project').get(
                slug=resource_slug, project__slug=project_slug
            )
        except Resource.DoesNotExist:
            return rc.NOT_FOUND
        source_push = False
        if lang_code == "source":
            language = resource.source_language
            source_push = True
        else:
            try:
                language =  Language.objects.by_code_or_alias(lang_code)
            except Language.DoesNotExist:
                logger.error("Weird! Selected language code (%s) does "
                             "not match with any language in the database."
                             % lang_code)
                return BAD_REQUEST(
                    "Selected language code (%s) does not match with any"
                    "language in the database." % lang_code
                )

        team = Team.objects.get_or_none(resource.project, lang_code)
        check = ProjectPermission(request.user)
        if source_push and not check.maintain(resource.project):
            return rc.FORBIDDEN
        elif (not check.submit_translations(team or resource.project) or\
            not resource.accept_translations) and not\
                check.maintain(resource.project):
            return rc.FORBIDDEN

        try:
            t = Translation.get_object("create", request, resource, language)
            res = t.create()
        except BadRequestError, e:
            return BAD_REQUEST(unicode(e))
        except NoContentError, e:
            return BAD_REQUEST(unicode(e))
        except AttributeError, e:
            return BAD_REQUEST("The content type of the request is not valid.")
        return t.__class__.to_http_for_create(t, res)

    def _delete(self, request, project_slug, resource_slug, lang_code):
        try:
            resource = Resource.objects.get(
                slug=resource_slug, project__slug=project_slug
            )
        except Resource.DoesNotExist, e:
            return rc.NOT_FOUND

        # Error message to use in case user asked to
        # delete the source translation
        source_error_msg = "You cannot delete the translation in the" \
                " source language."
        if lang_code == 'source':
            return BAD_REQUEST(source_error_msg)
        try:
            language = Language.objects.by_code_or_alias(lang_code)
        except Language.DoesNotExist:
            return rc.NOT_FOUND
        if language == resource.source_language:
            return BAD_REQUEST(source_error_msg)
        if language not in resource.available_languages:
            return rc.NOT_FOUND

        t = Translation.get_object("delete", request, resource, language)
        t.delete()
        return rc.DELETED


class Translation(object):
    """
    Handle a translation for a resource.
    """

    @staticmethod
    def get_object(type_, request, *args):
        """
        Factory method to get the suitable object for the request.
        """
        if type_ == "get":
            if 'file' in request.GET:
                return FileTranslation(request, *args)
            else:
                return StringTranslation(request, *args)
        elif type_ == "create":
            if request.content_type == "application/json":
                return StringTranslation(request, *args)
            elif "multipart/form-data" in request.content_type:
                return FileTranslation(request, *args)
        elif type_ == "delete":
            return Translation(request, *args)
        return None


    @classmethod
    def _to_http_response(cls, translation, result,
                          status=200, mimetype='application/json'):
        return HttpResponse(result, status=status, mimetype=mimetype)

    @classmethod
    def to_http_for_get(cls, translation, result):
        """
        Return the result to a suitable HttpResponse for a GET request.

        Args:
            translation: The translation object.
            result: The result to convert to a HttpResponse.

        Returns:
            A HttpResponse with the result.
        """
        return cls._to_http_response(translation, result, status=200)

    @classmethod
    def to_http_for_create(cls, translation, result):
        """
        Return the result to a suitable HttpResponse for a PUT/POST request.

        Args:
            translation: The translation object.
            result: The result to convert to a HttpResponse.

        Returns:
            A HttpResponse with the result.
        """
        return cls._to_http_response(translation, result, status=200)

    def __init__(self, request, resource=None, language=None):
        """
        Initializer.

        Args:
            request: The request
            resource: The resource the translation is asked for.
            language: The language of the requested translation.

        """
        self.request = request
        self.data = getattr(request, 'data', 'None')
        self.resource = resource
        self.language = language

    def create(self):
        """
        Create a new translation.
        """
        raise NotImplementedError

    @transaction.commit_on_success
    def delete(self):
        """
        Delete a specific translation.

        Delete all Translation objects that belong to the specified resource
        and are in the specified language.
        """
        TranslationModel.objects.filter(
            resource=self.resource,
            language=self.language
        ).delete()
        invalidate_stats_cache(
            self.resource, self.language, user=self.request.user
        )

    def get(self, pseudo_type, mode=None):
        """Get a translation.

        Args:
            pseudo_type: The pseudo_type to use, if any.
            mode: The mode of compilation, if any.
        """
        raise NotImplementedError

    def _parse_translation(self, parser):
        """
        Parses a source/translation file.

        We assume the content has been checked for validity
        by now.
        """
        strings_added, strings_updated = 0, 0
        parser.bind_resource(self.resource)
        parser.set_language(self.language)

        is_source = self.resource.source_language == self.language
        try:
            parser.parse_file(is_source)
            strings_added, strings_updated = parser.save2db(
                is_source, user=self.request.user
            )
        except Exception, e:
            raise BadRequestError("Could not import file: %s" % e)

        messages = []
        if strings_added > 0:
            messages.append(_("%i strings added") % strings_added)
        if strings_updated > 0:
            messages.append(_("%i strings updated") % strings_updated)
        retval= {
            'strings_added': strings_added,
            'strings_updated': strings_updated,
            'redirect': reverse(
                'resource_detail',
                args=[self.resource.project.slug, self.resource.slug]
            )
        }
        logger.debug("Extraction successful, returning: %s" % retval)

        # If any string added/updated
        if retval['strings_added'] > 0 or retval['strings_updated'] > 0:
            modified = True
        else:
            modified=False
        post_submit_translation.send(
            None, request=self.request, resource=self.resource,
            language=self.language, modified=modified
        )

        return retval


class FileTranslation(Translation):
    """
    Handle requests for translation as files.
    """

    @classmethod
    def to_http_for_get(cls, translation, result):
        response = HttpResponse(
            result, mimetype=registry.mimetypes_for(
                translation.resource.i18n_method
            )[0]
        )
        response['Content-Disposition'] = (
            'attachment; filename*="UTF-8\'\'%s_%s%s"' % (
                urllib.quote(translation.resource.name.encode('UTF-8')),
                translation.language.code,
                registry.file_extension_for(
                    translation.resource, translation.language
                )
            )
        )
        return response

    def get(self, pseudo_type, mode=None):
        """
        Return the requested translation as a file.

        Returns:
            The compiled template.

        Raises:
            BadRequestError: There was a problem with the request.
        """
        try:
            fb = FormatsBackend(self.resource, self.language)
            return fb.compile_translation(pseudo_type, mode=mode)
        except Exception, e:
            logger.error(unicode(e), exc_info=True)
            raise BadRequestError("Error compiling the translation file: %s" %e )

    def create(self):
        """
        Creates a new translation from file.

        Returns:
            A dict with information for the translation.

        Raises:
            BadRequestError: There was a problem with the request.
            NoContentError: There was no file in the request.
        """
        if not self.request.FILES:
            raise NoContentError("No file has been uploaded.")

        submitted_file = self.request.FILES.values()[0]
        name = str(submitted_file.name)
        size = submitted_file.size

        try:
            file_ = tempfile.NamedTemporaryFile(
                mode='wb',
                suffix=name[name.rfind('.'):],
                delete=False
            )
            for chunk in submitted_file.chunks():
                file_.write(chunk)
            file_.close()

            parser = registry.appropriate_handler(
                self.resource,
                language=self.language,
                filename=name
            )
            parser.bind_file(file_.name)
            if parser is None:
                raise BadRequestError("Unknown file type")
            if size == 0:
                raise BadRequestError("Empty file")

            try:
                parser.is_content_valid()
                logger.debug("Uploaded file %s" % file_.name)
            except (FileCheckError, ParseError), e:
                raise BadRequestError("Error uploading file: %s" % e)
            except Exception, e:
                logger.error(unicode(e), exc_info=True)
                raise BadRequestError("A strange error happened.")

            parser.bind_file(file_.name)
            res = self._parse_translation(parser)
        finally:
            os.unlink(file_.name)
        return res


class StringTranslation(Translation):
    """
    Handle requests for translation as strings.
    """

    def get(self, start=None, end=None, pseudo_type=None, mode=None):
        """
        Return the requested translation in a json string.

        If self.language is None, return all translations.

        Args:
            start: Start for pagination.
            end: End for pagination.
            pseudo_type: The pseudo_type requested.
            mode: The mode for the compilation.
        Returns:
            A dict with the translation(s).
        Raises:
            BadRequestError: There was a problem with the request.
        """
        try:
            fb = FormatsBackend(self.resource, self.language)
            template = fb.compile_translation(pseudo_type, mode=mode)
        except Exception, e:
            logger.error(unicode(e), exc_info=True)
            raise BadRequestError(
                "Error compiling the translation file: %s" % e
            )

        if self.resource.i18n_method == 'PROPERTIES':
            template = template.decode('ISO-8859-1')
        return {
            'content': template,
            'mimetype': registry.mimetypes_for(self.resource.i18n_method)[0]
        }

    def create(self):
        """
        Create a new translation supplied as a string.

        Returns:
            A dict with information for the request.

        Raises:
            BadRequestError: There was a problem with the request.
            NoContentError: There was no content string in the request.
        """
        if 'content' not in self.data:
            raise NoContentError("No content found.")
        parser = registry.appropriate_handler(
            self.resource, language=self.language
        )
        if parser is None:
            raise BadRequestError("I18n type is not supported: %s" % i18n_type)

        file_ = tempfile.NamedTemporaryFile(
            mode='wb',
            suffix=registry.extensions_for(self.resource.i18n_method)[0],
            delete=False,
        )
        try:
            file_.write(self.data['content'].encode('UTF-8'))
            file_.close()
            try:
                parser.bind_file(file_.name)
                parser.is_content_valid()
            except (FileCheckError, ParseError), e:
                raise BadRequestError(unicode(e))
            except Exception, e:
                logger.error(unicode(e), exc_info=True)
                raise BadRequestError("A strange error has happened.")

            parser.bind_file(file_.name)
            res = self._parse_translation(parser)
        finally:
            os.unlink(file_.name)
        return res

class FormatsHandler(BaseHandler):
    """
    Formats Handler for READ operation.
    """
    allowed_methods = ('GET',)

    def read(self, request, api_version=1):
        """
        Get details of supported i18n formats.
        """
        return registry.available_methods
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.