home.social

#httpx — Public Fediverse posts

Live and recent posts from across the Fediverse tagged #httpx, aggregated by home.social.

fetched live
  1. Yeah, so with #httpx being forked into httpx2, different projects are adapting different strategies. Some are straightaway replacing httpx with httpx2. Others support both. Even others are rebuilt or forked against httpx2.

    So someone decided to build pytest-httpx2 which is a httpx2 hack over respx. Except that respx still requires httpx, so you effectively pull both httpx and httpx2 as a result.

    Then someone decided they want a plain fork of pytest-httpx for httpx2. But since pytest-httpx2 was taken, the "obvious" thing to do was to make httpx2-pytest.

    Obviously there's zero confusion to be had here.

    pypi.org/project/pytest-httpx2/
    pypi.org/project/httpx2-pytest/

    #Python

  2. Почему 200 OK врёт: что я переделал в проверке доступности сайтов

    Задача казалась простой: раз в минуту сходить на сайт и сказать, работает он или нет. Первая версия уместилась в десяток строк: GET, проверка кода ответа, уведомление в Telegram. Через неделю оказалось, что почти каждая из этих строк врёт. Рассказываю, что пришлось переделать: как отличить «сайт упал» от «у меня сломалась сеть», почему код 200 ещё не значит «работает», как убрать ложные тревоги и не опоздать с настоящей аварией и как не дать проверке ходить во внутреннюю сеть через редиректы. Где ещё врёт простая проверка

    habr.com/ru/articles/1105846/

    #python #sqlite #ложные_срабатывания #мониторинг_сайтов #ssrf #asyncio #dns_rebinding #httpx #проверка_доступности

  3. Дело не в нагрузке: почему пул httpx теряет соединения при отменах

    PoolTimeout, когда свободные соединения вроде бы есть, и медленный рост busy при ровном RPS — знакомые симптомы? Причина может быть не в нагрузке, а в отмене запроса при закрытии ответа: в httpcore соединение остаётся в состоянии ACTIVE, а закрыть его повторно уже некому. В статье — диагностика по состоянию пула, минимальное воспроизведение и варианты исправления, пока фикса в upstream нет.

    habr.com/ru/companies/domclick

    #httpx

  4. Test FastAPI in-process with pytest-asyncio and httpx.AsyncClient over ASGITransport—no sockets—plus a coverage gate. One command, fast CI. #python #pytest #httpx valtersit.com/vault/run-fastap

  5. Check a fleet of HTTP services at once with 256 lines of async Python. Beginner-level httpx script, YAML config, JSON output. #python #monitoring #httpx valtersit.com/python/http-endp

  6. CERTIFICATE_VERIFY_FAILED на российском API: как доверять сертификату Минцифры только в одном клиенте Python

    Сервер российского API подписан цепочкой Минцифры, и Python падает с CERTIFICATE_VERIFY_FAILED. Показываю, как доверять этому сертификату ровно в одном клиенте: свой SSLContext, промежуточный сертификат как якорь и флаг VERIFY_X509_PARTIAL_CHAIN, без verify=False и без корня в системе. Чем рискуешь с этим флагом, как то же сделать в aiohttp, httpx, requests и urllib, как сверить отпечаток и что делать при смене сертификата.

    habr.com/ru/articles/1102026/

    #python #ssl #tls #openssl #x509 #requests #aiohttp #httpx #сертификаты_минцифры #certificate_verify_failed

  7. Первый запрос проходит, второй падает: почему TestClient ломает тесты FastAPI и как это исправить

    Первый запрос к FastAPI возвращает 200, второй падает с ошибкой asyncpg. При этом под uvicorn всё работает. Причина может быть в событийных циклах, которыми управляет TestClient . Разберёмся, откуда берётся ошибка, как её исправить и какие ещё особенности тестового клиента стоит учитывать. Настроить тесты

    habr.com/ru/companies/otus/art

    #python #асинхронное_программирование #pytest #тестирование_api #asgi #fastapi #httpx #testclient #событийный_цикл #отладка_ошибок

  8. Как я написал кросспостер из Telegram в VK и MAX на Python: парсинг UTF-16, обход API и SQLite-очередь

    Как я написал кросспостер из Telegram в VK и MAX на Python: парсинг UTF-16, обход API и SQLite-очередь После настройки единого рабочего окна для переписки с учениками в Chatwoot, о котором я рассказывал в предыдущих статьях, встал вопрос ведения каналов. Писать анонсы, полезные материалы по математике или новости проекта приходится регулярно, и делать это сразу в трёх местах (Telegram, сообщество ВКонтакте и MAX) вручную — слишком утомительно. Готовые сервисы автопостинга либо стоят неоправданно дорого для небольшого проекта, либо не поддерживают MAX. Поэтому я написал свой кросспостер на Python (на базе httpx и SQLite ), который слушает мой Telegram-канал через long polling и автоматически публикует посты в VK и MAX. Теги: Telegram API, ВКонтакте, MAX API, Python, SQLite, автопостинг, кросспостинг, боты

    habr.com/ru/articles/1092594/

    #кросспостинг #python #sqlite #мессенджеры #vk_api #автопостинг #telegram_api #telethon #httpx #max_api

  9. async def или def в FastAPI: как одна строчка делает сервис в 40 раз медленнее

    В FastAPI можно объявить обработчик как async def , а можно как обычный def . Многие ставят async везде «потому что так быстрее» и спокойно вызывают внутри requests.get() или синхронный драйвер БД. Сервис при этом работает, тесты проходят, а на первой же реальной нагрузке всё встаёт колом, причём вместе с health‑check'ом. В статье разберу, что на самом деле происходит с каждым вариантом, покажу замеры и дам короткую шпаргалку, какой вариант выбирать.

    habr.com/ru/articles/1083864/

    #python #asyncio #fastapi #eventloop #threadpool #производительность #httpx #requests #uvicorn #блокирующий_код

  10. Tired of slow sequential API tests? Async API Test Suite with httpx runs integration tests in parallel. 104 lines, intermediate level, pytest-based. valtersit.com/python/async-api #python #testing #httpx

  11. Please check this nice migration guide for httpx to httpx2: httpx2.pydantic.dev/migration/

  12. httpx2 2.6.0 -- everyones favorite Python http client -- is out now! It includes native websocket support and also support for the brand new QUERY method for HTTP, and of course again bug fixes.

    If you did not upgrade yet from httpx, now is the time!
    --> github.com/pydantic/httpx2/rel

  13. Мой мониторинг аптайма сам нагенерил 932 фантомных падения

    2 июня мой мониторинг аптайма разом отрапортовал, что упало почти всё: 932 инцидента за 25 минут. Сайты были живы — все до единого. Виноваты дефолтный лимит файловых дескрипторов 1024 и «оптимизация», тихо размножившаяся в 60 раз. Разбираю по приборам: /proc, ss, EMFILE и почему docker compose restart не спасает.

    habr.com/ru/articles/1052038/

    #EMFILE #ulimit #nofile #file_descriptors #Docker #httpx #connection_pool #FastAPI #postmortem #мониторинг

  14. Tilda и СБИС Presto: как мы синхронизируем остатки через стоп-лист, а не каталог

    Как мы избавили общепит от часа ручной работы каждое утро: разобрали реальный кейс синхронизации стоп-листа из СБИС Presto в каталог на Tilda через CommerceML. Поток на Python/FastAPI, дебаунс через SHA-256, eventual consistency без очередей и грабли, на которые наступили в проде. Решение и грабли

    habr.com/ru/articles/1043428/

    #python #fastapi #tilda #сбис #commerceml #интеграция #httpx #presto #синхронизация_остатков

  15. Tilda + СБИС Presto: пишем интеграцию на Python, когда готового решения не существует

    Клиент пришёл с простой задачей: заказы с сайта на Tilda должны автоматически попадать в СБИС Presto. Казалось бы, популярные инструменты — должно быть готовое решение. Его не оказалось. Написали свой сервис месяц в продакшене, всё работает. Рассказываем как — с кодом, граблями и объяснением неочевидных мест в документации СБИС. Стек: Python, FastAPI, Pydantic, httpx, cachetools.

    habr.com/ru/articles/1030324/

    #python #fastapi #сбис #tilda #webhook #интеграция #pydantic #httpx #presto

  16. There's a new piece explaining "The Slow Collapse of #MkDocs": "How personality clashes, an absent founder, and a controversial redesign fractured one of Python's most popular projects."

    fpgmaas.com/blog/collapse-of-m

    Well, that says a lot. But what's really interesting is that MkDocs 2.x is being developed as part of the "encode" organization. That's great, right? The people who gave us such great libraries as #httpx?

    Well, turns out no, not at all. It looks like encode has already crumbled and became immensely toxic.

    httpx is not allowing bug reports anymore, apparently because of "absurdly skewed gender representation", whatever that means.

    web.archive.org/web/2026022811

    That also explained why starlette moved out of the organization a while back:

    web.archive.org/web/2026032304

    There's a great rot in #OpenSource.

    #FreeSoftware #Python

  17. Hey, in light of github.com/encode/httpx/discus , does anyone know of how to get in touch or give feedback?

    I guess there's a stackoverflow tag

    #Python #HTTPX

  18. Ok, I got a #Python #HTTPX problem.

    I have a few custom httpx.Auth implementations, but I want them to pull from some common flows--namely GitHub Actions get-an-OIDC.

    In the standard form, you can just use `yield from`, and then requests and responses get shuffled around correctly, and you can just be like `token = yield from do_github()`

    but then I need to do non-http async things, and it all gets messy.

    because async generator can't use `yield from`, and all i've got is manual pumping.

  19. HTTPX is a nice Python HTTP client. Here is a comparison of HTTPX synchronous and asynchronous clients.

    gavinw.me/notes/python/httpx-s

  20. Httpx:platzierungen được khoanh sát là kliện HTTP hiện đại cho các lập trình viên. Với hỗ trợ nguyên thủy cho async và sync, nó cung cấpישית tiện khả năng gia tăng hiệu suất và dễ dàng trong việc quản lý các yếu cầu HTTP. Hưởng thuện sử dụng nhu soi nhất ở ganado khác nhau, nâng cấp trải nghiệm phát triển python. #Httpx #KliệnHTTP #LậpTrình #Python #TechNews

    reddit.com/r/programming/comme

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

    Когда в 1991 году Гвидо ван Россум представил миру Python, никто не мог предсказать, какое место через несколько десятилетий этот язык займет в веб-разработке, Data Science и Machine Learning. Сейчас Python продолжает развиваться: с новым поколением инструментов в прошлое уходят традиционные ограничения — производительность, GIL и сложность параллельных вычислений. Привет, Хабр! С вами Леша Жиряков, я руковожу бэкенд-направлением витрины KION, возглавляю гильдию по Python и пишу для блога MWS на Хабре. Я каждый день сталкиваюсь с вызовами высоконагруженных систем и сформировался пул инструментов, которые помогают решать критические проблемы современной разработки — от обработки данных с Polars до управления зависимостями с UV. В этом материале я сделаю обзор Python-библиотек, с которыми можно создавать системы, сравнимые по производительности с Go и Rust.

    habr.com/ru/companies/ru_mts/a

    #библиотеки #python #fastapi #litestar #polars #httpx #dask #Pydantic_V2 #ruff #Pithon_UV

  22. In today's electrifying episode of "Overcomplicate Your Life," we've got the Fiber Concurrency plugin, because who doesn't want to juggle fibers like a circus clown while their code hangs by a thread? 🎪🤹‍♂️ Apparently, if you're using #HTTPX, this is your golden ticket to a world where "seamless" means "good luck!" 🍀
    honeyryderchuck.gitlab.io/http #OvercomplicateYourLife #FiberConcurrency #CodingJuggling #CircusClown #HackerNews #ngated

  23. Асинхронные тесты для UI и API на Python: примеры, подводные камни и трезвый вывод

    Асинхронность в тестах выглядит как способ «бесплатно» ускорить прогон: пока один тест ждёт ответа сервера, другой мог бы выполняться. Я переписал UI (Playwright) и API (HTTPX) тесты на async/await, прогнал их в CI/CD и посмотрели на результат. Спойлер: магического ускорения не произошло — разбираемся, почему так и когда асинхронность всё-таки нужна.

    habr.com/ru/articles/933652/

    #тестирование #pytest #async #asyncio #api_тестирование #ui_тестирование #python #httpx #playwright #qa_automation

  24. Нагрузочное тестирование на Python и Locust с запуском на CI/CD

    Разбираемся, как организовать нагрузочное тестирование на Python с Locust — с сидинговыми сценариями , кастомными API-клиентами на HTTPX, конфигурацией через Pydantic и автоматическим запуском в GitHub Actions . Всё — на практике, с архитектурой, фреймворком и публикацией отчётов в GitHub Pages.

    habr.com/ru/articles/929136/

    #нагрузка #нагрузочное_тестирование #нагрузочные_тесты #python #locust #тестирование_производительности #cicd #github_actions #httpx #pydantic

  25. I'm super excited about @thom's preview of the upcoming 1.0 of HTTPX. It's shaping up to be the Python HTTP toolkit I always wanted.

    Just go look at that server example on the homepage. And it gets better from there. 🥰

    encode.io/httpnext/ #Python #HTTP #HTTPX

  26. State of client side HTTP in #python

    - stdlib http.client - HTTP/1.1 only, docs recommend to use requests instead.
    - requests - poorly maintained, in 2020 stopped working when servers deprecated older TLS versions. HTTP/1.1 only, sync only
    - #httpx - comparatively slow and API design is driven by compatibility with browsers. Some users plug-in aiohttp for better performance. Supports HTTP/2 but it's discouraged as not optimized.
    - #aiohttp - good API, both client and server but seems more focused on the server side; HTTP/1.1 only.
    - #niquests - async fork of requests with HTTP/2, but uses forked urllib3 with the same package name as the original, which messes up deployment.
    - #aioquic - client & server, HTTP/3 only

    🤦

    #pythonRequests #programming

  27. Did some benchmarking of how fast #Python (3.13) w/ async #httpx and #Pydantic could query a JSON API vs. #GoLang (both including unmarshalling to native types and some regex validation).

    While Python could do about 2.5k requests per second against localhost when running singlecore, Go did 10k.

    However, not only is Go "only" 4× as fast, these differences quickly shrink to 30 % when you introduce an actual network between the hosts, and become irrelevant with rate limiting & DDoS protection.

  28. The #Python requests lib feels dead. So, with little effort, we switched to #httpx: github.com/cusyio/Python4DataS

    See also ‘A Retrospective on Requests’ by @sigmavirus24: blog.ian.stapletoncordas.co/20

    You can find more information about switching to httpx in the ‘Requests Compatibility Guide’: python-httpx.org/compatibility

  29. LB: making stuff "for humans" (which IIRC is the "art statement" behind #requests) is a noble goal. And if the tool is the #1 download on pypi that means there's an actual appeal to that and I'd go as far as to say that "artful" stuff like that, even if a bit toy-like, is (partially, at least) responsible for Python's popularity. #Httpx API even follows somewhat the same ethos but with better engineering, it seems.

  30. My favourite #ruby http library turned 1.0.

    Congratulations #httpx 🎉

    gitlab.com/os85/httpx

  31. Played around with httpx and respx this weekend. Can thoroughly recommend respx for mocking httpx calls.

    github.com/lundberg/respx

    #Python #httpx #respx

Share on Mastodon

Enter the server where you have an account.