Example #1
0
def delete_own_comment(request):
    comment = get_object_or_404(comments.get_model(), pk=int(request.POST["comment_id"]), site__pk=settings.SITE_ID)
    response = HttpResponse(mimetype="text/html")
    if comment.user == request.user:
        comment.delete()
        response.write("deleted")
    return response
Example #2
0
def series_mbox(revision):
    patches = revision.ordered_patches()
    data = "\n".join([patch_to_mbox(x).as_string(True) for x in patches])
    response = HttpResponse(content_type="text/plain")
    response.write(data)
    response["Content-Disposition"] = "attachment; filename=" + revision.series.filename()
    return response
Example #3
0
def detail_json(request, indice_sondage):
    sondage = (
        Sondage.objects.filter(date_parution__isnull=False)
        .filter(date_parution__lte=datetime.date.today())
        .order_by("-date_parution")[int(indice_sondage)]
    )
    nombre_reponse = Vote.objects.filter(sondage=sondage).count()
    nombre_reponse_1 = Vote.objects.filter(sondage=sondage, choix=1).count()
    nombre_reponse_2 = Vote.objects.filter(sondage=sondage, choix=2).count()
    is_dernier = (
        int(indice_sondage)
        >= Sondage.objects.filter(date_parution__isnull=False).filter(date_parution__lte=datetime.date.today()).count()
        - 1
    )
    is_premier = int(indice_sondage) <= 0
    response = HttpResponse(mimetype="application/json")
    response.write(
        json.dumps(
            {
                "question": sondage.question,
                "reponse1": sondage.reponse1,
                "reponse2": sondage.reponse2,
                "nombre_reponse": nombre_reponse,
                "nombre_reponse_1": nombre_reponse_1,
                "nombre_reponse_2": nombre_reponse_2,
                "date_parution": sondage.date_str(),
                "is_premier": is_premier,
                "is_dernier": is_dernier,
            }
        )
    )
    return response
Example #4
0
def action_csv(request):

    json_val = None
    csvfile = ""
    dashboard_name = None

    json_val = request.REQUEST.get("json")
    response = json.loads(json_val)
    dashboard_name = response["name"].replace(" ", "_").encode("utf-8", "ignore")

    csvfile += dashboard_name + ",,,\n\n"

    i = 0
    for row_number in response["datastreams"]:
        value = response["datastreams"][i]
        datastreamrevision_id = value["id"]
        end_point = value["end_point"]
        query = {"pId": datastreamrevision_id}
        for k, v in urlparse.parse_qs(end_point).items():
            query[k] = v[0]
        json_response, type = invoke(query)
        loaded_json = json.loads(json_response)
        csv_emitter = CSVEmitter(loaded_json, name=u"")
        csvfile += str(csv_emitter.render()) + "\n\n\n\n\n\n"
        i += 1

    filename = "%s.csv" % (dashboard_name)
    response = HttpResponse(mimetype="text/csv")
    response["Content-Disposition"] = "attachment; filename=" + filename
    response.write(csvfile)

    return response
Example #5
0
def ascsv(request):
    response = HttpResponse(mimetype="text/csv")
    response["Content-Disposition"] = "attachment; filename=respectmynet.csv"

    res = []
    for v in Violation.objects.filter(activationid=""):
        res.append(
            (
                v.state,
                v.country,
                v.operator,
                v.contract,
                v.resource,
                v.resource_name,
                v.type,
                v.media,
                v.temporary,
                v.contractual,
                v.contract_excerpt,
                v.loophole,
                v.editorial,
                v.comment_set.get().comment,
            )
        )
    t = loader.get_template("csv.tmpl")
    c = Context({"data": res})
    response.write(t.render(c))
    return response
Example #6
0
 def _outer(request, *args, **kwargs):
     if ApiUser.auth(request.POST.get("username", ""), request.POST.get("password", ""), permission):
         response = fn(request, *args, **kwargs)
     else:
         response = HttpResponse()
         response.status_code = 401
     return response
