Python django.http 模块,HttpResponseNotFound() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.http.HttpResponseNotFound()

项目:django-hdfs    作者:thanos    | 项目源码 | 文件源码
def hdfs_usage(request, root=None):
    host = settings.HDFS_STROAGE['hosts']
    if not root:
        root = settings.HDFS_STROAGE['HDFS_ROOT']

    log.info('http://%s/%s', host, root)
    client = hdfs.InsecureClient('http://%s' % host)
    tree = []
    try:
        for appcode in client.list(root):
            url = 'http://%s/webhdfs/v1%s/%s?op=GETCONTENTSUMMARY' % (host, root, appcode)
            data = requests.get(url).json()
            if data['ContentSummary']['directoryCount']:
                tree.append({
                    'name': appcode,
                    'value': round(data['ContentSummary']['length'] / 1000000.0, 2)
                })
    except HdfsError, e:
        log.warn("hdfs_usage error: %s", e)
        return HttpResponseNotFound(dumps(tree), content_type='application/json')
    return HttpResponse(dumps(tree), content_type='application/json')
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def cancel_order(request):
    oid = request.POST.get('id', False)
    if not oid:
        return HttpResponseNotFound(NOTFOUNDMESSAGE)
    try:
        obj = Order.objects.get(pk=int(oid), user=request.user)
        if obj.is_accept:
            return JsonResponse({
                'status': 0
            })
        else:
            obj.delete()
            return JsonResponse({
                'status': 1
            })
    except:
        return JsonResponse({
            'status': 0
        })
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def accept_or_deny(request):
    if request.user.usertype:
        return HttpResponseForbidden()
    else:
        op = request.GET.get('op')
        try:
            opk = int(request.GET.get('opk'))
            b = request.user.business
            o = Order.objects.get(pk=opk, food__business=b)
        except:
            return HttpResponseNotFound(NOTFOUNDMESSAGE)
        if op == 'accept':
            o.is_accept = True
            o.save()
        elif op == 'deny':
            o.delete()

        return HttpResponseRedirect(reverse('businessucenterindex'))
项目:mercure    作者:synhack    | 项目源码 | 文件源码
def set_info(request, tracker_id):
    """Set browser infos.

    :param request:
    :param tracker_id:
    :return:
    """
    if not request.POST.get('infos'):
        return HttpResponseBadRequest()

    tracker = TrackerInfos.objects.filter(
        target_tracker_id=tracker_id, raw=None).order_by('created_at').last()

    if not tracker:
        return HttpResponseNotFound()

    tracker.raw = request.POST['infos']
    tracker.save()

    return HttpResponse('')
项目:cjworkbench    作者:CJWorkbench    | 项目源码 | 文件源码
def wfmodule_input(request, pk, format=None):
    if request.method == 'GET':
        try:
            wf_module = WfModule.objects.get(pk=pk)
        except WfModule.DoesNotExist:
            return HttpResponseNotFound()

        if not wf_module.user_authorized_read(request.user):
            return HttpResponseForbidden()

        # return empty table if this is the first module in the stack
        prev_modules = WfModule.objects.filter(workflow=wf_module.workflow, order__lt=wf_module.order)
        if not prev_modules:
            return HttpResponse(make_render_json(pd.DataFrame()), content_type="application/json")
        else:
            return table_result(request, prev_modules.last())

# Public access to wfmodule output. Basically just /render with different auth and output format
# NOTE: does not support startrow/endrow at the moment
项目:cjworkbench    作者:CJWorkbench    | 项目源码 | 文件源码
def wfmodule_public_output(request, pk, type, format=None):
    try:
        wf_module = WfModule.objects.get(pk=pk)
    except WfModule.DoesNotExist:
        return HttpResponseNotFound()

    if not wf_module.user_authorized_read(request.user):
        return HttpResponseNotFound()

    table = execute_wfmodule(wf_module)
    if type=='json':
        d = table.to_json(orient='records')
        return HttpResponse(d, content_type="application/json")
    elif type=='csv':
        d = table.to_csv(index=False)
        return HttpResponse(d, content_type="text/csv")
    else:
        return HttpResponseNotFound()


