Как вызвать ошибку 418

I have a web-server and I would like to have the HTTP status code 418 ‘I’m a teapot’ under some conditions, I am sure I would use an if statement, I just can’t seem to get it to trip, any help?

asked Feb 12, 2013 at 1:04

gudenau's user avatar

6

<?php
header("HTTP/1.1 418 I'm a teapot");
?>
<html>
<h1>418 I'm a teapot</h1><br>
<p>The HTCPCP Server is a teapot. The responding entity MAY be short and stout.</p>
</html>

Will result in:

418 I’m a teapot

The HTCPCP Server is a teapot. The responding entity MAY be short and stout.

James Billingham's user avatar

answered Feb 12, 2013 at 1:15

on September 5, 2019 •

nginx-logo-rgb-large

A year or so ago I got intrigued about how to “properly” implement custom HTTP errors on NGINX after watching this rather funny DEFCON talk. The speaker talks about returning “weird” HTTP codes since browsers usually seem to display anything they receive regardless of the HTTP status code in the return. The idea being that scanners used by script kiddies are usually poorly written and has a high chance of failing if they get an unexpected “rare” HTTP status code.

This got me thinking, returning arbitrary status codes instead of the correct ones seems a little drastic, and relies on undocumented “features” in web browsers, so the risk of something completely breaking down the line is rather high. But I thought that instead of returning obscure HTTP status codes for valid requests, what about returning really weird but still valid HTTP status codes instead of 404 errors?

The ones among you that happen to know what HTTP Error 418 is are probably chuckling a bit at this point, since 418 is probably the definition of a “weird but still valid HTTP status code”, but for the ones of you that don’t know, 418 is the code for “I’m a teapot”. Now, you might be wondering why you’d ever need a web server to respond “I’m a teapot”, and you’d be right in thinking “never”.

Error 418 came about as an April fools joke by the IETF back in 1998. RFC 2324 was published on 1th of April 1998, describing a standard called Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) that is an implementation for controlling coffee machines over HTTP. The whole RFC was basically a demonstration for how to not use HTTP for insane applications. Along with this standard a new HTTP status code was standardised, HTTP 418 “I’m a Teapot”, which is aptly used by said teapot when you ask it to brew coffee using HTCPCP.  That the standard doesn’t implement any support for teapots isn’t really explained, neither is the need for an unsupported teapot to implement HTCPCP. This was later rectified in 2014 by RFC 7168 which extends HTCPCP to allow brewing of teas. However, this being real standards means that HTTP 418 is a very real standardised error. This was later reaffirmed back in 2015 by the save418.com movement when some dimwit with the mission to eradicate any joy from the world got the bright spark to try and have 418 re-purposed for something more “useful”. 

So, we have the idea, we have our obscure but correct error, now how do we go about getting NGINX to cooperate?

I did a quick google search to see if anybody has had the same bright spark as I before and found this short snippet of code:

server {
    listen       80 default_server;

    location / {
        default_type text/plain;
        return 418 "418 I'm a teapotn";
    }
}

This was clearly intended as a joke, and I couldn’t for the life of me get this configuration to work, no matter what I tried.

The main problem I had was that I want my server to actually send the status code 418, not just redirect to an error page for 418 but with the jolly status code 200.

This is what I came up with