Example #7
0
def login(request):

    if request.user.is_authenticated():
        response = HttpResponse()
        response.status_code = 303
        response["location"] = "account"
        return response

    loginFailed = False
    if request.method == "POST":

        data = request.POST
        username = data["username"]
        password = data["password"]

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                auth_login(request, user)

                response = HttpResponse()
                response.status_code = 303
                response["location"] = "account"
                return response

            else:
                loginFailed = True
        else:
            loginFailed = True

    return render(request, "app/login.html", {"loginFailed": loginFailed})
Example #8
0
    def test_unicode_headers(self):
        r = HttpResponse()

        # If we insert a unicode value it will be converted to an ascii
        r["value"] = u"test value"
        self.assertTrue(isinstance(r["value"], str))

        # An error is raised when a unicode object with non-ascii is assigned.
        self.assertRaises(UnicodeEncodeError, r.__setitem__, "value", u"t\xebst value")

        # An error is raised when  a unicode object with non-ASCII format is
        # passed as initial mimetype or content_type.
        self.assertRaises(UnicodeEncodeError, HttpResponse, content_type=u"t\xebst value")

        # HttpResponse headers must be convertible to ASCII.
        self.assertRaises(UnicodeEncodeError, HttpResponse, content_type=u"t\xebst value")

        # The response also converts unicode keys to strings.)
        r[u"test"] = "testing key"
        l = list(r.items())
        l.sort()
        self.assertEqual(l[1], ("test", "testing key"))

        # It will also raise errors for keys with non-ascii data.
        self.assertRaises(UnicodeEncodeError, r.__setitem__, u"t\xebst key", "value")
Example #9
0
    def test_iter_content(self):
        r = HttpResponse(["abc", "def", "ghi"])
        self.assertEqual(r.content, "abcdefghi")

        # test iter content via property
        r = HttpResponse()
        r.content = ["idan", "alex", "jacob"]
        self.assertEqual(r.content, "idanalexjacob")

        r = HttpResponse()
        r.content = [1, 2, 3]
        self.assertEqual(r.content, "123")

        # test retrieval explicitly using iter and odd inputs
        r = HttpResponse()
        r.content = ["1", u"2", 3, unichr(1950)]
        result = []
        my_iter = r.__iter__()
        while True:
            try:
                result.append(my_iter.next())
            except StopIteration:
                break
        #'\xde\x9e' == unichr(1950).encode('utf-8')
        self.assertEqual(result, ["1", "2", "3", "\xde\x9e"])
        self.assertEqual(r.content, "123\xde\x9e")

        # with Content-Encoding header
        r = HttpResponse([1, 1, 2, 4, 8])
        r["Content-Encoding"] = "winning"
        self.assertEqual(r.content, "11248")
        r.content = [unichr(1950)]
        self.assertRaises(UnicodeEncodeError, getattr, r, "content")
Example #10
0
def moduleDescriptions(request, module=None):
    logging.info("MODULE: " + module)

    html = render_to_string("01cts_uberheader.html", {"title": "Error"})
    html += render_to_string("02cts_uberintroblock_nomodellinks.html", {"title2": "File not found"})
    html += linksLeft.linksLeft()

    module_text = ""
    if module == "chemedit-description":
        module_text = chemeditDescription()
    elif module == "pchemprop-description":
        module_text = pchempropDescription()
    elif module == "reactsim-description":
        module_text = reactsimDescription()
    elif module == "mamm-metabo":
        module_text = mMetabolismDescription()

        # body of page:
    html += render_to_string("04ubertext_start.html", {"model_attributes": "", "text_paragraph": module_text})

    html += render_to_string("04cts_ubertext_end.html", {})
    html += render_to_string("05cts_ubertext_links_right.html", {})
    html += render_to_string("06cts_uberfooter.html", {"links": ""})

    response = HttpResponse()
    response.write(html)

    return response