# Get list of data versions, or set current data version
项目:cjworkbench    作者:CJWorkbench    | 项目源码 | 文件源码
def wfmodule_dataversion(request, pk, format=None):
    try:
        wf_module = WfModule.objects.get(pk=pk)
    except WfModule.DoesNotExist:
        return HttpResponseNotFound()

    if request.method == 'GET':
        if not wf_module.user_authorized_read(request.user):
            return HttpResponseNotFound()

        versions = wf_module.list_fetched_data_versions()
        current_version = wf_module.get_fetched_data_version()
        response = {'versions': versions, 'selected': current_version}
        return Response(response)

    elif request.method == 'PATCH':
        if not wf_module.user_authorized_write(request.user):
            return HttpResponseForbidden()

        ChangeDataVersionCommand.create(wf_module, datetime.datetime.strptime(request.data['selected'], "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=pytz.UTC))
        return Response(status=status.HTTP_204_NO_CONTENT)
项目:cjworkbench    作者:CJWorkbench    | 项目源码 | 文件源码
def parameterval_png(request, pk):
    try:
        param = ParameterVal.objects.get(pk=pk)
    except ParameterVal.DoesNotExist:
        return HttpResponseNotFound()

    if not param.wf_module.public_authorized():
        return HttpResponseForbidden()

    # is this actually in image? totes hardcoded for now
    if param.parameter_spec.id_name != 'chart':
        return HttpResponseBadRequest()

    # decode the base64 payload of the data URI into a png
    image_data = param.value.partition('base64,')[2]
    binary = base64.b64decode(image_data)
    return HttpResponse(binary, content_type='image/png')
项目:no-design-slack-clone    作者:metsavaht    | 项目源码 | 文件源码
def page_not_found(request, template_name='404.html'):
    context = {
        'request_path': request.path,
        'error': {
            'title': _('Page not found'),
            'message': _("We tried but couldn't find this page, sorry."),
        },
    }

    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None

    except TemplateDoesNotExist:
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested URL {{ request_path }} was not found on this server.</p>')
        body = template.render(Context(context))
        content_type = 'text/html'

    return HttpResponseNotFound(body, content_type=content_type)
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def get_media_file_response(metadata):
    if metadata.data_file:
        file_path = metadata.data_file.name
        filename, extension = os.path.splitext(file_path.split('/')[-1])
        extension = extension.strip('.')
        dfs = get_storage_class()()

        if dfs.exists(file_path):
            response = response_with_mimetype_and_name(
                metadata.data_file_type,
                filename, extension=extension, show_date=False,
                file_path=file_path, full_mime=True)

            return response
        else:
            return HttpResponseNotFound()
    else:
        return HttpResponseRedirect(metadata.data_value)
项目:django-project-template    作者:thorgate    | 项目源码 | 文件源码
def page_not_found(request, template_name='404.html'):
    context = {
        'request_path': request.path,
        'error': {
            'title': _('Page not found'),
            'message': _("We tried but couldn't find this page, sorry."),
        },
    }

    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None

    except TemplateDoesNotExist:
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested URL {{ request_path }} was not found on this server.</p>')
        body = template.render(Context(context))
        content_type = 'text/html'

    return HttpResponseNotFound(body, content_type=content_type)
项目:bridge-adaptivity    作者:harvard-vpal    | 项目源码 | 文件源码
def sources(request):
    """
    Content Source backend endpoint.

    Uses OpenEdx Course API v.1.0
    :param request:
    :param course_id:
    :return: (JSON) blocks
    """
    course_id = request.POST.get('course_id')
    if not course_id:
        return HttpResponseBadRequest(reason={"error": "`course_id` is a mandatory parameter."})

    log.debug('course_ID{}'.format(course_id))

    try:
        sources_list = get_available_blocks(course_id)
    except ObjectDoesNotExist as exc:
        return HttpResponseBadRequest(reason={"error": exc.message})
    except HttpClientError as exc:
        return HttpResponseNotFound(reason={"error": exc.message})

    return JsonResponse(data=sources_list, safe=False)
项目:chores    作者:liberza    | 项目源码 | 文件源码
def give_away_weekly(request, **kwargs):
    if request.method != 'POST':
        return HttpResponseNotFound()
    scheduledChore = ScheduledChore.objects.get(pk=kwargs['sc_id'])
    if request.user != scheduledChore.person:
        return HttpResponseNotFound()
    people = Person.objects.all().order_by('-weekly_modifier')
    oldPerson = scheduledChore.person
    # make sure we don't give it back to the same person...
    if people[0] == oldPerson:
        newPerson = people[1]
    else:
        newPerson = people[0]
    oldPerson.weekly_modifier += 1
    oldPerson.save()
    scheduledChore.person = newPerson
    scheduledChore.save()
    return HttpResponseRedirect('/')
项目:chores    作者:liberza    | 项目源码 | 文件源码
def give_away_daily(request, **kwargs):
    if request.method != 'POST':
        return HttpResponseNotFound()
    scheduledChore = ScheduledChore.objects.get(pk=kwargs['sc_id'])
    if request.user != scheduledChore.person:
        return HttpResponseNotFound()
    people = Person.objects.all().order_by('-daily_modifier')
    oldPerson = scheduledChore.person
    # make sure we don't give it back to the same person...
    if people[0] == oldPerson:
        newPerson = people[1]
    else:
        newPerson = people[0]
    oldPerson.weekly_modifier += 1
    oldPerson.save()
    scheduledChore.person = newPerson
    scheduledChore.save()
    return HttpResponseRedirect('/')
项目:djangocms-onepage-example    作者:thorgate    | 项目源码 | 文件源码
def page_not_found(request, template_name='404.html'):
    context = {
        'request_path': request.path,
        'error': {
            'title': _('Page not found'),
            'message': _("We tried but couldn't find this page, sorry."),
        },
    }

    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None

    except TemplateDoesNotExist:
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested URL {{ request_path }} was not found on this server.</p>')
        body = template.render(Context(context))
        content_type = 'text/html'

    return HttpResponseNotFound(body, content_type=content_type)
项目:Distributed-Multi-User-Scrapy-System-with-a-Web-UI    作者:aaldaber    | 项目源码 | 文件源码
def delete_project(request, projectname):
    try:
        project = Project.objects.get(user=request.user, project_name=projectname)
    except Project.DoesNotExist:
        return HttpResponseNotFound('Nothing is here.')

    if request.method == 'GET':
        form = DeleteProject()
        return render(request, 'deleteproject.html', {'username': request.user.username, 'form': form, 'projectname': projectname})
    if request.method == 'POST':
        if 'cancel' in request.POST:
            return HttpResponseRedirect(reverse("mainpage"))
        elif 'submit' in request.POST:
            project.delete()
            return HttpResponseRedirect(reverse("mainpage"))
        else:
            return HttpResponseNotFound('Nothing is here.')
项目:Distributed-Multi-User-Scrapy-System-with-a-Web-UI    作者:aaldaber    | 项目源码 | 文件源码
def itemslist(request, projectname):
    try:
        project = Project.objects.get(user=request.user, project_name=projectname)
    except Project.DoesNotExist:
        return HttpResponseNotFound('Nothing is here.')

    itemtracker = 0

    items = Item.objects.filter(project=project)
    itemdata = []
    for item in items:
        itemdata.append([])
        itemdata[itemtracker].append(item.item_name)
        fields = Field.objects.filter(item=item)
        if fields:
            itemdata[itemtracker].append([])
        for field in fields:
            itemdata[itemtracker][1].append(field.field_name)
        itemtracker += 1
    return render(request, 'itemslist.html',
                  {'username': request.user.username, 'project': project.project_name, 'items': itemdata})
项目:Distributed-Multi-User-Scrapy-System-with-a-Web-UI    作者:aaldaber    | 项目源码 | 文件源码
def deleteitem(request, projectname, itemname):
    try:
        project = Project.objects.get(user=request.user, project_name=projectname)
    except Project.DoesNotExist:
        return HttpResponseNotFound('Nothing is here.')

    try:
        item = Item.objects.get(project=project, item_name=itemname)
    except Item.DoesNotExist:
        return HttpResponseNotFound('Nothing is here.')

    if request.method == 'GET':
        # using the form that was used for deleting the project
        form = DeleteProject()
        return render(request, 'deleteitem.html',
                      {'username': request.user.username, 'form': form, 'projectname': projectname, 'itemname': itemname})
    elif request.method == 'POST':
        if 'cancel' in request.POST:
            return HttpResponseRedirect(reverse("listitems", args=(projectname,)))
        elif 'submit' in request.POST:
            item.delete()
            return HttpResponseRedirect(reverse("listitems", args=(projectname,)))
项目:Distributed-Multi-User-Scrapy-System-with-a-Web-UI    作者:aaldaber    | 项目源码 | 文件源码
def pipelinelist(request, projectname):
    try:
        project = Project.objects.get(user=request.user, project_name=projectname)
    except Project.DoesNotExist:
        return HttpResponseNotFound('Nothing is here.')

    itemtracker = 0

    pipelines = Pipeline.objects.filter(project=project)
    pipelinedata = []
    for pipeline in pipelines:
        pipelinedata.append([])
        pipelinedata[itemtracker].append(pipeline.pipeline_name)
        pipelinedata[itemtracker].append(pipeline.pipeline_order)
        itemtracker += 1
    return render(request, 'pipelinelist.html', {'username': request.user.username, 'project': project.project_name, 'items': pipelinedata})
项目:Distributed-Multi-User-Scrapy-System-with-a-Web-UI    作者:aaldaber    | 项目源码 | 文件源码
def deletepipeline(request, projectname, pipelinename):
    try:
        project = Project.objects.get(user=request.user, project_name=projectname)
    except Project.DoesNotExist:
        return HttpResponseNotFound('Nothing is here.')

    try:
        pipeline = Pipeline.objects.get(project=project, pipeline_name=pipelinename)
    except Pipeline.DoesNotExist:
        return HttpResponseNotFound('Nothing is here.')

    if request.method == 'GET':
        form = DeleteProject()
        return render(request, 'deletepipeline.html',
                      {'username': request.user.username,
                       'form': form, 'projectname': project.project_name, 'pipelinename': pipeline.pipeline_name})
    elif request.method == 'POST':
        if 'cancel' in request.POST:
            return HttpResponseRedirect(reverse("listpipelines", args=(project.project_name,)))
        elif 'submit' in request.POST:
            pipeline.delete()
            return HttpResponseRedirect(reverse("listpipelines", args=(project.project_name,)))
项目:Distributed-Multi-User-Scrapy-System-with-a-Web-UI    作者:aaldaber    | 项目源码 | 文件源码
def scraper(request, projectname):
    try:
        project = Project.objects.get(user=request.user, project_name=projectname)
    except Project.DoesNotExist:
        return HttpResponseNotFound('Nothing is here.')

    spiderclassnamelabel = "class " + request.user.username.title() + project.project_name.title() + "Spider:"

    if request.method == 'GET':
        form = Scraper(initial={'function': project.scraper_function})
        form.fields['function'].label = spiderclassnamelabel
        return render(request, 'addscraper.html', {'username': request.user.username, 'form': form, 'project': project.project_name})
    elif request.method == 'POST':
        if 'cancel' in request.POST:
            return HttpResponseRedirect(reverse("manageproject", args=(projectname,)))
        if 'submit' in request.POST:
            form = Scraper(request.POST)
            form.fields['function'].label = spiderclassnamelabel
            if form.is_valid():
                project.scraper_function = form.cleaned_data['function']
                project.save()
                return HttpResponseRedirect(reverse("manageproject", args=(projectname,)))
            else:
                return render(request, 'addscraper.html',
                              {'username': request.user.username, 'form': form, 'project': project.project_name})
项目:Distributed-Multi-User-Scrapy-System-with-a-Web-UI    作者:aaldaber    | 项目源码 | 文件源码
def start_project(request, projectname, worker):
    uniqueprojectname = request.user.username + '_' + projectname
    try:
        project = Project.objects.get(user=request.user, project_name=projectname)
    except Project.DoesNotExist:
        return HttpResponseNotFound('Nothing is here.')

    if request.method == 'POST':
        if 'linkgenerator' in worker:
            linkgenaddress = settings.LINK_GENERATOR
            try:
                r = requests.post('%s/schedule.json' % linkgenaddress, data={'project': uniqueprojectname, 'spider': uniqueprojectname}, timeout=(3, None))
            except:
                pass
        elif 'worker' in worker:
            workernumber = ''.join(x for x in worker if x.isdigit())
            workernumber = int(workernumber)
            workeraddress = settings.SCRAPERS[workernumber - 1]
            try:
                r = requests.post('%s/schedule.json' % workeraddress, data={'project': uniqueprojectname, 'spider': uniqueprojectname}, timeout=(3, None))
            except:
                pass

        return HttpResponse('sent start signal')
项目:Distributed-Multi-User-Scrapy-System-with-a-Web-UI    作者:aaldaber    | 项目源码 | 文件源码
def start_project_on_all(request, projectname):

    uniqueprojectname = request.user.username + '_' + projectname

    try:
        project = Project.objects.get(user=request.user, project_name=projectname)
    except Project.DoesNotExist:
        return HttpResponseNotFound('Nothing is here.')

    workers = []
    workers.append(settings.LINK_GENERATOR)
    for worker in settings.SCRAPERS:
        workers.append(worker)

    if request.method == 'POST':
        for worker in workers:
            try:
                r = requests.post('%s/schedule.json' % worker, data={'project': uniqueprojectname, 'spider': uniqueprojectname}, timeout=(3, None))
            except:
                pass
        return HttpResponse('sent start signal')
项目:weixin_server    作者:duoduo369    | 项目源码 | 文件源码
def require_config(config_model):
    """View decorator that enables/disables a view based on configuration.

    Arguments:
        config_model (ConfigurationModel subclass): The class of the configuration
            model to check.

    Returns:
        HttpResponse: 404 if the configuration model is disabled,
            otherwise returns the response from the decorated view.

    """
    def _decorator(func):
        @wraps(func)
        def _inner(*args, **kwargs):
            if not config_model.current().enabled:
                return HttpResponseNotFound()
            else:
                return func(*args, **kwargs)
        return _inner
    return _decorator
项目:FormShare    作者:qlands    | 项目源码 | 文件源码
def get_media_file_response(metadata):
    if metadata.data_file:
        file_path = metadata.data_file.name
        filename, extension = os.path.splitext(file_path.split('/')[-1])
        extension = extension.strip('.')
        dfs = get_storage_class()()

        if dfs.exists(file_path):
            response = response_with_mimetype_and_name(
                metadata.data_file_type,
                filename, extension=extension, show_date=False,
                file_path=file_path, full_mime=True)

            return response
        else:
            return HttpResponseNotFound()
    else:
        return HttpResponseRedirect(metadata.data_value)
项目:django-lti-launch    作者:unizin    | 项目源码 | 文件源码
def get(self, request):
        if not request.user.is_authenticated():
            result = unauthorized_response()
        else:
            # FIXME: not sure what best default behavior is
            result = HttpResponseNotFound()
            return_url = lti_launch_return_url(request.user)
            if return_url:
                parsed = urlparse(return_url)
                launch_q = list(parse_qs(parsed.query).items())
                return_q = list(request.GET.items())
                new_q = urlencode(launch_q + return_q, doseq=True)
                url = urlunparse(
                    (parsed[0],
                     parsed[1],
                     parsed[2],
                     parsed[3],
                     new_q,
                     parsed[5]))
                result = HttpResponseRedirect(url, status=303)
        return result
项目:ISeeNN    作者:sunshaoyan    | 项目源码 | 文件源码
def view_selected_detail(request, query_id):
    try:
        anno_query = AnnoQuery.objects.get(query_image_id=query_id)
    except AnnoQuery.DoesNotExist:
        return HttpResponseNotFound("Resource not available")
    results = []
    for image_id in anno_query.target_image_ids:
        (width, height) = get_image_meta(image_id)
        results.append({
            'id': image_id,
            'width': width,
            'height': height,
        })
    return render(request, 'annotator/view_select_detail.html', {
        'query': query_id,
        'results': results,
    })
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def page_not_found(request, template_name='404.html'):
    """
    Default 404 handler.

    Templates: :template:`404.html`
    Context:
        request_path
            The path of the requested URL (e.g., '/app/pages/bad_page/')
    """
    context = {'request_path': request.path}
    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None             # Django will use DEFAULT_CONTENT_TYPE
    except TemplateDoesNotExist:
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested URL {{ request_path }} was not found on this server.</p>')
        body = template.render(Context(context))
        content_type = 'text/html'
    return http.HttpResponseNotFound(body, content_type=content_type)
项目:TeleGiphy    作者:JessicaNgo    | 项目源码 | 文件源码
def custom_not_found_page(request):
    return HttpResponseNotFound(
        render_to_string('404.html', request=request))
项目:geekcloud    作者:Mr-Linus    | 项目源码 | 文件源码
def log_kill(request):
    """ ??connect?? """
    pid = request.GET.get('id', '')
    log = Log.objects.filter(pid=pid)
    if log:
        log = log[0]
        try:
            os.kill(int(pid), 9)
        except OSError:
            pass
        Log.objects.filter(pid=pid).update(is_finished=1, end_time=datetime.datetime.now())
        return render_to_response('jlog/log_offline.html', locals(), context_instance=RequestContext(request))
    else:
        return HttpResponseNotFound(u'?????!')
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def page_not_found(request, exception, template_name='404.html'):
    """
    Default 404 handler.

    Templates: :template:`404.html`
    Context:
        request_path
            The path of the requested URL (e.g., '/app/pages/bad_page/')
        exception
            The message from the exception which triggered the 404 (if one was
            supplied), or the exception class name
    """
    exception_repr = exception.__class__.__name__
    # Try to get an "interesting" exception message, if any (and not the ugly
    # Resolver404 dictionary)
    try:
        message = exception.args[0]
    except (AttributeError, IndexError):
        pass
    else:
        if isinstance(message, six.text_type):
            exception_repr = message
    context = {
        'request_path': request.path,
        'exception': exception_repr,
    }
    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None             # Django will use DEFAULT_CONTENT_TYPE
    except TemplateDoesNotExist:
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested URL {{ request_path }} was not found on this server.</p>')
        body = template.render(Context(context))
        content_type = 'text/html'
    return http.HttpResponseNotFound(body, content_type=content_type)
项目:PrivacyScore    作者:PrivacyScore    | 项目源码 | 文件源码
def site_screenshot(request: HttpRequest, site_id: int) -> HttpResponse:
    """View a site and its most recent scan result (if any)."""
    site = get_object_or_404(Site, pk=site_id)

    screenshot = site.get_screenshot()
    if not screenshot:
        return HttpResponseNotFound(_('screenshot does not exist'))
    return HttpResponse(screenshot, content_type='image/png')
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        action_name = self.kwargs.get('action_name')
        if action_name == "contact":
            self.template_name = 'package/contact.html'
        elif action_name == "history":
            self.template_name = 'package/history.html'
        elif action_name is None:
            self.template_name = 'package/package.html'
        else:
            return HttpResponseNotFound()

        return super(PackageView, self).get(request, *args, **kwargs)
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
def package_file_fetch(request, package_id):
    pref = preferences.Setting
    pkg = Version.objects.get(id=int(package_id))
    if not pkg:
        return HttpResponseNotFound()
    file_path = os.path.join(settings.MEDIA_ROOT, pkg.storage.name)
    if not os.path.exists(file_path):
        return HttpResponseNotFound()
    if pref.download_cydia_only:
        if 'HTTP_X_UNIQUE_ID' not in request.META:
            return HttpResponseBadRequest()
    request_path = pkg.storage.name
    request_url = pkg.get_external_storage_link()
    pkg.download_times = pkg.download_times + 1
    pkg.save()
    if pref.redirect_resources == 1:
        # Redirect URLs
        return redirect(request_url)
    elif pref.redirect_resources == 2:
        # Redirect to WEB server
        response = HttpResponse()
        if pref.web_server == 0:
            response['X-Accel-Redirect'] = request_url
        elif pref.web_server == 1:
            # You may set Send File Path to settings.MEDIA_ROOT
            response['X-sendfile'] = request_path
        elif pref.web_server == 2:
            pass
    else:
        # Return FileResponse By Reading Static File
        response = serve(
            request,
            path=request_path,
            document_root=settings.MEDIA_ROOT,
        )
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Transfer-Encoding'] = "binary"
    response['Cache-Control'] = "public, must-revalidate, max-age=0"
    response['Content-Disposition'] = "attachment; filename=\"" + urllib.quote_plus(pkg.base_filename()) + "\""
    return response
项目:base_function    作者:Rockyzsu    | 项目源码 | 文件源码
def notfound(request):
    return HttpResponseNotFound('not found!!!')
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def order_is_done(request):
    oid = request.GET.get('id', False)
    if not oid:
        return HttpResponseNotFound(NOTFOUNDMESSAGE)
    try:
        obj = Order.objects.get(pk=int(oid), user=request.user)
        obj.is_done = True
        obj.save()
        return HttpResponseRedirect(reverse('ucenterindex'))
    except:
        return HttpResponseNotFound(NOTFOUNDMESSAGE)
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def business_order_is_done(request):
    oid = request.GET.get('id', False)
    if not oid:
        return HttpResponseNotFound(NOTFOUNDMESSAGE)
    try:
        obj = Order.objects.get(pk=int(oid), food__business__user=request.user)
        obj.is_done = True
        obj.save()
        return HttpResponseRedirect(reverse('businessucenterindex') + '?s=now')
    except:
        return HttpResponseNotFound(NOTFOUNDMESSAGE)
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def changeopen(request):
    if request.user.usertype:
        return HttpResponseForbidden()
    else:
        try:
            b = request.user.business
            b.is_open = not b.is_open
            b.save()
            return HttpResponseRedirect(reverse('businessucenterindex'))
        except:
            return HttpResponseNotFound(NOTFOUNDMESSAGE)
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def post(self, request):
        if not request.user.usertype:
            return JsonResponse({'status': 2})
        if not request.user.can_order:
            return JsonResponse({'status': -1})
        if request.user.get_no_done_order_list():
            return JsonResponse({'status': -2})
        confirm = request.POST.get('confirm', False)
        time = request.POST.get('time', False)
        remarkstr = request.POST.get('remarkstr', '')
        if confirm:
            try:
                orderdic = request.session['order']
            except:
                return HttpResponseNotFound("?????")
            try:
                for fpk in orderdic.keys():
                    if fpk == 'business':
                        b = Business.objects.get(pk=orderdic['business'])
                        if not b.is_open:
                            return JsonResponse({'status': 0})
                    else:
                        f = Food.objects.get(pk=fpk)
                        Order.objects.create(user=request.user, food=f, date_pickup=time, remark=remarkstr)
            except Exception as e:
                print(e)
                return JsonResponse({'status': 0})
            return JsonResponse({'status': 1})
        else:
            return JsonResponse({'status': 0})
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def comment(request, opk):

    try:
        order = request.user.myorder.get(pk=opk)
        business = order.food.business
    except:
        return HttpResponseNotFound()

    if not order.is_done:
        return HttpResponseNotFound()

    if request.method == 'GET':
        return render(request, 'operation/comment.html', {
            'order': order
        })
    elif request.method == 'POST':
        trank = int(request.POST.get('trank', False))
        prank = int(request.POST.get('prank', False))
        textcomment = request.POST.get('textcomment', False)
        try:
            order.trank, order.prank = trank, prank
            average = (trank + prank) / 2
            order.is_comment = True
            order.save()
            if textcomment:
                BusinessTextComment.objects.create(business=order.food.business, comment=textcomment)
            num_order = Order.objects.filter(is_comment=True).count()
            business.total_rank = business.total_rank + average
            business.rank = round(business.total_rank / num_order)
            business.save()
            return JsonResponse({'status': 1})
        except Exception as e:
            print(e)
            return JsonResponse({'status': 0})
项目:python-dockerflow    作者:mozilla-services    | 项目源码 | 文件源码
def version(request):
    """
    Returns the contents of version.json or a 404.
    """
    version_json = import_string(version_callback)(settings.BASE_DIR)
    if version_json is None:
        return HttpResponseNotFound('version.json not found')
    else:
        return JsonResponse(version_json)
项目:geekcloud    作者:GeekCloud-Team    | 项目源码 | 文件源码
def log_kill(request):
    """ ??connect?? """
    pid = request.GET.get('id', '')
    log = Log.objects.filter(pid=pid)
    if log:
        log = log[0]
        try:
            os.kill(int(pid), 9)
        except OSError:
            pass
        Log.objects.filter(pid=pid).update(is_finished=1, end_time=datetime.datetime.now())
        return render_to_response('jlog/log_offline.html', locals(), context_instance=RequestContext(request))
    else:
        return HttpResponseNotFound(u'?????!')
项目:prestashop-sync    作者:dragoon    | 项目源码 | 文件源码
def upload_csv(request, form_class):
    """
    Upload csv file to server and validate it.
    :param form_class: - form class to instantiate (taken from urls.py)
    :rtype: HttpResponse
    """
    csv_file = request.FILES.get('0')
    if csv_file:
        # Apply custom validation
        new_csv_file = None
        try:
            new_csv_file = form_class.validate_csv_file(csv_file)
        except Exception:
            pass
        if not new_csv_file:
            return HttpResponseNotFound(simplejson.dumps({'response': _('File is not valid')}))
        else:
            response = {'response': _('File is valid'), 'lines': new_csv_file.line_count,
                        'names': new_csv_file.names}
            if new_csv_file.warning:
                # add warning
                response['warning'] = new_csv_file.warning
                response['response'] = _('File is partially valid')
            request.session[form_class.CSV_FILE_NAME] = new_csv_file
        return HttpResponse(simplejson.dumps(response))
    raise Http404
项目:djacket    作者:Djacket    | 项目源码 | 文件源码
def get_http_error(exception):
    """
        Returns proper http failure status code according to the provided exception.
    """

    if 'Not a git repository' in exception.args[0]:
        return HttpResponseNotFound()
项目:cjworkbench    作者:CJWorkbench    | 项目源码 | 文件源码
def wfmodule_render(request, pk, format=None):
    if request.method == 'GET':
        try:
            wf_module = WfModule.objects.get(pk=pk)
        except WfModule.DoesNotExist:
            return HttpResponseNotFound()

        if not wf_module.workflow.user_authorized_read(request.user):
            return HttpResponseForbidden()

        return table_result(request, wf_module)


# /input is just /render on the previous wfmodule
项目:closedverse    作者:ariankordi    | 项目源码 | 文件源码
def forgot_passwd(request):
    """Password email page / post endpoint."""
    if request.method == 'POST' and request.POST.get('email'):
        try:
            user = User.objects.get(email=request.POST['email'])
        except (User.DoesNotExist, ValueError):
            return HttpResponseNotFound("There isn't a user with that email address.")
        try:
            user.password_reset_email(request)
        except:
            return HttpResponseBadRequest("There was an error submitting that.")
        return HttpResponse("Success! Check your emails, it should have been sent from \"{0}\".".format(settings.DEFAULT_FROM_EMAIL))
    if request.GET.get('token'):
        user = User.get_from_passwd(request.GET['token'])
        if not user:
            raise Http404()
        if request.method == 'POST':
            if not request.POST['password'] == request.POST['password_again']:
                return HttpResponseBadRequest("Your passwords don't match.")
            user.set_password(request.POST['password'])
            user.save()
            return HttpResponse("Success! Now you can log in with your new password!")
        return render(request, 'closedverse_main/forgot_reset.html', {
            'title': 'Reset password for ' + user.username,
            #'classes': ['no-login-btn'],
        })
    return render(request, 'closedverse_main/forgot_page.html', {
        'title': 'Reset password',
        #'classes': ['no-login-btn'],
    })
项目:closedverse    作者:ariankordi    | 项目源码 | 文件源码
def post_create(request, community):
    if request.method == 'POST' and request.is_ajax():
        # Wake
        request.user.wake(request.META['REMOTE_ADDR'])
        # Required
        if not (request.POST.get('community')):
            return HttpResponseBadRequest()
        try:
            community = Community.objects.get(id=community, unique_id=request.POST['community'])
        except (Community.DoesNotExist, ValueError):
            return HttpResponseNotFound()
        # Method of Community
        new_post = community.create_post(request)
        if not new_post:
            return HttpResponseBadRequest()
        if isinstance(new_post, int):
            # If post limit 
            if new_post == 8:
                # then do meme
                return json_response("You have already exceeded the number of posts that you can contribute in a single day. Please try again tomorrow.", 1215919)
            return json_response({
            1: "Your post is too long ("+str(len(request.POST['body']))+" characters, 2200 max).",
            2: "The image you've uploaded is invalid.",
            3: "You're making posts too fast, wait a few seconds and try again.",
            4: "Apparently, you're not allowed to post here.",
            5: "Uh-oh, that URL wasn't valid..",
            6: "Not allowed.",
            7: "Please don't spam.",
            }.get(new_post))
        # Render correctly whether we're posting to Activity Feed
        if community.is_activity():
            return render(request, 'closedverse_main/elements/community_post.html', { 
            'post': new_post,
            'with_community_container': True,
            'type': 2,
            })
        else:
            return render(request, 'closedverse_main/elements/community_post.html', { 'post': new_post })
    else:
        raise Http404()
项目:closedverse    作者:ariankordi    | 项目源码 | 文件源码
def notification_delete(request, notification):
    if not request.method == 'POST':
        raise Http404()
    try:
        notification = Notification.objects.get(to=request.user, unique_id=notification)
    except Notification.DoesNotExist:
        return HttpResponseNotFound()
    remove = notification.delete()
    return HttpResponse()

#@silk_profile(name='Notifications view')
项目:lopeningent_backend    作者:oSoc17    | 项目源码 | 文件源码
def test_get_node(self):
        """
            Fuzzy test
            Test whether indexing yields the correct response type
        """
        node = views.get_node(self.rf.get('/node?index=0'))
        self.assertTrue(isinstance(node, HttpResponse))
        self.assertFalse(isinstance(node, HttpResponseNotFound))
        node = views.get_node(self.rf.get('/node?index=-5'))
        self.assertTrue(isinstance(node, HttpResponseNotFound))
项目:lopeningent_backend    作者:oSoc17    | 项目源码 | 文件源码
def rate_route(request):
    """
    Adds the rating to all edges in a route, and saves it both in the structure and in the database.

    Query args:
    rid -- the id for the rated route
    rating -- a float between 0 and 5
    """
    try:
        tag = request.POST.get('visited_path')
        new_rating = float(request.POST.get('rating'))
        path = from_string(GRAPH, tag)
        edgecoords = [(s, e) for s, e in zip(path, path[1:])]

        def update_rating(edge):
            for edge in GRAPH.get_edges():
                for s, e in edgecoords:
                    if s == edge.id and e == edge.to:
                        edge._rating = (edge._rating + new_rating) / 2
                        update_edge_in_db(edge)

            return edge

        GRAPH.map_graph(lambda _: _, update_rating)
        return HttpResponse('')
    except:
        return HttpResponseNotFound("Something went wrong while rating your route.")