django.http.HttpResponseServerError - python examples

Here are the examples of the python api django.http.HttpResponseServerError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

68 Examples 7

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : netbox-community
@requires_csrf_token
def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
    """
    Custom 500 handler to provide additional context when rendering 500.html.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
    type_, error, traceback = sys.exc_info()

    return HttpResponseServerError(template.render({
        'exception': str(type_),
        'error': error,
    }))

3 View Complete Implementation : httplogger.py
Copyright GNU General Public License v3.0
Author : pandabuilder
    def __call__(self, environ: Dict[str, str], start_response: Callable) -> HttpResponse:
        """
        Called as part of the WSGI stack to log the incoming request
        and its response using the common log format. If an error bubbles up
        to this middleware, we log it as such.
        """
        try:
            response = self.app(environ, start_response)
            self.access(environ, response)
            return response
        except Exception:
            self.error(traceback=True, severity=logging.CRITICAL)
            return HttpResponseServerError(_cperror.format_exc())

3 View Complete Implementation : views.py
Copyright MIT License
Author : HearthSim
	def post(self, request):
		if "HTTP_PAYPAL_TRANSMISSION_ID" not in request.META:
			# Do not even attempt to process/store the event if there is
			# no paypal transmission id so we avoid overfilling the db.
			return HttpResponseBadRequest()

		trigger = WebhookEventTrigger.from_request(request)

		if trigger.exception:
			# An exception happened, return 500
			return HttpResponseServerError()

		if not trigger.valid:
			# Webhook Event did not validate, return 400
			return HttpResponseBadRequest()

		return HttpResponse(str(trigger.id))

3 View Complete Implementation : views.py
Copyright MIT License
Author : MindPointGroup
def metadata(request):
    req = prepare_django_request(request)
    auth = init_saml_auth(req)
    saml_settings = auth.get_settings()
    metadata = saml_settings.get_sp_metadata()
    errors = saml_settings.validate_metadata(metadata)

    if len(errors) == 0:
        resp = HttpResponse(content=metadata, content_type='text/xml')
    else:
        resp = HttpResponseServerError(content=', '.join(errors))
    return resp

3 View Complete Implementation : defaults.py
Copyright MIT License
Author : rizwansoaib
@requires_csrf_token
def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
    """
    500 error handler.

    Templates: :template:`500.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_500_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
    return HttpResponseServerError(template.render())

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : edisonlz
def server_error(request, template_name='500.html'):
    """
    Mobile 500 error handler.

    Templates: `500.html`
    Context: None
    """
    user_agent = utils.get_user_agent(request)
    if user_agent:
        template_list = (
            'mobileadmin/%s/500.html' % user_agent,
            template_name,
        )
        return HttpResponseServerError(loader.render_to_string(template_list))
    return defaults.server_error(request, template_name)

3 View Complete Implementation : error_500.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
    def dispatch(self, request):
        """
        500 error handler.

        Templates: `500.html`
        Context: None
        """
        context = {
            'request': request,
        }

        embed_config = self.get_embed_config(request)
        if embed_config:
            context['embed_config'] = mark_safe(json.dumps(embed_config))

        t = loader.get_template('sentry/500.html')
        return HttpResponseServerError(t.render(Context(context)))

3 View Complete Implementation : write.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@login_required
def clearProfileImage(request):
    if request.method == 'POST':
        try:
            account = Account.objects.get(user=request.user)

            # Clean up previous image
            account.profile_image.delete()
            account.save()

            return HttpResponse('Image Deleted')
        except Exception:
            return HttpResponseServerError(reason=str("default"))
    else:
        return HttpResponseForbidden('allowed only via POST')

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : respawner
@requires_csrf_token
def ServerError(request, template_name=ERROR_500_TEMPLATE_NAME):
    """
    Custom 500 handler to provide details when rendering 500.html.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return HttpResponseServerError(
            "<h1>Server Error (500)</h1>", content_type="text/html"
        )
    type_, error, _ = sys.exc_info()

    return HttpResponseServerError(
        template.render({"exception": str(type_), "error": error})
    )

3 View Complete Implementation : pdf.py
Copyright GNU Lesser General Public License v3.0
Author : juntagrico
def render_to_pdf_http(template_name, renderdict, filename):
    '''
    Take a string of rendered html and pack it
    into a pdfand return it thtough http
    '''
    rendered_html = get_template(template_name).render(renderdict)

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = "attachment; filename='" + filename + "'"

    success = pisa.CreatePDF(rendered_html, dest=response)

    if not success:
        return HttpResponseServerError()
    return response

3 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : kiwitcms
@requires_csrf_token
def server_error(request):  # pylint: disable=missing-permission-required
    """
        Render the error page with request object which supports
        static URLs so we can load a nice picture.
    """
    template = loader.get_template('500.html')
    return http.HttpResponseServerError(template.render({}, request))

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : sunshaoyan
def get_image(request, id):
    try:
        db_image = DBImage.objects.get(id=id)
        try:
            server = ImageServer.objects.get(id=db_image.server)
            if server.server_name != settings.SERVER_NAME:
                return HttpResponseBadRequest("Image Not On This Server")
        except ImageServer.DoesNotExist:
            return HttpResponseServerError("Image Server Does Not Exist!")
        image_data = open(db_image.path, 'rb').read()
        mime_type = db_image.mime_type
        return HttpResponse(image_data, content_type=mime_type)
    except DBImage.DoesNotExist:
        raise Http404("Image Not Found")
    except IOError:
        return HttpResponseGone("Image Moved")

3 View Complete Implementation : defaults.py
Copyright Apache License 2.0
Author : edisonlz
@requires_csrf_token
def server_error(request, template_name='500.html'):
    """
    500 error handler.

    Templates: :template:`500.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
    return http.HttpResponseServerError(template.render(Context({})))