Example #11
0
def create_polygon(request):
    """Create a new Polygon

    Used a function based view here to show it's usage with more complicated
    requests"""
    if request.method == "GET":
        allowed_methods = ["POST"]
        return HttpResponseNotAllowed(allowed_methods)

    name = request.POST.get("name")
    vertices = request.POST.getlist("vertices[]")
    if len(vertices) < 3:
        msg = _(u"Not enought vertices." u" A valid service area should have 3 or more")
        response = HttpResponse(msg)
        response.status_code = 400  # Bad request
    else:
        # Get polygon or create a new one
        shape, created = Polygon.objects.get_or_create(name=name)
        # Check if the vertices already belong to the shape or add them
        # FIXME: check if vertices already belong to shape before creating
        for each in vertices:
            lat, lon = each.split(",")
            shape.vertices.create(lat=lat, lon=lon)

        if not created:
            msg = _(u"Service area updated")
            status_code = 200  # Ok
        else:
            msg = _(u"Service area created")
            status_code = 201  # Created
        response = HttpResponse(msg)
        response.status_code = status_code

    return response
Example #12
0
    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        if form.is_valid():
            lang_code = request.POST.get("language", None)
            next = request.REQUEST.get("next", None)
            if request.is_ajax():
                response = HttpResponse(json.dumps({"success": True}), mimetype="application/json")
            else:
                response = http.HttpResponseRedirect(next)
            if lang_code and check_for_language(lang_code):
                if hasattr(request, "session"):
                    request.session[settings.LANGUAGE_COOKIE_NAME] = lang_code
                else:
                    response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
            return response

        if request.is_ajax():
            errors = " ".join(form.non_field_errors())
            for fieldname, errorlist in form.errors.items():
                if fieldname in form.fields:
                    errors += " " + form.fields[fieldname].label + ": "
                    errors += " ".join(errorlist)
                else:
                    errors += " ".join(errorlist)
            return HttpResponse(json.dumps({"success": False, "error_message": errors}), mimetype="application/json")
        return self.form_invalid(form)
Example #13
0
def get_uuid_displayname_catalogs(request, user_call=True):
    # Normal Response Codes: 200
    # Error Response Codes: BadRequest (400)

    try:
        input_data = json.loads(request.body)
    except:
        raise faults.BadRequest("Request body should be json formatted.")
    else:
        if not isinstance(input_data, dict):
            raise faults.BadRequest("Request body should be a json formatted dictionary")
        uuids = input_data.get("uuids", [])
        if uuids is None and user_call:
            uuids = []
        displaynames = input_data.get("displaynames", [])
        if not isinstance(displaynames, list):
            raise faults.BadRequest("Invalid displaynames: %s" % displaynames)
        for item in displaynames:
            if not isinstance(item, str):
                raise faults.BadRequest("Items in 'displaynames' must be " "strings")
        if displaynames is None and user_call:
            displaynames = []
        user_obj = AstakosUser.objects
        d = {
            "uuid_catalog": user_obj.uuid_catalog(uuids),
            "displayname_catalog": user_obj.displayname_catalog(displaynames),
        }

        response = HttpResponse()
        response.content = json.dumps(d)
        response["Content-Type"] = "application/json; charset=UTF-8"
        response["Content-Length"] = len(response.content)
        return response
Example #14
0
def index_json(request):
    list_messages = (
        Message.objects.filter(
            Q(destinataire__isnull=True)
            | Q(destinataire__in=request.user.get_profile().association_set.all())
            | Q(association__in=request.user.get_profile().association_set.all())
        )
        .exclude(lu__user__username=request.user.username)
        .order_by("-date")
    )
    response = HttpResponse(mimetype="application/json")
    response.write(
        simplejson.dumps(
            [
                {
                    "association": m.association.nom,
                    "association_pseudo": m.association.pseudo,
                    "objet": m.objet,
                    "contenu": m.html_to_text(),
                    "date": str(m.date.day)
                    + "/"
                    + str(m.date.month)
                    + "/"
                    + str(m.date.year)
                    + " "
                    + str(m.date.hour)
                    + ":"
                    + str(m.date.minute),
                    "expediteur": m.expediteur.user.username,
                }
                for m in list_messages
            ]
        )
    )
    return response