server {
        listen 80 default_server;
        
        location / {
                return 418;
        }
        
        error_page 418 /custom_418.html;
        location = /custom_418.html {
                root /var/www/html/errors;
                internal;
}

As you can see, we have a bit more going on. First, we do the same thing and return a 418 if we can’t find anything more appropriate, basically what NGINX does by default but with a different status code. Then outside the location block we define a custom 418 error page, as NGINX sadly doesn’t ship with a default error page for 418, so that we can get a lovely facsimile of the NGINX default error page, along with the aforementioned code and the message “I’m a Teapot” to further vex any script kiddie that pulls it up in his browser after wondering what in the world on that error page made his überl33t script crash. Here’s my version, I’m sure you can come up with something much more spectacular. Please post a comment with a link to your error if you do make one, I’d love to see them!

<html>
<head><title>418 I'm a teapot</title></head>
<body bgcolor="white">
<center><h1>418 I'm a teapot</h1></center>
<hr><center>Russell's teapot/1.2.11</center>
</body>
</html>

The following snippet has been thoroughly tested on NGINX, and actually returns a status code of 418 along with the page, just as Mr. L. Masinter intended. No guarantees of course, the above code is provided free at charge with no warranties, use at your own risk.

Hope you enjoyed this little useless bit of knowledge, and I hope it might also serve as an example of how just because something probably shouldn’t be done doesn’t mean it can’t be done. It also serves as a neat primer if you want to implement your own error pages in NGINX. And we have also proved that NGINX is indeed, still awesome!


Categories: Tech

Tags: error418, Internet, nginx, servers, web server

Если вы давно в Интернете, то наверняка встречали страницы с ошибками 404 («не найдено») или 403 («запрещено»). Но помимо них уже очень давно существует ошибка 418. Знаете, что она означает? Не поверите – «Я – [заварочный] чайник!».

Ошибка 418 - Я - чайник!

♥ ПО ТЕМЕ: Опрос: Какого цвета кроссовки вы видите – белые или черные?

1 апреля 1998 года Internet Engineering Task Force (IETF, «Целевая группа по инженерному обеспечению Интернета) представила «протокол для контроля, мониторинга и диагностики кофемашин». В документе среди прочего описывались и ошибки. Проблема за номером 418 описывалась так: если кто-то попытается сварить кофе в чайнике, последний вежливо, но твердо сообщит: «Я – чайник. Ошибка 418».

Ошибка 418: Я - чайник

Шутка прижилась (по крайней мере, в узких кругах). Например, у Google даже сегодня есть соответствующая страница Google.com/teapot.

Google teapot

В языках программирования Node.js и Google Go, фреймворке Microsoft ASP.NET ошибка 418 также присутствует как «пасхальное яйцо».

Однако летом 2017 года над 418-й нависла чудовищная угроза. Руководитель IETF Марк Ноттингем заявил, что эта ошибка никогда не была частью стандарта HTTP, за которым он надзирает (протокол HTTP отвечает за взаимодействие веб-браузеров и веб-серверов – прим. ред.). Так что 418-ю ошибку стоило бы лишить текущего гэг-наполнения и вместо него назначить что-нибудь более полезное.

«Я знаю, что это весело… но не стоит загрязнять базовый протокол».

♥ ПО ТЕМЕ: Биткоин: 10 удивительных фактов, о которых вы могли не знать.

Сторонники у погибающей ошибки нашлись сразу же. И главным из них, как ни странно, оказался 15-летний школьник-программист Шейн Брансвик. Он запустил кампанию «Save 418» и хэштэг #Save418.

«Такие вещи как она вызывают улыбку на лице. Это напоминание о том, что компьютеры делают люди. Потерять 418-ю было бы по-настоящему ужасно».

Другие пользователи указывают, что 418-я ошибка в своем нынешнем виде существовала так долго, что отказ от неё создаст проблемы многим сайтам.

Ноттингем, по его собственному признанию, не ожидал, что его предложение вызовет столь большой резонанс. Он уверяет, что просто хотел прояснить статус 418-й – или его отсутствие. Узнав о школьнике-защитнике старой ошибки, он написал в Twitter «Я плохой, плохой человек» и поставил ссылку на веб-сайт Save418. Разработчик говорит, что его приятно удивил сам факт того, что современный тинейджер проявляет такой интерес к стандарту, которому уже почти три десятилетия:

«Я на самом деле рад тому, что следующее поколение разработчиков по-прежнему уделяет большое внимание HTTP».

error 418 teapot

История с ошибкой 418 закончилась хэппи-эндом. Ноттингем пообещал, что официально сделает ошибку 418 частью HTTP-кода. Так что заявление «Я — чайник» совершенно законно окажется неотъемлемой частью интернета. Готовьте свои мемогенераторы! :).

Смотрите также:

  • Как появились названия брендов: Ikea, Lego, Pepsi, Reebok, Skype, Sony, Canon, Google — 16 историй о происхождении названий известных компаний.
  • Чревовещатели (вентрологи), или как говорить и петь не раскрывая рта (видео).
  • Почему доллар называют баксом, обозначают символом $ и другие интересные факты об американской валюте.

Многие, на просторах сети, так или иначе сталкивались с ошибками при соединении с сайтами. Многие видели ошибку 404, 403 или какую-нибудь другую. Но есть одна ошибка, которая выбивается из общего ряда и это ошибка 418 – «Я чайник!».

