python类HttpResponseNotAllowed()的实例源码

views.py 文件源码 项目:django-decision-matrix 作者: adamcharnock 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get(self, request, *args, **kwargs):
        return HttpResponseNotAllowed(permitted_methods=['POST'])
base.py 文件源码 项目:djanoDoc 作者: JustinChavez 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def http_method_not_allowed(self, request, *args, **kwargs):
        logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
            extra={
                'status_code': 405,
                'request': request
            }
        )
        return http.HttpResponseNotAllowed(self._allowed_methods())
views.py 文件源码 项目:nav 作者: UNINETT 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def index(request, uri):
    """
    Proxies render requests to graphite-web, as configured in graphite.conf
    """
    base = CONFIG.get('graphiteweb', 'base')

    if request.method in ('GET', 'HEAD'):
        query = _inject_default_arguments(request.GET)
        url = urljoin(base, uri + ('?' + query) if query else '')
        req = Request(url)
    elif request.method == 'POST':
        data = _inject_default_arguments(request.POST)
        url = urljoin(base, uri)
        req = Request(url, data)
    else:
        return HttpResponseNotAllowed(['GET', 'POST', 'HEAD'])

    LOGGER.debug("proxying request to %r", url)
    proxy = urlopen(req)
    headers = proxy.info()
    content_type = headers.getheader('Content-Type', 'text/html')

    if request.method == 'HEAD':
        response = HttpResponse(content_type=content_type)
        response['Content-Length'] = headers.getheader('Content-Length', '0')
    else:
        response = HttpResponse(proxy.read(), content_type=content_type)

    response['X-Where-Am-I'] = request.get_full_path()
    return response
views.py 文件源码 项目:dach 作者: ffaraone 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def descriptor(request):
    if request.method == 'GET':
        app_name = request.resolver_match.app_name
        if not app_name:
            raise Exception('you must include the dach.urls with the app_name')
        descritor_tpl = DACH_CONFIG['appconfig'][app_name].get('descriptor',
            '{}/atlassian-connect.json'.format(app_name))
        return render(request, descritor_tpl, content_type='application/json')

    return HttpResponseNotAllowed(['get'])
views.py 文件源码 项目:dach 作者: ffaraone 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def install(request):
    if request.method == 'POST':
        app_name = request.resolver_match.app_name
        if not app_name:
            raise Exception('you must include the dach.urls with the app_name')
        appconfig = DACH_CONFIG['appconfig']
        scopes_list = appconfig[app_name]['scopes']

        info = json.loads(force_text(request.body))
        capabilities_url = lookup_dict(info, 'capabilitiesUrl')
        token_url, api_url = _get_and_check_capabilities(capabilities_url)
        tenant = Tenant()
        tenant.oauth_id = info['oauthId']
        tenant.oauth_secret = info['oauthSecret']
        tenant.capabilities_url = capabilities_url
        tenant.oauth_token_url = token_url
        tenant.api_url = api_url
        tenant.group_id = info['groupId']
        tenant.room_id = info.get('roomId', None)
        tenant.app_name = app_name
        tenant.scopes = '|'.join(scopes_list)

        token = get_access_token(tenant)

        tenant.group_name = token.group_name
        get_backend().set(tenant.oauth_id, 'tenant', tenant.json())
        post_install.send(
            apps.get_app_config(app_name),
            tenant=tenant
        )
        logger.info('addon successfully installed')
        return HttpResponse(status=204)
    return HttpResponseNotAllowed(['post'])
views.py 文件源码 项目:dach 作者: ffaraone 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def uninstall(request, oauth_id):
    if request.method == 'DELETE':
        app_name = request.resolver_match.app_name
        if not app_name:
            raise Exception('you must include the dach.urls with the app_name')
        get_backend().delete(oauth_id)
        post_uninstall.send(
            apps.get_app_config(app_name),
            oauth_id=oauth_id
        )
        logger.info('addon successfully uninstalled')
        return HttpResponse(status=204)
    return HttpResponseNotAllowed(['delete'])