Example #15
0
    def download_files(self, langs, app):
        in_memory = StringIO()
        zip_file = ZipFile(in_memory, "a")
        for l in langs:
            if l.name == "English":
                zip_file.writestr("values/strings.xml", self.generate_file(l, app))
            else:
                # There's more than one language register with that language
                # code. Subculture code must be specified.
                if langs.filter(iso_639=l.iso_639).count() > 1:
                    zip_file.writestr("values-%s-r%s/strings.xml" % (l.iso_639, l.iso_3166), self.generate_file(l, app))
                else:
                    zip_file.writestr("values-%s/strings.xml" % l.iso_639, self.generate_file(l, app))

        # Fix for Linux zip files read in Windows
        for file in zip_file.filelist:
            file.create_system = 0

        zip_file.close()

        response = HttpResponse(mimetype="application/zip")
        response["Content-Disposition"] = "attachment; filename=%s.zip" % (app.__unicode__().replace(" ", "-"))
        response["Content-Length"] = in_memory.tell()

        in_memory.seek(0)
        response.write(in_memory.read())
        return response
Example #16
0
def language(request, language="en-gb"):
    response = HttpResponse("settings language to %s" % language)

    response.set_cookie("lang", language)

    request.session["lang"] = language
    return response
Example #17
0
    def download_files(self, langs, app):
        in_memory = StringIO()

        zip_file = ZipFile(in_memory, "a")
        for l in langs:
            if l.name == "English":
                zip_file.writestr("Strings-AppResources.xml", self.generate_file(l, app))
            else:
                zip_file.writestr(
                    "Strings-AppResources.%s-%s.xml" % (l.iso_639, l.iso_3166), self.generate_file(l, app)
                )

        # Fix for Linux zip files read in Windows
        for file in zip_file.filelist:
            file.create_system = 0

        zip_file.close()

        response = HttpResponse(mimetype="application/zip")
        response["Content-Disposition"] = "attachment; filename=%s.zip" % (app.__unicode__().replace(" ", "-"))
        response["Content-Length"] = in_memory.tell()

        in_memory.seek(0)
        response.write(in_memory.read())
        return response
Example #18
0
def deferred(request):
    from google.appengine.ext.deferred.deferred import run, SingularTaskFailure, PermanentTaskFailure

    response = HttpResponse()

    if "HTTP_X_APPENGINE_TASKEXECUTIONCOUNT" in request.META:
        logging.debug("[DEFERRED] Retry %s of deferred task", request.META["HTTP_X_APPENGINE_TASKEXECUTIONCOUNT"])

    if "HTTP_X_APPENGINE_TASKNAME" not in request.META:
        logging.critical('Detected an attempted XSRF attack. The header "X-AppEngine-Taskname" was not set.')
        response.status = 403
        return response

    in_prod = on_production()

    if in_prod and os.environ.get("REMOTE_ADDR") != "0.1.0.2":
        logging.critical("Detected an attempted XSRF attack. This request did not originate from Task Queue.")
        response.status = 403
        return response

    try:
        run(request.body)
    except SingularTaskFailure:
        logging.debug("Failure executing task, task retry forced")
        response.status = 408
    except PermanentTaskFailure:
        logging.exception("Permanent failure attempting to execute task")

    return response
Example #19
0
def inventory(request):
    if request.method == "POST":
        # get the pending invoice for this user.
        # if one doesn't exist then create a new one
        user_invoice = Invoice.get_cart_invoice(request.user)

        if not user_invoice:
            response = HttpResponse()
            response.status_code = 303
            response["location"] = "login"
            return response

        inventoryItem = InventoryType.objects.get(product_name=request.POST["item"])

        itemCount = int(request.POST["quantity"])
        # add invoice items to the invoice with the drone
        for x in range(itemCount):
            inv_item = InvoiceItem(invoice=user_invoice, inventory_type=inventoryItem)
            inv_item.save()

            # update the inventory count
        inventoryItem.stock_count = inventoryItem.stock_count - itemCount
        inventoryItem.save()

        response = HttpResponse()
        response.status_code = 303
        if request.POST["submit"] == "add and go to checkout":
            response["location"] = "checkout"
        else:
            response["location"] = "inventory#body"
        return response

    inventory_items = InventoryType.objects.all()
    context = {"inventory_items": inventory_items}
    return render(request, "app/inventory.html", context)