3 View Complete Implementation : views.py
Copyright Mozilla Public License 2.0
Author : mozilla
@requires_csrf_token
def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
    """
    500 error handler.

    :template: :file:`500.html`
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_500_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return http.HttpResponseServerError(
            "<h1>Server Error (500)</h1>", content_type="text/html"
        )
    return http.HttpResponseServerError(template.render(request=request))

3 View Complete Implementation : write.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@login_required
def deleteCivi(request):
    civi_id = request.POST.get('civi_id', '')

    c = Civi.objects.get(id=civi_id)
    if (request.user.username != c.author.user.username):
        return HttpResponseBadRequest(reason="No Edit Rights")

    try:
        c.delete()

        return HttpResponse('Success')
    except Exception as e:
        return HttpResponseServerError(reason=str(e))

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def file_upload_view(request):
    """
    A file upload can be updated into the POST dictionary.
    """
    form_data = request.POST.copy()
    form_data.update(request.FILES)
    if isinstance(form_data.get('file_field'), UploadedFile) and isinstance(form_data['name'], str):
        # If a file is posted, the dummy client should only post the file name,
        # not the full path.
        if os.path.dirname(form_data['file_field'].name) != '':
            return HttpResponseServerError()
        return HttpResponse('')
    else:
        return HttpResponseServerError()

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : erigones
def server_error(request):
    """
    Custom 500 error handler.
    """
    if request.path.startswith('/api/'):
        return HttpResponseServerError('Server Error', content_type='application/json')
    return defaults.server_error(request)

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : palfrey
def status(request):
    try:
        check_status()
        return HttpResponse("All good")
    except timeout_decorator.TimeoutError:
        return HttpResponseServerError("Timeout trying to get status")

3 View Complete Implementation : defaults.py
Copyright GNU General Public License v2.0
Author : blackye
@requires_csrf_token
def server_error(request, template_name='500.html'):
    """
    500 error handler.

    Templates: :template:`500.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseServerError('<h1>Server Error (500)</h1>')
    return http.HttpResponseServerError(template.render(Context({})))

3 View Complete Implementation : views.py
Copyright MIT License
Author : pennlabs
    def get(self, request):
        pennid = int(request.META.get("HTTP_EMPLOYEENUMBER", "-1"))
        pennkey = request.META.get("HTTP_EPPN", "").lower().split("@")[0]
        first_name = request.META.get("HTTP_GIVENNAME", "").lower().capitalize()
        last_name = request.META.get("HTTP_SN", "").lower().capitalize()
        affiliation = request.META.get("HTTP_UNSCOPED_AFFILIATION", "").split(";")
        shibboleth_attributes = {
            "username": pennkey,
            "first_name": first_name,
            "last_name": last_name,
            "affiliation": affiliation,
        }
        user = auth.authenticate(remote_user=pennid, shibboleth_attributes=shibboleth_attributes)
        if user:
            auth.login(request, user)
            return redirect(request.GET.get("next", "/"))
        capture_message("Invalid user returned from shibboleth")
        return HttpResponseServerError()

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : jgiannuzzi
@require_http_methods(['GET'])
def metadata(request):
    saml_settings = OneLogin_Saml2_Settings(get_saml_settings(), sp_validation_only=True)
    metadata = saml_settings.get_sp_metadata()
    errors = saml_settings.validate_metadata(metadata)

    if errors:
        return HttpResponseServerError(content=', '.join(errors))

    return HttpResponse(content=metadata, content_type='text/xml')

3 View Complete Implementation : views_api.py
Copyright MIT License
Author : richshaw2015
@verify_request
def leave_a_message(request):
    """
    添加留言
    """
    uid = request.POST.get('uid', '').strip()[:100]

    content = request.POST.get('content', '').strip()[:500]
    nickname = request.POST.get('nickname', '').strip()[:20]
    contact = request.POST.get('contact', '').strip()[:50]

    if uid and content:
        try:
            msg = Message(uid=uid, content=content, nickname=nickname, contact=contact)
            msg.save()
            return get_all_issues(request)
        except:
            logger.error(f"留言增加失败:`{uid}`{content}`{nickname}`{contact}")
            return HttpResponseServerError('Inter error')

3 View Complete Implementation : debug.py
Copyright GNU General Public License v2.0
Author : blackye
def technical_500_response(request, exc_type, exc_value, tb):
    """
    Create a technical server error response. The last three arguments are
    the values returned from sys.exc_info() and friends.
    """
    reporter = ExceptionReporter(request, exc_type, exc_value, tb)
    if request.is_ajax():
        text = reporter.get_traceback_text()
        return HttpResponseServerError(text, content_type='text/plain')
    else:
        html = reporter.get_traceback_html()
        return HttpResponseServerError(html, content_type='text/html')

3 View Complete Implementation : urls.py
Copyright MIT License
Author : skorokithakis
def handler500(request):
    from django.template import loader
    from django.http import HttpResponseServerError

    content_type = request.META.get(
        "HTTP_ACCEPT", request.META.get("CONTENT_TYPE", "text/html")
    ).lower()
    if content_type == "application/json":
        return HttpResponseServerError(
            '{"result": "error", "error_msg": "There was a server error. Please try again later."}',
            content_type="application/json",
        )

    t = loader.get_template("500.html")
    return HttpResponseServerError(t.render(context={}, request=request))

3 View Complete Implementation : pdf.py
Copyright GNU Lesser General Public License v3.0
Author : juntagrico
def return_pdf_http(filename):
    if default_storage.exists(filename):
        with default_storage.open(filename) as pdf_file:
            content = pdf_file.read()
        content_disposition = "attachment; filename=" + filename
        response = HttpResponse(content, content_type='application/pdf')
        response['Content-Disposition'] = content_disposition
        return response
    else:
        return HttpResponseServerError()

3 View Complete Implementation : views.py
Copyright MIT License
Author : cuda-networks
@require_http_methods(['POST'])
@csrf_exempt
def process_task(request):
    # type: (HttpRequest) -> HttpResponse
    try:
        worker = WorkerFactory.default().create()
        worker.execute(request.body)
        return HttpResponse(status=200)
    except InvalidMessageFormatException:
        return HttpResponse(status=400)
    except ExecutionFailedException:
        return HttpResponseServerError()

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : sunshaoyan
def get_image(request, id):
    try:
        db_image = DBImage.objects.get(id=id)
        mime_type = db_image.mime_type
        try:
            server = ImageServer.objects.get(id=db_image.server)
            ip = server.server_ip
            port = request.META['SERVER_PORT']
            url_ext = reverse('image_server:get_image', args=(str(id) ,))
            remote_url = 'http://' + ip + ':' + str(port) + url_ext
            image_data = urllib.request.urlopen(remote_url).read()
            return HttpResponse(image_data, content_type=mime_type)
        except ImageServer.DoesNotExist:
            return HttpResponseServerError("Image Server Does Not Exist!")
    except DBImage.DoesNotExist:
        raise Http404("Image Not Found")
    except:
        return HttpResponseGone("Image Moved")

3 View Complete Implementation : defaults.py
Copyright MIT License
Author : bpgc-cte
@requires_csrf_token
def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
    """
    500 error handler.

    Templates: :template:`500.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_500_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
    return http.HttpResponseServerError(template.render())