media_select.py 文件源码 项目:C3FOCSite 作者: Technikradio 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def render_media_selection_page(request: HttpRequest):
    # TODO add 'add_media' button
    if not request.GET.get('action_url'):
        return HttpResponseNotAllowed("You must specify a action url")
    payload = request.GET.get("payload")
    action_url = request.GET["action_url"]
    action = action_url + "?payload=" + str(payload) + "&media_id="
    page = 1
    if request.GET.get('page'):
        page = int(request.GET['page'])
    items_per_page = 50
    if request.GET.get('objects'):
        items_per_page = int(request.GET["objects"])
    total_items = Media.objects.all().count()
    max_page = total_items / items_per_page
    if max_page < 1:
        max_page = 1
    if page > max_page:
        page = max_page
    start_range = 1 + page * items_per_page
    if start_range > total_items:
        start_range = 0
    end_range = (page + 1) * items_per_page
    a = render_headbar(request, title="Select media")
    a += '<div class="admin-popup">'
    a += '<h3>Please select your desired image</h3><table><tr><th>Select</th><th>Preview</th><th>Title</th></tr>'
    objects = Media.objects.filter(pk__range=(start_range, end_range))
    for img in objects:
        a += '<tr><td><a href="' + action + str(img.pk)
        a += '"><img src="/staticfiles/frontpage/add-image.png" class="button"/></a></td><td><img src="'
        a += img.lowResFile + '" /></td><td>' + img.headline + '</td></tr>'
    a += '</table>'
    if page > 1:
        a += '<a href="' + request.path + '?page=' + str(page - 1) + '&objects=' + str(objects) + '&payload=' + \
             str(payload) + '&action_url=' + str(action_url) + '" class="button">Previous page </a>'
    if page < max_page:
        a += '<a href="' + request.path + '?page=' + str(page + 1) + '&objects=' + str(objects) + '&payload=' + \
             str(payload) + '&action_url=' + str(action_url) + '" class="button">Next page </a>'
    a += '</div>' + render_footer(request)
    return HttpResponse(a)
views.py 文件源码 项目:django-yandex-cash-register 作者: bzzzzzz 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get(self, request, *args, **kwargs):
        return HttpResponseNotAllowed(['POST'])
views.py 文件源码 项目:django-yandex-cash-register 作者: bzzzzzz 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get(self, request, *args, **kwargs):
        if not request.META.get(
                'HTTP_REFERER', '').startswith(conf.MONEY_URL) and \
                not settings.DEBUG:
            return HttpResponseNotAllowed(['POST'])
        return super(PaymentFinishView, self).get(request, *args, **kwargs)
api.py 文件源码 项目:Sentry 作者: NetEaseGame 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def _dispatch(self, request, helper, project_id=None, origin=None,
                  *args, **kwargs):
        # NOTE: We need to override the auth flow for a CSP report!
        # A CSP report is sent as a POST request with no Origin or Referer
        # header. What we're left with is a 'document-uri' key which is
        # inside of the JSON body of the request. This 'document-uri' value
        # should be treated as an origin check since it refers to the page
        # that triggered the report. The Content-Type is supposed to be
        # `application/csp-report`, but FireFox sends it as `application/json`.
        if request.method != 'POST':
            return HttpResponseNotAllowed(['POST'])

        if request.META.get('CONTENT_TYPE') not in self.content_types:
            raise APIError('Invalid Content-Type')

        request.user = AnonymousUser()

        project = self._get_project_from_id(project_id)
        helper.context.bind_project(project)
        Raven.tags_context(helper.context.get_tags_context())

        # This is yanking the auth from the querystring since it's not
        # in the POST body. This means we expect a `sentry_key` and
        # `sentry_version` to be set in querystring
        auth = self._parse_header(request, helper, project)

        project_ = helper.project_from_auth(auth)
        if project_ != project:
            raise APIError('Two different project were specified')

        helper.context.bind_auth(auth)
        Raven.tags_context(helper.context.get_tags_context())

        return super(APIView, self).dispatch(
            request=request,
            project=project,
            auth=auth,
            helper=helper,
            **kwargs
        )
base.py 文件源码 项目:django-next-train 作者: bitpixdigital 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def http_method_not_allowed(self, request, *args, **kwargs):
        logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
            extra={
                'status_code': 405,
                'request': request
            }
        )
        return http.HttpResponseNotAllowed(self._allowed_methods())
middleware.py 文件源码 项目:FormShare 作者: qlands 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def process_response(self, request, response):
        if isinstance(response, HttpResponseNotAllowed):
            context = RequestContext(request)
            response.content = loader.render_to_string(
                "405.html", context_instance=context)

        return response