Инженерный Совет Интернета 1 апреля 1998 года выпустил «протокол
для контроля, мониторинга и диагностики кофемашин» (Hyper Text Coffee Pot
Control Protocol). Протокол шуточный, как вы могли понять по дате выпуска, но в
нем были даже описаны ошибки, одной из которых была та самая ошибка 418. Ошибка
вызывается при попытке приготовить кофе в чайнике.

Шуточная ошибка понравилась пользователям. Это не полноценная ошибка стандартизированная в http и маловероятно, что вы когда-то наткнетесь на нее в сети. Некоторые фреймворки, к примеру Symfony, всё равно поддерживает данную ошибку, а Google создала даже отдельную страницу с данной ошибкой, на которой есть чайник, нажав на него проиграется анимация.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Посмотрите также:

  • Btop++ — одна из самых функциональных утилит для мониторинга…
  • Топ-10 облачных хранилищ 2023 года
  • Пасхалка. Играем в Pac-Man в поиске Google
  • Statusbar Icon Hider — скроет ненужные вам иконки со статус…
  • Бэтмен стал пахталкой в поиске Google
  • Пасхалка. Скринсейвер с DVD в поиске Google

400 — Bad Request (Некорректный запрос)

«Плохой запрос». Этот ответ означает, что сервер не понимает… Читать далее

Подробнее

401 — Unauthorized (Не авторизован)

«Неавторизовано». Для получения запрашиваемого ответа нужна … Читать далее

Подробнее

402 — Payment Required (Необходима оплата)

«Необходима оплата». Этот код ответа зарезервирован для буду… Читать далее

403 — Forbidden (Запрещено)

«Запрещено». У клиента нет прав доступа к содержимому, поэто… Читать далее

Подробнее

404 — Not Found (Не найдено)

«Не найден». Сервер не может найти запрашиваемый ресурс. Код… Читать далее

Подробнее

405 — Method Not Allowed (Метод не поддерживается)

«Метод не разрешен». Сервер знает о запрашиваемом методе, но… Читать далее

Подробнее

406 — Not Acceptable (Неприемлемо)

Этот ответ отсылается, когда веб сервер после выполнения ser… Читать далее

Подробнее

407 — Proxy Authentication Required (Необходима аутентификация прокси)

Этот код ответа аналогичен коду 401, только аутентификация т… Читать далее

Подробнее

408 — Request Timeout (Истекло время ожидания)

Ответ с таким кодом может прийти, даже без предшествующего з… Читать далее

Подробнее

409 — Conflict (Конфликт)

Этот ответ отсылается, когда запрос конфликтует с текущим со… Читать далее

410 — Gone (Удалён)

Этот ответ отсылается, когда запрашиваемый контент удален с … Читать далее

Подробнее

411 — Length Required (Необходима длина)

Запрос отклонен, потому что сервер требует указание заголовк… Читать далее

Подробнее

412 — Precondition Failed (Условие ложно)

Клиент указал в своих заголовках условия, которые сервер не … Читать далее

Подробнее

413 — Request Entity Too Large (Полезная нагрузка слишком велика)

Размер запроса превышает лимит, объявленный сервером. Сервер… Читать далее

Подробнее

414 — Request-URI Too Long (URI слишком длинный)

URI запрашиваемый клиентом слишком длинный для того, чтобы с… Читать далее

Подробнее

415 — Unsupported Media Type (Неподдерживаемый тип данных)

Медиа формат запрашиваемых данных не поддерживается сервером… Читать далее

Подробнее

416 — Requested Range Not Satisfiable (Диапазон не достижим)

Диапозон указанный заголовком запроса Range не может бы… Читать далее

417 — Expectation Failed (Ожидание не удалось)

Этот код ответа означает, что ожидание, полученное из заголо… Читать далее

Подробнее

418 — I’m a teapot (Я — чайник)

I’m a teapot — Этот код был введен в 1998 году как одна из т… Читать далее

Подробнее

419 — Authentication Timeout (not in RFC 2616) (Обычно ошибка проверки CSRF)

Authentication Timeout (not in RFC 2616) — Этого кода нет в … Читать далее

Подробнее

420 — Enhance Your Calm (Twitter) (Подождите немного (Твиттер))

Возвращается Twitter Search и Trends API, когда клиент отпра… Читать далее

Подробнее

421 — Misdirected Request (Неверный запрос)

Misdirected Request — запрос был перенаправлен на сервер, не… Читать далее

Подробнее

422 — Unprocessable Entity (Необрабатываемый экземпляр)