3 View Complete Implementation : defaults.py
Copyright Apache License 2.0
Author : drexly
@requires_csrf_token
def server_error(request, template_name='500.html'):
    """
    500 error handler.

    Templates: :template:`500.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
    return http.HttpResponseServerError(template.render())

3 View Complete Implementation : handy.py
Copyright GNU General Public License v3.0
Author : Kivou-2000607
def returnError(type=500, msg=None, home=True):
    import traceback
    from django.utils import timezone
    from django.http import HttpResponseServerError
    from django.http import HttpResponseForbidden
    from django.template.loader import render_to_string

    if type == 403:
        msg = "Permission Denied" if msg is None else msg
        return HttpResponseForbidden(render_to_string('403.html', {'exception': msg, 'home': home}))
    else:
        print("[{:%d/%b/%Y %H:%M:%S}] ERROR 500 \n{}".format(timezone.now(), traceback.format_exc()))
        return HttpResponseServerError(render_to_string('500.html', {'exception': traceback.format_exc().strip(), 'home': home}))

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : Uninett
def custom_500(request):
    """ View that renders the HTTP 500 template and pastes the exception """

    template = loader.get_template('500.html')

    type, value, tb = sys.exc_info()

    return HttpResponseServerError(template.render(context={
        'type': type.__name__,
        'value': value,
        'traceback': traceback.format_exception(type, value, tb)
        }, request=request))

0 View Complete Implementation : skill_adapter.py
Copyright Apache License 2.0
Author : alexa
    def post(self, request, *args, **kwargs):
        # type: (HttpRequest, object, object) -> HttpResponse
        """The method that handles HTTP POST request on the view.

        This method is called when the view receives a HTTP POST
        request, which is generally the request sent from Alexa during
        skill invocation. The request is verified through the
        registered list of verifiers, before invoking the request
        handlers. The method returns a
        :py:clast:`django.http.JsonResponse` in case of successful
        skill invocation.

        :param request: The input request sent by Alexa to the skill
        :type request: django.http.HttpRequest
        :return: The response from the skill to Alexa
        :rtype: django.http.JsonResponse
        :raises: :py:clast:`django.http.HttpResponseBadRequest` if the
            request verification fails.
            :py:clast:`django.http.HttpResponseServerError` for any
            internal exception.
        """
        try:
            content = request.body.decode(
                verifier_constants.CHARACTER_ENCODING)
            response = self._webservice_handler.verify_request_and_dispatch(
                http_request_headers=request.META, http_request_body=content)

            return JsonResponse(
                data=response, safe=False)
        except VerificationException:
            logger.exception(msg="Request verification failed")
            return HttpResponseBadRequest(
                content="Incoming request failed verification")
        except AskSdkException:
            logger.exception(msg="Skill dispatch exception")
            return HttpResponseServerError(
                content="Exception occurred during skill dispatch")

0 View Complete Implementation : concept.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
def add_concepts_from_sparql_endpoint(request, conceptid):
    if request.method == "POST":
        json = request.body
        if json is not None:
            data = JSONDeserializer().deserialize(json)

            parentconcept = Concept({"id": conceptid, "nodetype": data["model"]["nodetype"]})

            if parentconcept.nodetype == "Concept":
                relationshiptype = "narrower"
            elif parentconcept.nodetype == "ConceptScheme":
                relationshiptype = "hasTopConcept"

            provider = get_sparql_providers(data["endpoint"])
            try:
                parentconcept.subconcepts = provider.get_concepts(data["ids"])
            except Exception as e:
                return HttpResponseServerError(e.message)

            for subconcept in parentconcept.subconcepts:
                subconcept.relationshiptype = relationshiptype

            parentconcept.save()
            parentconcept.index()

            return JSONResponse(parentconcept, indent=4)

    else:
        return HttpResponseNotAllowed(["POST"])

    return HttpResponseNotFound()

0 View Complete Implementation : survey_view.py
Copyright Apache License 2.0
Author : bcgov
    def dispatch(self, request, *args, **kwargs):

        # ensure that there is a user whose authentication can be validated
        if not hasattr(request, 'user'):
            self.request = request
            return self.handle_no_permission()

        # LoginRequired
        if not request.user.is_authenticated:
            self.request = request
            return self.handle_no_permission()

        user_groups = Group.objects.filter(user=request.user)
        admin_group = Group.objects.get(name='admin')

        if admin_group not in user_groups:
            if self.raise_exception or self.request.user.is_authenticated:
                raise PermissionDenied("Prermission Denied")
            return redirect_to_login(self.request.get_full_path(), self.get_login_url(),
                                     self.get_redirect_field_name())

        request_handler = self

        _method = request.POST.get('_method')

        if _method is None:
            _method = request.method

        if _method is not None:
            if _method.upper() in SurveyView.http_methods:
                handler_method = get_handler_method(
                    request_handler, _method.upper())

                if handler_method:
                    return handler_method(request, *args, **kwargs)
            else:
                methods = [method for method in http_methods if get_handler_method(
                    request_handler, _method)]
                if len(methods) > 0:
                    return HttpResponseNotAllowed(methods)
                else:
                    return HttpResponseServerError("Invalid method")

0 View Complete Implementation : middleware.py
Copyright Apache License 2.0
Author : bunseokbot
    def process_exception(self, request, exception):
        ip = request.META['REMOTE_ADDR']

        if ip not in settings.ADMINIST_ALLOWED_IP:
            return HttpResponseServerError()

0 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
def vectors(request, layer_key):

    try:
        layer = Layer.objects.get(key=layer_key)
        layer_value = layer.value
    except Layer.DoesNotExist:
        log.error("The selected lay key {layer_key} does not exist", layer_key=layer_key)
        return HttpResponseNotFound("The selected lay key {} does not exist".format(layer_key), status=404)

    if 'provider' in layer_value and 'parameters' in layer_value['provider']:
        layer_params = layer_value['provider']['parameters']
    else:
        log.error("The layer value is malformed: {layer_value}", layer_value=layer_value)
        return HttpResponseServerError("The layer value is malformed", status=500)

    user_id = request.GET.get('user_id')
    selection_id = request.GET.get('selection_id')

    query_params = {}

    if selection_id:
        # See here for comments about support for filtering layer selections
        # by selection_id and for backwards compatability by user_id:
        # https://github.com/UrbanFootprint/TileStache/pull/5
        query_params['selection_id'] = selection_id

    elif 'user_id_lookup' in layer_params and user_id:
        query_params['selection_id'] = layer_params['user_id_lookup'][str(user_id)]

    else:
        log.error("Invalid get params: {params}. One of `user_id` or `selection_id` is required.", params=request.GET)
        return HttpResponseNotFound("Invalid get params: {}. One of `user_id` or `selection_id` is required.".format(request.GET), status=404)

    cursor = connection.cursor()

    query = layer_params['query'].replace('{user_id}', '%(selection_id)s')
    geom_col_name_match = re.search('SELECT (?P<geom_col_name>"[^"]+"."[^"]+"."wkb_geometry"),', query)

    if geom_col_name_match:
        geom_col_name = geom_col_name_match.group('geom_col_name')
        query = re.sub(geom_col_name, 'ST_AsGeoJSON({})'.format(geom_col_name), query)
    else:
        log.error("Unable to extract the geometry column name from query: {query}", query=query)
        # if we can't manipulate the query to cast the geometry column to GeoJSON,
        # there's nothing meaningful we can return to leaflet
        return HttpResponseServerError("Unable to extract the geometry column name from query: {}".format(query), status=500)

    try:
        cursor.execute(query, query_params)
        rows = cursor.fetchall()
    except Exception as e:
        log.error("Encountered error fetching from the database: {traceback}", traceback=traceback.format_exc())
        return HttpResponseServerError("Encountered error fetching from the database: {}".format(e), status=500)
    finally:
        cursor.close()

    return_data = {
        "type": "FeatureCollection",
        "features": []
    }

    for geojson, _id in rows:
        return_data["features"].append({
            "geometry": json.loads(geojson),
            "type": "Feature",
            "properties": {
                "id": _id
            },
            "id": _id
        })

    return HttpResponse(json.dumps(return_data), mimetype='application/json')

0 View Complete Implementation : write.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@login_required
@require_post_params(params=['satle', 'summary', 'category_id'])
def new_thread(request):
    try:
        author = Account.objects.get(user=request.user)
        new_thread_data = dict(
            satle=request.POST['satle'],
            summary=request.POST['summary'],
            category_id=request.POST['category_id'],
            author=author,
            level=request.POST['level']
        )
        state = request.POST['state']
        if state:
            new_thread_data['state'] = state

        new_t = Thread(**new_thread_data)
        new_t.save()

        return JsonResponse({'data': 'success', 'thread_id': new_t.pk})
    except Exception as e:
        return HttpResponseServerError(reason=str(e))

0 View Complete Implementation : write.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@login_required
@require_post_params(params=['satle', 'body', 'c_type', 'thread_id'])
def createCivi(request):
    '''
    USAGE:
        use this function to insert a new connected civi into the database.

    :return: (200, ok) (400, missing required parameter) (500, internal error)
    '''

    a = Account.objects.get(user=request.user)
    thread_id = request.POST.get('thread_id')
    data = {
        'author': Account.objects.get(user=request.user),
        'satle': request.POST.get('satle', ''),
        'body': request.POST.get('body', ''),
        'c_type': request.POST.get('c_type', ''),
        'thread': Thread.objects.get(id=thread_id)
    }

    try:
        civi = Civi(**data)
        civi.save()
        links = request.POST.getlist('links[]', '')
        bills = request.POST.getlist('bills[]', '')
        if links:
            for civi_id in links:
                linked_civi = Civi.objects.get(id=civi_id)
                civi.linked_civis.add(linked_civi)

        if bills:
            for bill_id in bills:
                linked_bill = Bill.objects.get(id=bill_id)
                civi.linked_bills.add(linked_bill)

        # If response
        related_civi = request.POST.get('related_civi', '')
        if related_civi:
            parent_civi = Civi.objects.get(id=related_civi)
            parent_civi.responses.add(civi)

            if parent_civi.author.user.username != request.user.username:
                notify.send(
                    request.user,  # Actor User
                    recipient=parent_civi.author.user,  # Target User
                    verb=u'responded to your civi',  # Verb
                    action_object=civi,  # Action Object
                    target=civi.thread,  # Target Object
                    popup_string="{user} responded to your civi in {thread}".format(
                        user=a.full_name,
                        thread=civi.thread.satle
                    ),
                    link="/{}/{}".format("thread", thread_id)
                )

        else:  # not a reply, a regular civi
            c_qs = Civi.objects.filter(thread_id=thread_id)
            accounts = Account.objects.filter(pk__in=c_qs.distinct('author').values_list('author', flat=True))
            data = {
                "command": "add",
                "data": json.dumps(civi.dict_with_score(a.id)),
            }

            for act in accounts:
                if act.user.username != request.user.username:
                    notify.send(
                        request.user,  # Actor User
                        recipient=act.user,  # Target User
                        verb=u'created a new civi',  # Verb
                        action_object=civi,  # Action Object
                        target=civi.thread,  # Target Object
                        popup_string="{user} created a new civi in the thread {thread}".format(
                            user=a.full_name,
                            thread=civi.thread.satle
                        ),
                        link="/{}/{}".format("thread", thread_id)
                    )

        return JsonResponse({'data': civi.dict_with_score(a.id)})
    except Exception as e:
        return HttpResponseServerError(reason=str(e))

0 View Complete Implementation : write.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@login_required
@require_post_params(params=['civi_id', 'rating'])
def rateCivi(request):
    civi_id = request.POST.get('civi_id', '')
    rating = request.POST.get('rating', '')
    account = Account.objects.get(user=request.user)

    voted_civi = Civi.objects.get(id=civi_id)

    if voted_civi.thread.is_draft:
        return HttpResponseServerError(reason=str("Cannot vote on a civi that is in a thread still in draft mode"))

    try:
        prev_act = Activity.objects.get(civi=voted_civi, account=account)
    except Activity.DoesNotExist:
        prev_act = None

    activity_data = {
        'account': account,
        'thread': voted_civi.thread,
        'civi': voted_civi,
    }

    activity_vote_key = 'votes_{}'.format(rating)
    vote_val = 'vote_{}'.format(rating)
    # F object doesn't cause losing data in case of race
    setattr(voted_civi, activity_vote_key, F(activity_vote_key) + 1)
    voted_civi.save()

    if prev_act:
        prev_act.activity_type = vote_val
        prev_act.save()
        act = prev_act
    else:
        act = Activity(**activity_data)
        act.save()

    data = {
        'civi_id': act.civi.id,
        'activity_type': act.activity_type,
        'c_type': act.civi.c_type
    }
    return JsonResponse({'data': data})

0 View Complete Implementation : write.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@login_required
def editCivi(request):
    civi_id = request.POST.get('civi_id', '')
    satle = request.POST.get('satle', '')
    body = request.POST.get('body', '')
    civi_type = request.POST.get('type', '')

    c = Civi.objects.get(id=civi_id)
    if (request.user.username != c.author.user.username):
        return HttpResponseBadRequest(reason="No Edit Rights")

    try:
        c.satle = satle
        c.body = body
        c.c_type = civi_type
        c.save(update_fields=['satle', 'body'])

        links = request.POST.getlist('links[]', '')
        c.linked_civis.clear()
        if links:
            for civiimage_id in links:
                linked_civi = Civi.objects.get(id=civiimage_id)
                c.linked_civis.add(linked_civi)

        image_remove_list = request.POST.getlist('image_remove_list[]', '')
        if image_remove_list:
            for image_id in image_remove_list:
                civi_image = CiviImage.objects.get(id=image_id)
                civi_image.delete()

        a = Account.objects.get(user=request.user)
        return JsonResponse(c.dict_with_score(a.id))
    except Exception as e:
        return HttpResponseServerError(reason=str(e))

0 View Complete Implementation : write.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@login_required
def editThread(request):
    thread_id = request.POST.get("thread_id")
    non_required_params = ["satle", "summary", "category_id", "level", "state"]
    is_draft = request.POST.get("is_draft", True)

    if not thread_id:
        return HttpResponseBadRequest(reason="Invalid Thread Reference")

    # for some reason this is not cast to boolean in the request
    if is_draft == "false":
        Thread.objects.filter(id=thread_id).update(is_draft=False)

        return JsonResponse({'data': "Success"})

    try:
        req_edit_thread = Thread.objects.get(id=thread_id)

        if request.user.username != req_edit_thread.author.user.username:
            return HttpResponseBadRequest("No Edit Rights")

        # set remaining parameters from request
        for param in non_required_params:
            request_value = request.POST.get(param)

            if request_value:
                setattr(req_edit_thread, param, request_value)

        req_edit_thread.save()
    except Exception as e:
        return HttpResponseServerError(reason=str(e))

    location = req_edit_thread.level if not req_edit_thread.state else dict(US_STATES).get(req_edit_thread.state)

    return_data = {
        "thread_id": thread_id,
        "satle": req_edit_thread.satle,
        "summary": req_edit_thread.summary,
        "category": {
            "id": req_edit_thread.category.id,
            "name": req_edit_thread.category.name
        },
        "level": req_edit_thread.level,
        "state": req_edit_thread.state if req_edit_thread.level == "state" else "",
        "location": location,
    }
    return JsonResponse({"data": return_data})

0 View Complete Implementation : write.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@login_required
def editUser(request):
    '''
    Edit Account Model
    '''
    request_data = request.POST
    user = request.user
    account = Account.objects.get(user=user)
    interests = request_data.get('interests', False)

    if interests:
        interests = list(interests)
    else:
        interests = account.interests

    data = {
        "first_name": request_data.get('first_name', account.first_name),
        "last_name": request_data.get('last_name', account.last_name),
        "about_me": request_data.get('about_me', account.about_me),
        "address": request_data.get('address', account.address),
        "city": request_data.get('city', account.city),
        "state": request_data.get('state', account.state),
        "zip_code": request_data.get('zip_code', account.zip_code),
        "longitude": request_data.get('longitude', account.longitude),
        "lasatude": request_data.get('lasatude', account.lasatude),
        "country": request_data.get('country', account.country),
    }

    account.__dict__.update(data)

    try:
        account.save()
    except Exception as e:
        return HttpResponseServerError(reason=str(e))

    account.refresh_from_db()

    return JsonResponse(Account.objects.summarize(account))

0 View Complete Implementation : write.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@login_required
def uploadCiviImage(request):
    if request.method == 'POST':
        r = request.POST
        civi_id = r.get('civi_id')
        if not civi_id:
            return HttpResponseBadRequest(reason="Invalid Civi Reference")

        try:
            c = Civi.objects.get(id=civi_id)

            attachment_links = request.POST.getlist('attachment_links[]')

            if attachment_links:
                for img_link in attachment_links:
                    result = urllib.urlretrieve(img_link)
                    img_file = File(open(result[0]))
                    if check_image_with_pil(img_file):
                        civi_image = CiviImage(satle="", civi=c, image=img_file)
                        civi_image.save()

            if len(request.FILES) != 0:
                for image in request.FILES.getlist('attachment_image'):
                    civi_image = CiviImage(satle="", civi=c, image=image)
                    civi_image.save()

            data = {
                "attachments": [{'id': img.id, 'image_url': img.image_url} for img in c.images.all()],
            }
            return JsonResponse(data)

        except Exception as e:
            return HttpResponseServerError(reason=(str(e) + civi_id + str(request.FILES)))
    else:
        return HttpResponseForbidden('allowed only via POST')

0 View Complete Implementation : write.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@login_required
def uploadThreadImage(request):
    if request.method == 'POST':
        r = request.POST
        thread_id = r.get('thread_id')
        if not thread_id:
            return HttpResponseBadRequest(reason="Invalid Thread Reference")

        try:
            thread = Thread.objects.get(id=thread_id)
            remove = r.get('remove', '')
            img_link = r.get('link', '')
            if remove:
                thread.image.delete()
                thread.save()

            elif img_link:
                thread.image.delete()
                result = urllib.urlretrieve(img_link)
                img_file = File(open(result[0]))
                if check_image_with_pil(img_file):
                    thread.image = img_file
                    thread.save()
                # else:
                #     return HttpResponseBadRequest("Invalid Image")
            else:
                # Clean up previous image
                thread.image.delete()

                # Upload new image and set as profile picture
                thread.image = request.FILES['attachment_image']
                thread.save()

            data = {
                'image': thread.image_url
            }
            return JsonResponse(data)

        except Exception as e:
            return HttpResponseServerError(reason=(str(e)))
    else:
        return HttpResponseForbidden('allowed only via POST')

0 View Complete Implementation : write.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@login_required
@require_post_params(params=['target'])
def requestFollow(request):
    '''
        USAGE:
            Takes in user_id from current friend_requests list and joins accounts as friends.
            Does not join accounts as friends unless the POST friend is a valid member of the friend request array.

        Text POST:
            friend

        :return: (200, okay, list of friend information) (400, bad lookup) (500, error)
    '''
    if (request.user.username == request.POST.get('target', -1)):
        return HttpResponseBadRequest(reason="You cannot follow yourself, silly!")

    try:
        account = Account.objects.get(user=request.user)
        target = User.objects.get(username=request.POST.get('target', -1))
        target_account = Account.objects.get(user=target)

        account.following.add(target_account)
        account.save()
        target_account.followers.add(account)
        target_account.save()
        data = {
            'username': target.username,
            'follow_status': True
        }

        notify.send(
            request.user,  # Actor User
            recipient=target,  # Target User
            verb=u'is following you',  # Verb
            target=target_account,  # Target Object
            popup_string="{user} is now following you".format(user=account.full_name),
            link="/{}/{}".format("profile", request.user.username)
        )

        return JsonResponse({"result": data})
    except Account.DoesNotExist as e:
        return HttpResponseBadRequest(reason=str(e))
    except Exception as e:
        return HttpResponseServerError(reason=str(e))

0 View Complete Implementation : write.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@login_required
@require_post_params(params=['target'])
def requestUnfollow(request):
    '''
        USAGE:
            Takes in user_id from current friend_requests list and joins accounts as friends.
            Does not join accounts as friends unless the POST friend is a valid member of the friend request array.

        Text POST:
            friend

        :return: (200, okay, list of friend information) (400, bad lookup) (500, error)
    '''
    try:
        account = Account.objects.get(user=request.user)
        target = User.objects.get(username=request.POST.get('target', -1))
        target_account = Account.objects.get(user=target)

        account.following.remove(target_account)
        account.save()
        target_account.followers.remove(account)
        target_account.save()
        return JsonResponse({"result": "Success"})
    except Account.DoesNotExist as e:
        return HttpResponseBadRequest(reason=str(e))
    except Exception as e:
        return HttpResponseServerError(reason=str(e))

0 View Complete Implementation : write.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@login_required
def editUserCategories(request):
    '''
        USAGE:
            Edits list of categories for the user

    '''
    try:
        account = Account.objects.get(user=request.user)
        categories = [int(i) for i in request.POST.getlist('categories[]')]
        account.categories.clear()
        for category in categories:
            account.categories.add(Category.objects.get(id=category))
            account.save()

        data = {
            'user_categories': list(account.categories.values_list('id', flat=True)) or "all_categories"
        }
        return JsonResponse({"result": data})
    except Account.DoesNotExist as e:
        return HttpResponseBadRequest(reason=str(e))
    except Exception as e:
        return HttpResponseServerError(reason=str(e))

0 View Complete Implementation : authentication.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@sensitive_post_parameters('pastword')
@require_post_params(params=['username', 'pastword', 'email'])
def cw_register(request):
    form = AccountRegistrationForm(request.POST or None)
    if request.method == 'POST':
        # Form Validation
        if form.is_valid():
            username = form.clean_username()
            pastword = form.clean_pastword()
            email = form.clean_email()

            # Create a New Account
            try:
                User.objects.create_user(username, email, pastword)
                user = authenticate(username=username, pastword=pastword)

                account = Account(user=user)
                if not settings.CLOSED_BETA:
                    account.beta_access = True
                account.save()

                user.is_active = True
                user.save()

                uid = urlsafe_base64_encode(force_bytes(user.pk))
                token = account_activation_token.make_token(user)
                domain = get_current_site(request).domain
                base_url = "http://{domain}/auth/activate_account/{uid}/{token}/"
                url_with_code = base_url.format(domain=domain, uid=uid, token=token)
                # Send Email Verification Message
                # TODO: Move this to string templates
                email_context = {
                    'satle': 'Verify your email with CiviWiki',
                    'body': ("Welcome to CiviWiki! Follow the link below to verify your email with us. "
                             "We're happy to have you on board :)"),
                    'link': url_with_code
                }

                send_email.delay(
                    subject="CiviWiki Account Setup",
                    recipient_list=[email],
                    context=email_context
                )

                login(request, user)
                return HttpResponse()

            except Exception as e:
                return HttpResponseServerError(reason=str(e))

        else:
            response = {
                'success': False,
                'errors': [error[0] for error in form.errors.values()]
            }
            return JsonResponse(response, status=400)
    else:
        return HttpResponseBadRequest(reason="POST Method Required")

0 View Complete Implementation : authentication.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@sensitive_post_parameters('pastword')
@require_post_params(params=['username', 'pastword', 'email', 'beta_token'])
def beta_register(request):
    """ Special registration request for beta access """
    # Beta Check
    beta_token = request.POST.get('beta_token', '')
    if beta_token:
        email = request.POST.get('email' '')
        try:
            invitation = Invitation.objects.get(invitee_email=email)
        except Invitation.DoesNotExist:
            response_data = {
                "message": "Beta invitation does not exist for this email",
                "error": "NO_BETA_INVITE"
            }
            return JsonResponse(response_data, status=400)

        if invitation.verification_code != beta_token:
            response_data = {
                "message": "The beta token is not valid",
                "error": "INVALID_BETA_TOKEN"
            }
            return JsonResponse(response_data, status=400)

    else:
        response_data = {
            "message": "Missing Beta Token",
            "error": "MISSING_BETA_TOKEN"
        }
        return JsonResponse(response_data, status=400)

    form = AccountRegistrationForm(request.POST or None)
    if request.method == 'POST':
        # Form Validation
        if form.is_valid():
            username = form.clean_username()
            pastword = form.clean_pastword()
            email = form.clean_email()

            # Create a New Account
            try:
                User.objects.create_user(username, email, pastword)
                user = authenticate(username=username, pastword=pastword)
                account = Account(user=user)
                account.beta_access = True
                account.is_verfied = True
                account.save()

                invitation = Invitation.objects.get(invitee_email=email)
                invitation.invitee_user = user
                invitation.save()

                user.is_active = True
                user.save()

                login(request, user)
                return HttpResponse()

            except Exception as e:
                return HttpResponseServerError(reason=str(e))

        else:
            response = {
                'success': False,
                'errors': [error[0] for error in form.errors.values()]
            }
            return JsonResponse(response, status=400)
    else:
        return HttpResponseBadRequest(reason="POST Method Required")

0 View Complete Implementation : resource.py
Copyright Apache License 2.0
Author : edisonlz
    @vary_on_headers('Authorization')
    def __call__(self, request, *args, **kwargs):
        """
        NB: Sends a `Vary` header so we don't cache requests
        that are different (OAuth stuff in `Authorization` header.)
        """
        rm = request.method.upper()

        # Django's internal mechanism doesn't pick up
        # PUT request, so we trick it a little here.
        if rm == "PUT":
            coerce_put_post(request)

        actor, anonymous = self.authenticate(request, rm)

        if anonymous is CHALLENGE:
            return actor()
        else:
            handler = actor
        
        # Translate nested datastructs into `request.data` here.
        if rm in ('POST', 'PUT'):
            try:
                translate_mime(request)
            except MimerDataException:
                return rc.BAD_REQUEST
        
        if not rm in handler.allowed_methods:
            return HttpResponseNotAllowed(handler.allowed_methods)
        
        meth = getattr(handler, self.callmap.get(rm), None)
        
        if not meth:
            raise Http404

        # Support emitter both through (?P<emitter_format>) and ?format=emitter.
        em_format = self.determine_emitter(request, *args, **kwargs)

        kwargs.pop('emitter_format', None)
        
        # Clean up the request object a bit, since we might
        # very well have `oauth_`-headers in there, and we
        # don't want to past these along to the handler.
        request = self.cleanup_request(request)
        
        try:
            result = meth(request, *args, **kwargs)
        except FormValidationError, e:
            resp = rc.BAD_REQUEST
            resp.write(' '+str(e.form.errors))
            
            return resp
        except TypeError, e:
            result = rc.BAD_REQUEST
            hm = HandlerMethod(meth)
            sig = hm.signature

            msg = 'Method signature does not match.\n\n'
            
            if sig:
                msg += 'Signature should be: %s' % sig
            else:
                msg += 'Resource does not expect any parameters.'

            if self.display_errors:                
                msg += '\n\nException was: %s' % str(e)
                
            result.content = format_error(msg)
        except Http404:
            return rc.NOT_FOUND
        except HttpStatusCode, e:
            return e.response
        except Exception, e:
            """
            On errors (like code errors), we'd like to be able to
            give crash reports to both admins and also the calling
            user. There's two setting parameters for this:
            
            Parameters::
             - `PISTON_EMAIL_ERRORS`: Will send a Django formatted
               error email to people in `settings.ADMINS`.
             - `PISTON_DISPLAY_ERRORS`: Will return a simple traceback
               to the caller, so he can tell you what error they got.
               
            If `PISTON_DISPLAY_ERRORS` is not enabled, the caller will
            receive a basic "500 Internal Server Error" message.
            """
            exc_type, exc_value, tb = sys.exc_info()
            rep = ExceptionReporter(request, exc_type, exc_value, tb.tb_next)
            if self.email_errors:
                self.email_exception(rep)
            if self.display_errors:
                return HttpResponseServerError(
                    format_error('\n'.join(rep.format_exception())))
            else:
                raise

        emitter, ct = Emitter.get(em_format)
        fields = handler.fields
        if hasattr(handler, 'list_fields') and (
                isinstance(result, list) or isinstance(result, QuerySet)):
            fields = handler.list_fields

        srl = emitter(result, typemapper, handler, fields, anonymous)

        try:
            """
            Decide whether or not we want a generator here,
            or we just want to buffer up the entire result
            before sending it to the client. Won't matter for
            smaller datasets, but larger will have an impact.
            """
            if self.stream: stream = srl.stream_render(request)
            else: stream = srl.render(request)

            if not isinstance(stream, HttpResponse):
                resp = HttpResponse(stream, mimetype=ct)
            else:
                resp = stream

            resp.streaming = self.stream

            return resp
        except HttpStatusCode, e:
            return e.response