views.py 文件源码 项目:updater 作者: mmohrhard 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get_channels(request):
    if request.method != 'GET':
        return HttpResponseNotAllowed('Only GET allowed')

    channels = UpdateChannel.objects.values('name')
    channel_names = [channel['name'] for channel in channels]
    return JsonResponse(channel_names, safe=False)
views.py 文件源码 项目:updater 作者: mmohrhard 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get_releases(request, channel):
    if request.method != 'GET':
        return HttpResponseNotAllowed('Only GET allowed')

    update_channel = get_object_or_404(UpdateChannel, name=channel)
    releases = Release.objects.filter(channel=update_channel).values('name')
    release_names = [release['name'] for release in releases]
    return JsonResponse(release_names, safe=False)
views.py 文件源码 项目:perdiem-django 作者: RevolutionTech 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def dispatch(self, request, *args, **kwargs):
        try:
            return super(FormsetView, self).dispatch(request, *args, **kwargs)
        except Http405:
            return HttpResponseNotAllowed(['GET', 'POST'])
views.py 文件源码 项目:blobstore_django 作者: Cadmus 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def http_method_not_allowed(self, *args, **kwargs):
        allowed_methods = [m for m in self.http_method_names if hasattr(self, m)]
        return http.HttpResponseNotAllowed(allowed_methods)
views.py 文件源码 项目:berlyne 作者: rugo 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def perform_action(request, problem_slug, action_name):
    try:
        _run_task_on_existing_vm(action_name, problem_slug)
    except deploy_controller.IllegalAction as ex:
        return HttpResponseNotAllowed(str(ex))
    return redirect(
        'vmmanage_detail_problem',
        problem_slug=problem_slug
    )
views.py 文件源码 项目:HFUT_Market 作者: netcan 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def CommodityDelete(request, pk):
    # ????
    commodity = get_object_or_404(Commodity, pk=pk)
    if commodity.user != request.user:
        return HttpResponseNotAllowed(['GET', 'POST'])

    if request.method == 'POST':
        commodity.delete()
        return HttpResponseRedirect(reverse('market:index'))
    else:
        return HttpResponseNotAllowed(['GET'])
base.py 文件源码 项目:django-wechat-api 作者: crazy-canux 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def http_method_not_allowed(self, request, *args, **kwargs):
        logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
            extra={
                'status_code': 405,
                'request': request
            }
        )
        return http.HttpResponseNotAllowed(self._allowed_methods())
views.py 文件源码 项目:pyconjp-website 作者: pyconjp 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def result_notification_send(request, section_slug, status):
    if request.method != "POST":
        return HttpResponseNotAllowed(["POST"])

    if not request.user.has_perm("reviews.can_manage_%s" % section_slug):
        return access_not_permitted(request)

    if not all([k in request.POST for k in ["proposal_pks", "from_address", "subject", "body"]]):
        return HttpResponseBadRequest()

    try:
        proposal_pks = [int(pk) for pk in request.POST["proposal_pks"].split(",")]
    except ValueError:
        return HttpResponseBadRequest()

    proposals = ProposalBase.objects.filter(
        kind__section__slug=section_slug,
        result__status=status,
    )
    proposals = proposals.filter(pk__in=proposal_pks)
    proposals = proposals.select_related("speaker__user", "result")
    proposals = proposals.select_subclasses()

    notification_template_pk = request.POST.get("notification_template", "")
    if notification_template_pk:
        notification_template = NotificationTemplate.objects.get(pk=notification_template_pk)
    else:
        notification_template = None

    emails = []

    for proposal in proposals:
        if not proposal.speaker_email:
            continue

        rn = ResultNotification()
        rn.proposal = proposal
        rn.template = notification_template
        rn.to_address = proposal.speaker_email
        rn.from_address = request.POST["from_address"]
        rn.subject = request.POST["subject"]
        rn.body = Template(request.POST["body"]).render(
            Context({
                "proposal": proposal.notification_email_context()
            })
        )
        rn.save()
        emails.append(rn.email_args)

    send_mass_mail(emails)

    return redirect("result_notification", section_slug=section_slug, status=status)


问题


面经


文章

微信
公众号

扫码关注公众号