Запрос имел правильный формат, но его нельзя обработать из-з… Читать далее

Подробнее

423 — Locked (Заблокировано)

Целевой ресурс из запроса заблокирован от применения к нему … Читать далее

424 — Failed Dependency (Невыполненная зависимость)

Не удалось завершить запрос из-за ошибок к предыдущем запрос… Читать далее

Подробнее

425 — Too Early (Слишком рано)

Too Early — сервер не готов принять риски обработки «ранней … Читать далее

Подробнее

426 — Upgrade Required (Необходимо обновление)

Указание сервера, клиенту, обновить протокол. Заголовок отве… Читать далее

Подробнее

428 — Precondition Required (Необходимо предусловие)

Precondition Required — сервер указывает клиенту на необходи… Читать далее

Подробнее

429 — Too Many Requests (Слишком много запросов)

Too Many Requests — клиент попытался отправить слишком много… Читать далее

Подробнее

430 — Would Block (Будет заблокировано)

Код состояния 430 would Block — это код, который сервер мог … Читать далее

Подробнее

431 — Request Header Fields Too Large (Поля заголовка запроса слишком большие)

Request Header Fields Too Large — Превышена допустимая длина… Читать далее

434 — Requested host unavailable (Запрашиваемый адрес недоступен)

Сервер к которому вы обратились недоступен… Читать далее

Подробнее

444 — No Response (Nginx) (Нет ответа (Nginx))

Код ответа Nginx. Сервер не вернул информацию и закрыл соеди… Читать далее

Подробнее

449 — Retry With (Повторить с…)

Retry With — возвращается сервером, если для обработки запро… Читать далее

Подробнее

450 — Blocked by Windows Parental Controls (Microsoft) (Заблокировано родительским контролем Windows (Microsoft))

Расширение Microsoft. Эта ошибка возникает, когда родительск… Читать далее

Подробнее

451 — Unavailable For Legal Reasons (Недоступно по юридическим причинам)

Unavailable For Legal Reasons — доступ к ресурсу закрыт по ю… Читать далее

Подробнее

499 — Client Closed Request (Клиент закрыл соединение)

Нестандартный код состояния, представленный nginx для случая… Читать далее

Подробнее

I use this code. I have nginx reverse-proxying requests to two separate HTTP servers. One handles requests for unauthenticated users, and the second handles requests for authenticated users. The problem in this particular case, is the first server is the one that determines if the user is authenticated. Please don’t ask why.

So, if the first server determines the user is authenticated, it responds 418 I'm a teapot. NGINX then reroutes the traffic internally to the second server. As far as the browser is concerned, it was a single request.

This is in the spirit of HTCPCP code 418, because if you attempt to BREW with a teapot, the appropriate response is «I’m not the kind of thing that can handle that request, but there may be others.» .. In other words, «I’m a teapot. Find a coffee maker.» (the second server being the coffee maker).

Ultimately, while 418 is not explicitly defined in RFC 7231, it is still covered by the umbrella of 4xx (Client Error).

6. Response Status Codes

  • 4xx (Client Error): The request contains bad syntax or cannot be fulfilled

6.5. Client Error 4xx

  • The 4xx (Client Error) class of status code indicates that the client
    seems to have erred. Except when responding to a HEAD request, the
    server SHOULD send a representation containing an explanation of the
    error situation, and whether it is a temporary or permanent
    condition. These status codes are applicable to any request method.
    User agents SHOULD display any included representation to the user.

Если вы знакомы как работают сайты в интернете, то знаете, что когда что-то на сервере идет не так, он выдает ошибку с определенным кодом.  У пользователей Beeline тоже возникают сложности при совершении стандартных действий: отправке СМС, попытке выйти в интернет или открыть сайт. Рассмотрим, почему возникает ошибка доступа 418 Билайн, откуда вообще появилась эта кодировка, и что можно сделать для ее исправления.

Что делать при ошибке доступа 418 в Билайн ТВ

Большинство сбоев при работе с устройствами для выхода в интернет, есть свои кодовые номера. По ним можно определит примерную причину проблемы, и предпринять определенные действия. Например, кодовый номер ошибки 418 с продолжением I’m a teapot был введен несколько дет назад как первоапрельский розыгрыш.