Example #20
0
def generar_pdf(request):
    print "Genero el PDF"
    response = HttpResponse(content_type="application/pdf")
    pdf_name = "clientes.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    buff = BytesIO()
    doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=40, leftMargin=40, topMargin=60, bottomMargin=18)
    mercaderias = []
    styles = getSampleStyleSheet()
    header = Paragraph("Listado de Ingreso de Mercaderia", styles["Heading1"])
    mercaderias.append(header)
    headings = ("Codigo", "Fecha de ingreso", "Total", "Proveedor")
    allMercaderi = [
        (m.id, m.fec_mercaderia, m.tot_mercaderia, (Proveedor.objects.get(id=m.proveedor_id)))
        for m in Mercaderia.objects.all()
    ]
    print allMercaderi

    t = Table([headings] + allMercaderi)
    t.setStyle(
        TableStyle(
            [
                ("GRID", (0, 0), (3, -1), 1, colors.dodgerblue),
                ("LINEBELOW", (0, 0), (-1, 0), 2, colors.darkblue),
                ("BACKGROUND", (0, 0), (-1, 0), colors.dodgerblue),
            ]
        )
    )
    mercaderias.append(t)
    doc.build(mercaderias)
    response.write(buff.getvalue())
    buff.close()
    return response
Example #21
0
    def __call__(self, request, *args, **kwargs):
        # HTTP auth check inspired by http://djangosnippets.org/snippets/243/
        if request.user.is_authenticated():
            # already logged in
            return super(HTTPAuthFeed, self).__call__(request, *args, **kwargs)

        # check HTTP auth credentials
        if "HTTP_AUTHORIZATION" in request.META:
            auth = request.META["HTTP_AUTHORIZATION"].split()
            if len(auth) == 2:
                # only basic auth is supported
                if auth[0].lower() == "basic":
                    uname, passwd = base64.b64decode(auth[1]).split(":")
                    user = authenticate(username=uname, password=passwd)
                    if user is not None:
                        if user.is_active:
                            login(request, user)
                            request.user = user
                            return super(HTTPAuthFeed, self).__call__(request, *args, **kwargs)

        # missing auth header or failed authentication results in 401
        response = HttpResponse()
        response.status_code = 401
        response["WWW-Authenticate"] = 'Basic realm="%s"' % self.basic_auth_realm
        return response
Example #22
0
    def mkcalendar(self, request, user, resource_name):

        resource = self.get_resource(request, user, resource_name, create=True, collection=True, strict=True)

        cl = int(request.META.get("CONTENT_LENGTH", "0"))
        if cl > 0:
            try:
                dom = etree.fromstring(request.read())
            except:
                raise davvy.exceptions.BadRequest()

            # logger.debug(etree.tostring(dom, pretty_print=True))

            for prop in dom.find("{DAV:}set").find("{DAV:}prop"):
                try:
                    resource.set_prop(self, request, prop.tag, prop)
                except davvy.exceptions.Forbidden:
                    pass

            doc = etree.Element("{urn:ietf:params:xml:ns:caldav}mkcalendar-response")
            doc_propstat = etree.Element("{DAV:}propstat")
            doc_propstat_status = etree.Element("{DAV:}status")
            doc_propstat_status.text = request.META["SERVER_PROTOCOL"] + " 200 OK"
            doc_propstat.append(doc_propstat_status)
            doc.append(doc_propstat)

            response = HttpResponse(etree.tostring(doc, pretty_print=True), content_type="text/xml; charset=utf-8")
        else:
            response = HttpResponse()
        response.status_code = 201
        response.reason_phrase = "Created"
        response["Cache-Control"] = "no-cache"
        return response