В принципе, никто не ожидал, что он будет поддерживаться реальными серверами. Ведь его дословный перевод «Я чайник». Однако в действительности, в последние два года пользователи Билайн стали сталкиваться с ошибкой доступа для потока 418. При этом, как отмечает большинство клиентов оператора, сталкиваются с такой ошибкой именно при подключении к телевизору. Сначала сигнал идет нормально, а после начинаются выбросы уведомления «Ошибка 418», и это явно не розыгрыш.

Принцип появления данного сбоя не относится к серверным проблемам. Так же она не генерируется программным обеспечением, или оборудованием, на котором возникает. Здесь полностью исключается вина вашего провайдера. Поэтому и причины нужно искать исключительно на стороне пользователя:

  1. Ограничение устанавливает IP-адрес.
  2. Система вас не узнает, и воспринимает как робота.
  3. Неверные данные для активации учетной записи.
  4. Вы не оплатили пакет на обслуживание, или срок его действия истек.
  5. Аккаунт заблокирован по какой-то причине.
  6. Неверно выставленный адрес сервера.

Обратите внимание! Ошибка 418, в переводе обозначенная, как «Я чайник», говорит о проблемах исключительно на стороне пользователя.

Что делать, если в Билайн возникает ошибка 418

Если так случилось, что вопреки всему на вашем экране при попытке входа на сайт www.beeline.ru все же отобразилось уведомление с этим кодом, то здесь уже явно не розыгрыш. Поэтому пробуем решить проблему самостоятельно:

  1. Если вы неверно ввели логин и пароль. Проверьте еще раз ваши данные, которые получены при регистрации, исправьте все и введите их повторно.
  2. Очистите куки через историю своего браузера. В этом блоке отыщите «Очистить cookies», а также «Удалить кэш». Воспользуйтесь нажатием на кнопки, и вычистите все лишнее.
  3. Уточните не заблокировал ли вас провайдер за какие-либо нарушения, а также проверьте наличие оплаченных пакетов.

Важно при действиях по настройкам и очистке, когда вы их закончите, перезагрузить устройство. Тогда данные системы обновятся, и вы сможете подключиться к ТВ Билайн.

Однако если вообще ни одна из рекомендаций у вас не сработает, лучше обратиться в поддержку. Возможно, специалисты Билайна подскажут вам оптимальное решение в вашей ситуации.

Felippe Regazio

I was building an API, and consulting some http status codes when i saw the 418 status code on the MDN documentation.

418 I'm a teapot
The server refuses the attempt to brew coffee with a teapot.

And this is what the MDN says about it:

The HTTP 418 I’m a teapot client error response code indicates that the server refuses to brew coffee because it is a teapot. This error is a reference to Hyper Text Coffee Pot Control Protocol which was an April Fools’ joke in 1998.

You can check the documentation here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

And here is the RFC:
https://tools.ietf.org/html/rfc2324#section-2.3.2

Then i asked myself: WTF?
Most of you devs may already known this staus code and even its history, but many dont. So, there it goes:

«So, what’s the «418 I’m a teapot» all about? Well, the group of people who make these codes and set the standards is the IETF or «Internet Engineering Task Force». To propose new standards, the members release RFC’s or «Requests for Comments» to the community. Every year since 1989, they release a few humorous RFC’s for April’s Fool Day and on April 1st, 1998, RFC 2324 introduced the «Hyper Text Coffee Pot Control Protocol» or (HTCPCP/1.0). This was a brand new protocol for controlling, monitoring, and diagnosing coffee pots. Now, the RFC is pretty funny with lines like «Coffee pots heat water using electronic mechanisms, so there is no fire. (…) Now, you may be asking, if this is a COFFEE protocol, why the «teapot» code? This is answered in Section 2.3.2. in that «Any attempt to brew coffee with a teapot should result in the HTTP error code 418 I’m a teapot and the resulting entity body MAY be short and stout». And just like that the «418 I’m a teapot» code was born! Since then, it’s been used in all sorts of wacky ways. Google even referred to «418» as a different error in their 2013 April Fool’s Joke «Google Nose» saying that «418: Scent transfer protocol error» indicates system congestion; please try again later».

from: https://sitesdoneright.com/blog/2013/03/what-is-418-im-a-teapot-status-code-error

So, its just a joke.
Personally, i found it very cool ;P

Для многих утро не бывает добрым, если его не начать с чашечки кофе. А знаете ли вы, что в Интернете существует специальный протокол для управления кофеваркой? А сервер возвращает ошибку с кодом 418 «I’m a teapot» — «Я чайник» при попытке неправильного приготовления кофе.

ошибка кода

Это не бред и не ошибка системы. Дело все в том, что каждый год 1 апреля Internet Engineering Task Force (Инженерный Совет Интернета) публикует шуточные RFC (рабочие предложения), которые содержат технические спецификации и стандарты.

Протокол HTCPCP был опубликован 1 апреля 1998 года. Этот протокол служит расширением HTTP, а запросы определяются с помощью схемы URI coffee: и содержат несколько добавлений к HTTP-запросам:

  • BREW или POST: заставляет HTCPCP-сервер заваривать кофе.
  • GET: получение кофе от HTCPCP-сервера.
  • PROPFIND: поиск метаданных о кофе.
  • WHEN: Сказав «when», пользователь заставляет HTCPCP-сервер завершить добавление молока в кофе (когда есть молоко).

Однако, у этого протокола существует один очевидный недостаток: не предусмотрена ошибка «Out of Coffee», когда в кофеварке закончился кофе.

После выхода данного протокола в обсуждение были выдвинуты предложения по расширению спецификации HTCPCP для других напитков. В 2014 году вышел протокол HTCPCP для чая. Теперь жители Туманного Альбиона могут спать спокойно…

Если у Вас есть проект

или вы хотите задать нам какие-нибудь вопросы

HTTP response status code ==418 I’m a teapot== is a client error that is returned by the server to indicate that this server has been requested to brew coffee, yet, it’s a teapot.

Usage

The ==418 I’m a teapot== error message was designed as one of the IETF April Fools’ jokes and the RFC states that any teapot that has been asked to brew coffee shall respond with this message. Specifically, it states that the resulting message body may be short and stout.

Funnily enough, although this status code is not used, it is supported by many HTTP libraries. Some time ago, there was an effort to have this error removed so that the number can be used in an official capacity. However, this was met with resistance and led to the creation of the Save 418 initiative. As such, the message and status code remain.

Note

Search engines like Google will not index a URL with 418 I’m a teapot response status, and consequently, URLs that have been indexed in the past but are now returning this HTTP status code will be removed from the search results.

Example

In the example, the client requests that coffee be brewed, but the teapot objects.

Request

BREW coffee HTTP/1.1
Host: www.example.re
Content-Type: message/coffeepot
Content-Length: 5

start

Response

HTTP/1.1 418 I’m a teapot
Content-Type: text/html
Content-Length: 146

<html>
  <head>
    <title>Beverage not supported</title>
  </head>
  <body>
   <p>I’m a teapot and I don’t support coffee.</p>
  </body>
</html>

Code references

.NET

StatusCodes.Status418ImATeapot

Rust

http::StatusCode::IM_A_TEAPOT

Go

http.StatusTeapot

Symfony

Response::HTTP_I_AM_A_TEAPOT

Python3.5+

http.HTTPStatus.IM_A_TEAPOT

Angular

@angular/common/http/HttpStatusCode.ImATeapot

Takeaway

The ==418 I’m a teapot== status code is a client error that was designed as an April Fools joke and will not likely be seen in production.

See also

  • RFC 2324
  • RFC 7168

Last updated: August 2, 2023

It seems Webapp2 does not support the status code 418 because it doesn’t have a status message mapped to it. How do I get around it and return a 418?

response.set_status(418)    # does not work
response.status_int = 418   # does not work either

Traceback:

  File "/.../App Engine SDK/lib/webapp2-2.5.2/webapp2.py", line 425, in set_status
    self.status = code
  File "/.../App Engine SDK/lib/webapp2-2.5.2/webapp2.py", line 405, in _set_status
    message = message or Response.http_status_message(code)
  File "/.../App Engine SDK/lib/webapp2-2.5.2/webapp2.py", line 488, in http_status_message
    raise KeyError('Invalid HTTP status code: %d' % code)
KeyError: 'Invalid HTTP status code: 418'

asked Aug 11, 2017 at 20:18

Derek 朕會功夫's user avatar

Derek 朕會功夫Derek 朕會功夫

92.4k44 gold badges185 silver badges247 bronze badges

10

By monkey patching, I am able to get the status code 418 to work, but only partially.

class TeapotHandle(webapp2.RequestHandler):
    def get(self):
        from webob import util
        import httplib

        util.status_reasons[418] = "I'm a teapot"
        httplib.responses[418] = "I'm a teapot"

        self.response.set_status(418)