Example #23
0
def run(req):
    r = HttpResponse()
    r["Access-Control-Allow-Origin"] = "*"
    if req.method == "OPTIONS" or len(req.POST) == 0:  # FF3 trying to check if Cross Site Request allowed.
        # print "options request"
        return r
    else:
        # rpc request:
        # if settings.ENABLE_REMOTE_DEBUGGING:
        #    import pydevd; pydevd.settrace()
        fctname = req.POST["f"]
        payload = json.loads(req.POST["a"])
        cid = req.POST["cid"]
        if cid == "0" or cid == 0:
            cid = datetime.datetime.now()
            signals.register_session.send("rpc", cid=cid, req=req)
        UR.CID = cid
        MODULE = sys.modules[__name__]
        if fctname in __EXPORTS:
            r.content = getattr(MODULE, fctname)(payload, req)
            return r
        else:
            assert False, "[PDF] method '%s' not found in __EXPORTS" % fctname
            r.content = UR.prepare_response({}, 1, "[PDF] method '%s' not found in __EXPORTS" % fctname)
            return r
Example #24
0
def measles_mini_summary_csv(request, file_name):
    output = StringIO.StringIO()
    csvio = csv.writer(output)
    header = False
    summary = ReportCHWStatus.measles_mini_summary()
    rows = []
    row = []
    row.append("Facility")
    row.append("No. Vaccinated")
    row.append("No. Eligible")
    row.append("%")
    rows.append(row)
    for info in summary:
        info["percentage"] = round(float(float(info["vaccinated_cases"]) / float(info["eligible_cases"])) * 100, 2)

        row = []
        row.append(u"%(clinic)s" % info)
        row.append(u"%(vaccinated_cases)s" % info)
        row.append(u"%(eligible_cases)s" % info)
        row.append(u"%(percentage)s%%" % info)
        rows.append(row)
    # Write rows on CSV
    for row in rows:
        csvio.writerow([cell for cell in row])
    response = HttpResponse(mimetype="text/csv")
    response["Content-Disposition"] = "attachment; filename=%s" % file_name
    response.write(output.getvalue())
    return response
Example #25
0
def xmlrpc(request):

    if request.POST:

        redirect = request.POST.get("redirect_to")
        if redirect:
            return HttpResponseRedirect(redirect)

        output = dispatcher.run(request.raw_post_data)

        host = request.get_host()
        domain = Site.objects.get_current().domain
        if host != domain:
            for protocol in ("http", "https"):
                output = output.replace("%s://%s/" % (protocol, domain), "%s://%s/" % (protocol, host))

        response = HttpResponse(mimetype="application/xml")
        response.write(strip_spaces_between_tags(output))
        return response

    methods = {}
    for method_name in dispatcher.system_listMethods():
        namespace = method_name.split(".")[0]
        methods.setdefault(namespace, SortedDict())
        methods[namespace][method_name] = get_method_info(dispatcher.funcs[method_name])

    method_lists = []
    for namespace in sorted(methods.keys()):
        method_lists.append((namespace, NAMESPACE_TITLES.get(namespace, namespace), methods[namespace].items()))

    return render_to_response(
        template_name="xmlrpc/xmlrpc.html",
        dictionary={"method_lists": method_lists},
        context_instance=RequestContext(request),
    )
Example #26
0
def add_list_network_device(request, classroom_id, list_id):
    response = HttpResponse()
    url_list = UrlList.objects.get(id=list_id)
    url_list_items = url_list.url_list_items.all()
    classroom_ = Classroom.objects.get(id=classroom_id)
    network_type = classroom_.network_device.network_type
    firewall_rule = classroom_.firewall_rule

    if network_type == "Mikrotik":
        try:
            mk = MikrotikRouter()
            mk.set_networkdevice(classroom_.network_device)
            mk.add_firewall_list(url_list_items, url_list.name)

            """ Add drop firewall rule"""
            mk.delete_firewall_rule("POST-LLISTA-" + classroom_id)

            # If we don't have other choice and we use the less preferable way to block a classroom. Blocking using every single MAC 		#from the PCs of the Classroom
            if classroom_.mac_filter:
                mk.block_classroom_by_mac(classroom_, "POST-LLISTA-" + classroom_id)
            else:
                mk.add_firewall_rule(
                    "POST-LLISTA-" + classroom_id, str(firewall_rule.src_address), str(firewall_rule.src_netmask)
                )

            """ Add accept firewall rule to destination list"""
            mk.delete_firewall_rule("LLISTA-" + classroom_id)
            mk.add_firewall_rule("LLISTA-" + classroom_id, "", "", url_list.name, "accept")

        except Exception, e:
            response.write("ERROR: " + str(e))