yields, using the dev server:

HTTP/1.1 418 Unknown Status Code
[...]

But in fact, it works as expected once deployed on App Engine Cloud:

HTTP/1.1 418 I'm a Teapot
[...]

answered Jan 7, 2018 at 23:49

solsTiCe's user avatar

solsTiCesolsTiCe

3795 silver badges15 bronze badges

The 418 HTTP Status Code means “I’m a teapot“, indicating that the server cannot brew coffee because it is permanently configured as a teapot. When a coffee/tea pot is out of coffee, it should return 503. Hyper Text Coffee Pot Control Protocol, as defined in April Fool’s Day jokes in 1998 and 2014, is the source of this issue. Certain websites use this response for requests they prefer to ignore, such as automated queries. The difference between HTTP Status Codes 400 and 418 is that the 400 HTTP Status Code indicates that due to insufficient syntax, the server was unable to recognize the request, whereas the 418 HTTP Status Code indicates that The server declines to attempt coffee brewing using a teapot.

What does 418 HTTP Status Code Mean?

The 418 HTTP Status Code means I’m a teapot, indicating that any attempt to brew coffee in a teapot should generate the error 418 I’m a teapot. There may be a body for the entity that is short and stout.

How to Use 418 HTTP Status Codes for a Website?

To use the 418 HTTP Status Code is when the teapots that are asked to brew coffee should return the response code.

How to Check 418 HTTP Status Code?

Which HTTP Method is used with 418 HTTP Status Codes?

There is only one HTTP Method used with 418 HTTP Status Code which is the TRACE HTTP Method. The TRACE HTTP Method is the message body, which contains the server’s response to the request message.

There is a related HTTP Response Header with 418 HTTP Status Code which is the 417 HTTP Status Code. The 417 Expectation Failed HTTP Status Code is similar to the 418 HTTP Status Code because they are both client error responses. The 417 HTTP Status Code means the server is unable to fulfill the expectation specified in the Expect request header field.

What is the Browsers Compatibility of 418 HTTP Status Code?

The 418 HTTP Status Code is compatible with all browsers including Chrome, Edge, Firefox, Internet Explorer, Opera, Safari, and Web view Android. 

What are the other Similar Status Codes to the 418 HTTP Status Codes?

There are other similar HTTP Status Codes to the 418 HTTP Status codes. The following are listed below.

  • 414 URI Too Long HTTP Status Code: The 414 HTTP Status Code is similar to the 418 HTTP Status Code because they are both client error responses. The 414 HTTP Status Code indicates that the client’s URI request is longer than the server will interpret.
  • 415 Unsupported Media Type HTTP Status Code: The 415 HTTP Status Code is similar to the 418 HTTP Status Code because they are both client error responses. The 415 HTTP Status Code indicates that the server does not support the requested media format, hence it rejects the request.
  • 416 Range Not Satisfiable HTTP Status Code: The 416 HTTP Status Code is similar to the 418 HTTP Status Code because they are both client error responses. The 416 HTTP Status Code indicates the range specified in the request’s Range header field cannot be accomplished. It is possible that the range is greater than the data size of the target URI.
  • 421 Misdirected Request HTTP Status Code:  The 421 HTTP Status Code is similar to the 418 HTTP Status Code because they are both client error responses. The 418 HTTP Status Code indicates that The request was sent to a server that can’t give an answer. This can be issued by a server that is not configured to respond to the request URI’s combination of scheme and authority.
  • Author
  • Recent Posts

Holistic SEO

Holistic SEO & Digital has been built by Koray Tuğberk GÜBÜR. Holistic SEO is the process of developing integrated digital marketing projects with every aspect including Coding, Natural Language Processing, Data Science, Page Speed, Digital Analytics, Content Marketing, Technical SEO, and Branding. Structured, Semantic Search Engine improves its ability to detect the real-world entities, today. Having a simple website is not enough anymore. To show that your brand is authoritative, trustworthy, and expert on its own niche, you need entity-based Search Engine Optimization Projects. Holistic SEO & Digital’s main focus is on improving the brand’s organic visibility and growth potential.

Holistic SEO

Понравилась статья? Поделить с друзьями:
  • Как вызвать ошибку 404 на сайте
  • Как вызвать ошибку 404 django
  • Как вызвать ошибку 403
  • Как вызвать звук ошибки windows
  • Как вызвать 500 ошибку специально