Example #27
0
 def test_max_age_expiration(self):
     "Cookie will expire if max_age is provided"
     response = HttpResponse()
     response.set_cookie("max_age", max_age=10)
     max_age_cookie = response.cookies["max_age"]
     self.assertEqual(max_age_cookie["max-age"], 10)
     self.assertEqual(max_age_cookie["expires"], cookie_date(time.time() + 10))
Example #28
0
    def download_files(self, langs, app):
        in_memory = StringIO()

        zip_file = ZipFile(in_memory, "a")
        for l in langs:
            if langs.filter(iso_639=l.iso_639).count() > 1:
                zip_file.writestr(
                    "%s_%s.lproj/Localizable.strings" % (l.iso_639, l.iso_3166), self.generate_file(l, app)
                )
            else:
                zip_file.writestr("%s.lproj/Localizable.strings" % l.iso_639, self.generate_file(l, app))

        # Fix for Linux zip files read in Windows
        for file in zip_file.filelist:
            file.create_system = 0

        zip_file.close()

        response = HttpResponse(mimetype="application/zip")
        response["Content-Disposition"] = "attachment; filename=%s.zip" % (app.__unicode__().replace(" ", "-"))
        response["Content-Length"] = in_memory.tell()

        in_memory.seek(0)
        response.write(in_memory.read())
        return response
Example #29
0
    def test_is_extendable(self):
        """
        Tests that the XFrameOptionsMiddleware method that determines the
        X-Frame-Options header value can be overridden based on something in
        the request or response.
        """

        class OtherXFrameOptionsMiddleware(XFrameOptionsMiddleware):
            # This is just an example for testing purposes...
            def get_xframe_options_value(self, request, response):
                if getattr(request, "sameorigin", False):
                    return "SAMEORIGIN"
                if getattr(response, "sameorigin", False):
                    return "SAMEORIGIN"
                return "DENY"

        with override_settings(X_FRAME_OPTIONS="DENY"):
            response = HttpResponse()
            response.sameorigin = True
            r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), response)
            self.assertEqual(r["X-Frame-Options"], "SAMEORIGIN")

            request = HttpRequest()
            request.sameorigin = True
            r = OtherXFrameOptionsMiddleware().process_response(request, HttpResponse())
            self.assertEqual(r["X-Frame-Options"], "SAMEORIGIN")

        with override_settings(X_FRAME_OPTIONS="SAMEORIGIN"):
            r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())
            self.assertEqual(r["X-Frame-Options"], "DENY")
Example #30
0
def add_opinion(request, discussion, user, title, slug, speech_act):
    parent_story = request.POST.get("parent_story", None)
    parent_class = request.POST.get("parent_class", None)
    if parent_story is None:
        return HttpResponse("Did not get parent story.")
    if parent_class is None:
        return HttpResponse("Did not get parent type.")
    opinion = Opinion()
    opinion.discussion = discussion
    opinion.created_by = user
    opinion.title = title
    opinion.slug = slug
    opinion.speech_act = speech_act
    opinion.parent_story = {"1": Story.objects.get, "2": Opinion.objects.get, "3": StoryRelation.objects.get}[
        parent_class
    ](pk=parent_story)
    try:
        try:
            opinion.full_clean()
        except ValidationError, e:
            message = DEFAULT_FORM_ERROR_MSG
            if e.message_dict[NON_FIELD_ERRORS] and re.search(
                UNIQUENESS_ERROR_PATTERN, e.message_dict[NON_FIELD_ERRORS][0]
            ):
                message = _("Oops! An opinion with this title was already created inside this discussion.")
            resp = HttpResponse(message)
            resp.status_code = 500
            return resp

        opinion.save()
        resp = HttpResponse("%s" % discussion.last_related_update)

        create_notification_task.delay(
            "There is a new opinion in %s discussion: %s" % (discussion.slug, title), opinion, request.user
        )