An independent #rust text editor that runs in your terminal!
Ox is a code editor. It was written in Rust using ANSI escape sequences. It assists developers with programming by providing several tools to speed up and make programming easier and a refreshing alternative to heavily bloated and resource hungry editors such as VS Code and JetBrains. Ox is lightweight so it can be used on older computers.
Bear in mind, this is a personal project and is nowhere near ready to replace your existing tools just yet.
It runs in the terminal and runs on platforms like Linux and macOS but doesn't work on Windows directly (it works if you use WSL) due to a lack of a good command line. There are many text editors out there and each one of them has their flaws and I hope to have a text editor that overcomes many of the burdens and issues.
Ox is not based on any other editor and has been built from the ground up without any base at all.
https://github.com/curlpipe/ox
Ox is a code editor. It was written in Rust using ANSI escape sequences. It assists developers with programming by providing several tools to speed up and make programming easier and a refreshing alternative to heavily bloated and resource hungry editors such as VS Code and JetBrains. Ox is lightweight so it can be used on older computers.
Bear in mind, this is a personal project and is nowhere near ready to replace your existing tools just yet.
It runs in the terminal and runs on platforms like Linux and macOS but doesn't work on Windows directly (it works if you use WSL) due to a lack of a good command line. There are many text editors out there and each one of them has their flaws and I hope to have a text editor that overcomes many of the burdens and issues.
Ox is not based on any other editor and has been built from the ground up without any base at all.
https://github.com/curlpipe/ox
Fast, consistent builds for Python and more. Pants v2 is a fast, scalable build system for growing codebases. It's currently focused on Python, with support for other languages coming soon.
> Installing, configuring and orchestrating the invocation of Python build tools like flake8, mypy, or tox—all while not re-executing work unnecessarily—is a hard problem, especially as your codebase grows. The lack of a robust, scalable build system for Python has been a problem for a long time, and this has become even more acute in recent years, with Python codebases increasing in size and complexity.
Some noteworthy features include:
- Minimal metadata and boilerplate
- Fine-grained workflow
- Shared result caching
- Concurrent execution
- A responsive, scalable UI
- Unified interface for multiple tools and languages
- Extensibility and customizability via a plugin API
https://www.pantsbuild.org/
Announcement: https://blog.pantsbuild.org/introducing-pants-v2/
Written in #python and #rust
> Installing, configuring and orchestrating the invocation of Python build tools like flake8, mypy, or tox—all while not re-executing work unnecessarily—is a hard problem, especially as your codebase grows. The lack of a robust, scalable build system for Python has been a problem for a long time, and this has become even more acute in recent years, with Python codebases increasing in size and complexity.
Some noteworthy features include:
- Minimal metadata and boilerplate
- Fine-grained workflow
- Shared result caching
- Concurrent execution
- A responsive, scalable UI
- Unified interface for multiple tools and languages
- Extensibility and customizability via a plugin API
https://www.pantsbuild.org/
Announcement: https://blog.pantsbuild.org/introducing-pants-v2/
Written in #python and #rust
Fuzzy Finder in #rust!
Half of our life is spent on navigation: files, lines, commands, etc. You need skim! It is a general fuzzy finder that saves you time. skim provides a single executable: sk. Basically anywhere you would want to use grep, try sk instead.
https://github.com/lotabout/skim
Half of our life is spent on navigation: files, lines, commands, etc. You need skim! It is a general fuzzy finder that saves you time. skim provides a single executable: sk. Basically anywhere you would want to use grep, try sk instead.
https://github.com/lotabout/skim
Command-line DNS #rust client
Dogs can look up!
dog is a command-line DNS client, like dig. It has colourful output, understands normal command-line argument syntax, supports the DNS-over-TLS and DNS-over-HTTPS protocols, and can emit JSON.
https://github.com/ogham/dog
Dogs can look up!
dog is a command-line DNS client, like dig. It has colourful output, understands normal command-line argument syntax, supports the DNS-over-TLS and DNS-over-HTTPS protocols, and can emit JSON.
https://github.com/ogham/dog
Fast and simple Node #js version manager, built in #rust
Features:
- Cross-platform support (Mac, Windows, Linux)
- Single file, easy installation, instant startup
- Built with speed in mind
- Works with
https://github.com/Schniz/fnm
Features:
- Cross-platform support (Mac, Windows, Linux)
- Single file, easy installation, instant startup
- Built with speed in mind
- Works with
.node-version and .nvmrc fileshttps://github.com/Schniz/fnm
Type-safe, compiled Jinja-like templates for #rust
Askama implements a template rendering engine based on Jinja. It generates Rust code from your templates at compile time based on a user-defined struct to hold the template's context.
Feature highlights:
- Construct templates using a familiar, easy-to-use syntax
- Template code is compiled into your crate for optimal performance
- Benefit from the safety provided by Rust's type system
- Optional built-in support for Actix, Gotham, Iron, Rocket, tide, and warp web frameworks
- Debugging features to assist you in template development
- Templates must be valid UTF-8 and produce UTF-8 when rendered
- Works on stable Rust
https://github.com/djc/askama
Askama implements a template rendering engine based on Jinja. It generates Rust code from your templates at compile time based on a user-defined struct to hold the template's context.
Feature highlights:
- Construct templates using a familiar, easy-to-use syntax
- Template code is compiled into your crate for optimal performance
- Benefit from the safety provided by Rust's type system
- Optional built-in support for Actix, Gotham, Iron, Rocket, tide, and warp web frameworks
- Debugging features to assist you in template development
- Templates must be valid UTF-8 and produce UTF-8 when rendered
- Works on stable Rust
https://github.com/djc/askama
An incremental parsing system for programming tools written in #rust
Tree-sitter is a parser generator tool and an incremental parsing library. It can build a concrete syntax tree for a source file and efficiently update the syntax tree as the source file is edited.
Tree-sitter aims to be:
- General enough to parse any programming language
- Fast enough to parse on every keystroke in a text editor
- Robust enough to provide useful results even in the presence of syntax errors
- Dependency-free so that the runtime library (which is written in pure C) can be embedded in any application
https://github.com/tree-sitter/tree-sitter
Tree-sitter is a parser generator tool and an incremental parsing library. It can build a concrete syntax tree for a source file and efficiently update the syntax tree as the source file is edited.
Tree-sitter aims to be:
- General enough to parse any programming language
- Fast enough to parse on every keystroke in a text editor
- Robust enough to provide useful results even in the presence of syntax errors
- Dependency-free so that the runtime library (which is written in pure C) can be embedded in any application
https://github.com/tree-sitter/tree-sitter
GitHub
GitHub - tree-sitter/tree-sitter: An incremental parsing system for programming tools
An incremental parsing system for programming tools - tree-sitter/tree-sitter
My new article is out! It is all about typeclasses in Python and
Today I am explaining what typeclasses are and how to use them. I give examples in 4 very different languages: #rust, #elixir, #haskell, and #python to show that this concept is universal.
I am also showing that this idea is very pythonic by comparing our
Check how easy it is to define a typeclass with
Check it out!
dry-python/classes.Today I am explaining what typeclasses are and how to use them. I give examples in 4 very different languages: #rust, #elixir, #haskell, and #python to show that this concept is universal.
I am also showing that this idea is very pythonic by comparing our
classes implementation with functools.singledispatch. There are lots of different details!Check how easy it is to define a typeclass with
classes: from classes import AssociatedType, Supports, typeclass
class Greet(AssociatedType):
"""Special type to represent that some instance can `greet`."""
@typeclass(Greet)
def greet(instance) -> str:
"""No implementation needed."""
@greet.instance(str)
def _greet_str(instance: str) -> str:
return 'Hello, {0}!'.format(instance)
def greet_and_print(instance: Supports[Greet]) -> None:
print(greet(instance))
greet_and_print('world')
Check it out!
Flix: Next-generation reliable, safe, concise, and functional-first programming language.
Flix is inspired by OCaml and Haskell with ideas from Rust and Scala. Flix looks like Scala, but its type system is based on Hindley-Milner. Two unique features of Flix are its polymorphic effect system and its support for first-class Datalog constraints.
Flix aims to offer a unique combination of features that no other programming language offers, including: algebraic data types and pattern matching (like Haskell, OCaml), extensible records (like Elm), type classes (like #haskell, #rust), higher-kinded types (like Haskell), local type inference (like Haskell, OCaml), channel and process-based concurrency (like #go), a polymorphic effect system (unique feature), first-class Datalog constraints (unique feature), and compilation to JVM bytecode (like #scala).
https://flix.dev/
Personal opinion: it has all the features new modern programming language should have. It has nice syntax, powerful ideas, and (hopefully) good JVM integration and code-reuse. That's a recipe for a success. I will keep an eye on this amazing language.
It also has a playground on its website, check it out!
I would love to highlight this example of polymorphic effects:
Flix is inspired by OCaml and Haskell with ideas from Rust and Scala. Flix looks like Scala, but its type system is based on Hindley-Milner. Two unique features of Flix are its polymorphic effect system and its support for first-class Datalog constraints.
Flix aims to offer a unique combination of features that no other programming language offers, including: algebraic data types and pattern matching (like Haskell, OCaml), extensible records (like Elm), type classes (like #haskell, #rust), higher-kinded types (like Haskell), local type inference (like Haskell, OCaml), channel and process-based concurrency (like #go), a polymorphic effect system (unique feature), first-class Datalog constraints (unique feature), and compilation to JVM bytecode (like #scala).
https://flix.dev/
Personal opinion: it has all the features new modern programming language should have. It has nice syntax, powerful ideas, and (hopefully) good JVM integration and code-reuse. That's a recipe for a success. I will keep an eye on this amazing language.
It also has a playground on its website, check it out!
I would love to highlight this example of polymorphic effects:
Rust Memory Safety & Undefined Behavior Detection.
Rudra is a static analyzer to detect common undefined behaviors in #rust programs. It is capable of analyzing single Rust packages as well as all the packages on crates.io.
Features:
- Panic Safety (Unsafe code that can create memory-safety issues when panicked)
- Higher Order Invariant (Assumed properties about traits)
- Send Sync Variance (Unrestricted Send or Sync on generic types)
https://github.com/sslab-gatech/Rudra
Rudra is a static analyzer to detect common undefined behaviors in #rust programs. It is capable of analyzing single Rust packages as well as all the packages on crates.io.
Features:
- Panic Safety (Unsafe code that can create memory-safety issues when panicked)
- Higher Order Invariant (Assumed properties about traits)
- Send Sync Variance (Unrestricted Send or Sync on generic types)
https://github.com/sslab-gatech/Rudra
GitHub
GitHub - sslab-gatech/Rudra: Rust Memory Safety & Undefined Behavior Detection
Rust Memory Safety & Undefined Behavior Detection. Contribute to sslab-gatech/Rudra development by creating an account on GitHub.
#rust 1.55 is here.
New features:
- Cargo deduplicates compiler errors
- Faster, more correct float parsing
- std::io::ErrorKind variants updated
- Open range patterns added
https://blog.rust-lang.org/2021/09/09/Rust-1.55.0.html
New features:
- Cargo deduplicates compiler errors
- Faster, more correct float parsing
- std::io::ErrorKind variants updated
- Open range patterns added
https://blog.rust-lang.org/2021/09/09/Rust-1.55.0.html
TODOs you cannot forget!
In the Bad Old Days™, if you had a bit of code you knew you needed to change later, you might leave yourself a code comment to remind yourself to change it. For example, here's the real world code comment that inspired this method:
This was bad. The comment did nothing to remind myself or anyone else to actually delete the code. Because no one was working on this part of the system for a while, the continued existence of the redirect eventually resulted in an actual support incident (long story).
To use it, try replacing one of your TODO comments with something like this:
Nothing will happen at all until February 4th, at which point the gem will raise an error whenever this class is loaded until someone deals with it.
#ruby: https://github.com/searls/todo_or_die
#rust: https://github.com/davidpdrsn/todo-or-die
In the Bad Old Days™, if you had a bit of code you knew you needed to change later, you might leave yourself a code comment to remind yourself to change it. For example, here's the real world code comment that inspired this method:
class UsersController < ApiController
# TODO: remember to delete after JS app has propagated
def show
redirect_to root_path
end
end
This was bad. The comment did nothing to remind myself or anyone else to actually delete the code. Because no one was working on this part of the system for a while, the continued existence of the redirect eventually resulted in an actual support incident (long story).
To use it, try replacing one of your TODO comments with something like this:
class UsersController < ApiController
TodoOrDie("delete after JS app has propagated", by: "2019-02-04")
def show
redirect_to root_path
end
end
Nothing will happen at all until February 4th, at which point the gem will raise an error whenever this class is loaded until someone deals with it.
#ruby: https://github.com/searls/todo_or_die
#rust: https://github.com/davidpdrsn/todo-or-die
Like jq, but for HTML. Uses CSS selectors to extract bits of content from HTML files.
https://github.com/mgdm/htmlq
#rust
https://github.com/mgdm/htmlq
#rust
KDL is a document language with xml-like semantics that looks like you're invoking a bunch of CLI commands! It's meant to be used both as a serialization format and a configuration language, much like JSON, YAML, or XML.
Features:
- Node-based, you won't have to mess with identation to make it work
- Type annotations
- Implementations in different languages: #python, #elixir, #rust, #java, #js, #ruby, #php, etc
https://kdl.dev/
Features:
- Node-based, you won't have to mess with identation to make it work
- Type annotations
- Implementations in different languages: #python, #elixir, #rust, #java, #js, #ruby, #php, etc
https://kdl.dev/
Flowistry is a VSCode extension that helps you understand #rust programs with program analysis.
Flowistry uses dataflow analysis and pointer analysis to analyze Rust programs at a deeper level than just types can offer (e.g. as you can already find in rust-analyzer).
Flowistry has five commands:
- Flowistry: Backward Highlight: given a selected variable, this command highlights the backward slice of the variable.
- Flowistry: Backward Select: same as above, but this puts the slice in your selection rather than highlighting it.
- Flowistry: Forward Highlight and Flowistry: Forward Select: same as above, but for forward slices than backward slices.
- Flowistry: Effects: given your cursor is within a particular function, this command opens the effects panel for that function.
https://github.com/willcrichton/flowistry
Flowistry uses dataflow analysis and pointer analysis to analyze Rust programs at a deeper level than just types can offer (e.g. as you can already find in rust-analyzer).
Flowistry has five commands:
- Flowistry: Backward Highlight: given a selected variable, this command highlights the backward slice of the variable.
- Flowistry: Backward Select: same as above, but this puts the slice in your selection rather than highlighting it.
- Flowistry: Forward Highlight and Flowistry: Forward Select: same as above, but for forward slices than backward slices.
- Flowistry: Effects: given your cursor is within a particular function, this command opens the effects panel for that function.
https://github.com/willcrichton/flowistry
Seed is a #rust front-end framework for creating fast and reliable web apps with an Elm-like architecture.
Seed allows you to develop the front-end with all the benefits of Rust, meaning speed, safety, and too many more things to count.
The Seed templating system uses a macro syntax that makes Rustaceans feel right at home. This means linting, formatting, and commenting will work, and it's all in Rust. This is opposed to a JSX-like syntax that relies on IDE extensions to improve the developer experience.
Seed has a batteries-included approach. This means less time writing boilerplate and less time installing dependencies.
Features
- completely written in Rust, including the templating system (e.g.
- built-in state management that is based on the Elm architecture.
- a batteries-included approach with a focus on developer experience.
- clear and extensive documentation for Rust beginners and pros alike.
- WebAssembly.
https://github.com/seed-rs/seed
Seed allows you to develop the front-end with all the benefits of Rust, meaning speed, safety, and too many more things to count.
The Seed templating system uses a macro syntax that makes Rustaceans feel right at home. This means linting, formatting, and commenting will work, and it's all in Rust. This is opposed to a JSX-like syntax that relies on IDE extensions to improve the developer experience.
Seed has a batteries-included approach. This means less time writing boilerplate and less time installing dependencies.
Features
- completely written in Rust, including the templating system (e.g.
div! macro).- built-in state management that is based on the Elm architecture.
- a batteries-included approach with a focus on developer experience.
- clear and extensive documentation for Rust beginners and pros alike.
- WebAssembly.
https://github.com/seed-rs/seed
A #rust graphical tool to visualize binary data.
It colorizes bytes according to different rules and renders them as pixels in a rectangular grid. This allows users to identify interesting parts in large files and to reveal image-like regions.
The program allows you to control various parameters like the offset into the file, the stride, the width of the rectangular grid as well as the way in which (groups of) bytes are colorized.
https://github.com/sharkdp/binocle
It colorizes bytes according to different rules and renders them as pixels in a rectangular grid. This allows users to identify interesting parts in large files and to reveal image-like regions.
The program allows you to control various parameters like the offset into the file, the stride, the width of the rectangular grid as well as the way in which (groups of) bytes are colorized.
https://github.com/sharkdp/binocle
Статический анализ GitHub Actions
Сразу после релиза новой версии линтера, я задался вопросом обновления своего шаблона для создания новых питоновских библиотек: https://github.com/wemake-services/wemake-python-package
И я понял, что я несколько отстал в вопросе стат анализа GitHub Actions и прочей инфраструктуры.
Расскажу о своих находках.
pre-commit ci
Все знают про пакет pre-commit? Несколько лет назад он получил еще и свой собственный CI, который умеет запускаться без дополнительного конфига. И автоматически пушить вам в ветку любые изменения. Что супер удобно для всяких
Строить CI на базе
- Автоматически исправляются многие проблемы
- Автоматически запускается CI, 0 настроек
- Локально все тоже работает одной командой:
actionlint
Первый раз я увидел
Даже умеет автоматом shellcheck запускать на ваши
zizmor
Исходники. Уже на #rust, он более злой. Делает похожие вещи: находит проблемы безопасности. Находит много проблем.
Вот пример, сколько всего он нашел в mypy.
check-jsonschema
Еще есть вот такой проект, он в основном полезен за счет доп интеграций: можно проверять
Ставится просто как:
Выводы
Как всегда – статический анализ многому меня научил. Я узнал много нового про безопасность GitHub Actions, про вектора атаки, про лучшие практики. А сколько проблем в ваших actions?
Скоро ждите весь новый тулинг в python шаблоне
Сразу после релиза новой версии линтера, я задался вопросом обновления своего шаблона для создания новых питоновских библиотек: https://github.com/wemake-services/wemake-python-package
И я понял, что я несколько отстал в вопросе стат анализа GitHub Actions и прочей инфраструктуры.
Расскажу о своих находках.
pre-commit ci
Все знают про пакет pre-commit? Несколько лет назад он получил еще и свой собственный CI, который умеет запускаться без дополнительного конфига. И автоматически пушить вам в ветку любые изменения. Что супер удобно для всяких
ruff / black / isort и прочего. У нас такое стоит в большом количестве проектов. Вот пример из typeshed. Вот что поменялось автоматически. Строить CI на базе
pre-commit очень удобно, потому что тебе просто нужно скопировать пару строк в конфиг. А плюсов много:- Автоматически исправляются многие проблемы
- Автоматически запускается CI, 0 настроек
- Локально все тоже работает одной командой:
pre-commit run TASK_ID -aactionlint
Первый раз я увидел
actionlint внутри CPython и затащил его в mypy. Actionlint на #go, он предлагает набор проверок для ваших GitHub Actions от безопасности до валидации спеки вашего yml. Довольно полезно, позволяет найти много мест для улучшений.
test.yaml:3:5: unexpected key "branch" for "push" section. expected one of "branches", ..., "workflows" [syntax-check]
|
3 | branch: main
| ^~~~~~~
test.yaml:10:28: label "linux-latest" is unknown. available labels are "macos-latest", ..., "windows". if it is a custom label for self-hosted runner, set list of labels in actionlint.yaml config file [runner-label]
|
10 | os: [macos-latest, linux-latest]
| ^~~~~~~~~~~~~
test.yaml:13:41: "github.event.head_commit.message" is potentially untrusted. avoid using it directly in inline scripts. instead, pass it through an environment variable. see https://docs.github.com/en/actions/security-for-github-actions/security-guides/security-hardening-for-github-actions for more details [expression]
|
13 | - run: echo "Checking commit '${{ github.event.head_commit.message }}'"
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Даже умеет автоматом shellcheck запускать на ваши
run: скрипты!zizmor
Исходники. Уже на #rust, он более злой. Делает похожие вещи: находит проблемы безопасности. Находит много проблем.
Вот пример, сколько всего он нашел в mypy.
warning[artipacked]: credential persistence through GitHub Actions artifacts
--> mypy/.github/workflows/mypy_primer.yml:37:9
|
37 | - uses: actions/checkout@v4
| _________-
38 | | with:
39 | | path: mypy_to_test
40 | | fetch-depth: 0
| |________________________- does not set persist-credentials: false
|
= note: audit confidence → Low
error[dangerous-triggers]: use of fundamentally insecure workflow trigger
--> mypy/.github/workflows/mypy_primer_comment.yml:3:1
|
3 | / on:
4 | | workflow_run:
... |
7 | | types:
8 | | - completed
| |_________________^ workflow_run is almost always used insecurely
|
= note: audit confidence → Medium
check-jsonschema
Еще есть вот такой проект, он в основном полезен за счет доп интеграций: можно проверять
dependabot.yml, renovate.yml, readthedocs.yml и многое другое.Ставится просто как:
- repo: https://github.com/python-jsonschema/check-jsonschema
rev: 0.30.0
hooks:
- id: check-dependabot
- id: check-github-workflows
Выводы
Как всегда – статический анализ многому меня научил. Я узнал много нового про безопасность GitHub Actions, про вектора атаки, про лучшие практики. А сколько проблем в ваших actions?
Скоро ждите весь новый тулинг в python шаблоне
v2025 😎GitHub
GitHub - wemake-services/wemake-python-package: Bleeding edge cookiecutter template to create new python packages
Bleeding edge cookiecutter template to create new python packages - wemake-services/wemake-python-package
👍66❤16🤯7🔥5👎3😱1
Находки в опенсорсе: EasyP – тулбокс для ProtoBuf файлов
https://www.youtube.com/watch?v=XI-dNpM77iM
Хоть
Если много используете ProtoBuf – обязательно для ознакомления!
Как оно работает?
Прощайте огромные
Что будет в видео?
В видео:
- спросим зачем ребята его сделали
- узнаем как оно работает
- покажем, откуда можно устанавливать зависимости
- потыкаем разные юзкейсы
- поговорим про безопасность решения
- обсудим планы на следующие релизы
- расскажем как находить ломающие изменения в вашей ProtoBuf спецификации
А еще в видео кот на гитаре играет!
Репозиторий: https://github.com/easyp-tech/easyp
Документация: https://easyp.tech
Чатик сообщества: @easyptech
Поставьте пацанам звездочек, если проект понравился!
Обсуждение: Какие инструменты для ProtoBuf вы используете? Какие есть пролемы? Что можно было бы добавить в качестве новой фичи в easyp?
| Поддержать | YouTube | GitHub | Чат |
https://www.youtube.com/watch?v=XI-dNpM77iM
easyp – пакетный менеджер, билд-система и линтер для .proto файлов.Хоть
easyp и написан на #go 😱, одна из его фишек в том – что вы можете использовать любые плагины для генерации финального кода: он может быть хоть на #python, хоть на #rust.Если много используете ProtoBuf – обязательно для ознакомления!
Как оно работает?
# Секция для правил линтера:
lint:
use:
- DEFAULT
# Секция с зависимостями:
deps:
- github.com/googleapis/googleapis
- github.com/grpc-ecosystem/grpc-gateway@v2.20.0
# Секция для правил сборки и генерации итоговых файлов:
generate:
plugins:
- name: go
out: .
opts:
paths: source_relative
- name: go-grpc
out: .
opts:
paths: source_relative
require_unimplemented_servers: false
Прощайте огромные
Makefile с кучей скриптов для сборки.Что будет в видео?
В видео:
- спросим зачем ребята его сделали
- узнаем как оно работает
- покажем, откуда можно устанавливать зависимости
- потыкаем разные юзкейсы
- поговорим про безопасность решения
- обсудим планы на следующие релизы
- расскажем как находить ломающие изменения в вашей ProtoBuf спецификации
А еще в видео кот на гитаре играет!
Репозиторий: https://github.com/easyp-tech/easyp
Документация: https://easyp.tech
Чатик сообщества: @easyptech
Поставьте пацанам звездочек, если проект понравился!
Обсуждение: Какие инструменты для ProtoBuf вы используете? Какие есть пролемы? Что можно было бы добавить в качестве новой фичи в easyp?
| Поддержать | YouTube | GitHub | Чат |
YouTube
Находки в опенсорсе: EasyP – тулбокс для работы с ProtoBuf
- Мой телеграм канал: https://xn--r1a.website/opensource_findings
- Наш чат, где можно обсудить выпуск: https://xn--r1a.website/opensource_findings_chat
- Поддержать: https://boosty.to/sobolevn
- Мой GitHub: https://github.com/sobolevn
EasyP – тулбокс для работы с ProtoBuf файлами.…
- Наш чат, где можно обсудить выпуск: https://xn--r1a.website/opensource_findings_chat
- Поддержать: https://boosty.to/sobolevn
- Мой GitHub: https://github.com/sobolevn
EasyP – тулбокс для работы с ProtoBuf файлами.…
22❤28👍22🔥11🤯3
Зачем нужен новый REST API для Django?
Последний месяц я крайне увлечен созданием https://github.com/wemake-services/django-modern-rest
(Кстати, у нас уже >200 звезд и 26 контрибьюторов при 0 релизов)
Ключевой вопрос – зачем? Что будет нового?
Во-первых, я крайне сильно люблю Django. Основная причина – под него есть буквально любые библиотеки. Все то, что в FastAPI нужно героически писать руками – в джанге уже давно есть и работает.
Но, есть несколько основных причин, почему люди думают, что не любят джангу:
1. DRF, тут без лишних слов – он ужасен. Нет типизации, нет async, очень сложно работать с ним в сложных случаях
2. Многие считают, что джанга - сложная. Однако, она как FastAPI или Litestar может спокойно уместиться в один файл: https://django-modern-rest.readthedocs.io/en/latest/pages/micro-framework.html
3. Есть критика за архитектуру: тут нечего особо даже комментировать. На любом фреймворке можно писать хорошо, на любом можно писать плохо. Слой фреймворка очень тонкий
4. Медленный. А вот тут остановимся подробнее.
На скринах выше можно сравнить, что с
Во-вторых, Django на длительный срок был в плену DRF. Который морально устарел еще в середине десятых.
Потом появилась
Вот такие проблемы мы решаем.
Одной строкой:
- Супер строгая OpenAPI схема и валидация при разработке, что мы ее соблюдаем
- Полная типизация всего
- Нормальный способ создания АПИ, без god-functions a-la FastAPI
-
- Быстро:
- Пидантик,
- Полная поддержка всего существующего в Django. От декораторов до миддлварь (с полной валидацией и OpenAPI схемой!)
- OpenAPI схема из коробки
- Удобное тестирование с polyfactory
- property-based тесты вашего АПИ одной командой благодаря schemathesis
Что еще будет:
- RSGI (да, на #rust скорее всего) под granian, в теории можем побить FastAPI после такого
- SSE с автоматической OpenAPI спекой и умной валидацией схемы
- JWT или любая другая аутентификация
- Какие-то части (скорее всего валидацию) мы компильнем cython, чтобы было еще быстрее
Modern? Modern!
Осталось дождаться. Релиз скоро!
И еще скоро будут несколько новых видео.
Мы регулярно постим задачки в @opensource_findings_python, так что можно нам помочь.
А если кто хочет мне закинуть на развитие опенсорса (за написание 32500 строк кода за 2 недели), то мой бусти открыт: https://boosty.to/sobolevn
Ну и звезды можно ставить, конечно же. Там посмотрите, какие люди нас уже советуют.
Большое спасибо Александру, Алексею, Роману, Максиму и всем остальным за неоценимую помощь. Пацаны, без вас никак! Лучшее сообщество!
Обсуждение: а чего бы вам хотелось в modern rest фреймворке? Чего сильно не хватает сейчас?
Последний месяц я крайне увлечен созданием https://github.com/wemake-services/django-modern-rest
(Кстати, у нас уже >200 звезд и 26 контрибьюторов при 0 релизов)
Ключевой вопрос – зачем? Что будет нового?
Во-первых, я крайне сильно люблю Django. Основная причина – под него есть буквально любые библиотеки. Все то, что в FastAPI нужно героически писать руками – в джанге уже давно есть и работает.
Но, есть несколько основных причин, почему люди думают, что не любят джангу:
1. DRF, тут без лишних слов – он ужасен. Нет типизации, нет async, очень сложно работать с ним в сложных случаях
2. Многие считают, что джанга - сложная. Однако, она как FastAPI или Litestar может спокойно уместиться в один файл: https://django-modern-rest.readthedocs.io/en/latest/pages/micro-framework.html
3. Есть критика за архитектуру: тут нечего особо даже комментировать. На любом фреймворке можно писать хорошо, на любом можно писать плохо. Слой фреймворка очень тонкий
4. Медленный. А вот тут остановимся подробнее.
На скринах выше можно сравнить, что с
django-modern-rest, без нескольких будущих оптимизаций (привет cython и rust!), голая джанга начинает выглядеть не так уж и медленнее FastAPI: бенчи.Во-вторых, Django на длительный срок был в плену DRF. Который морально устарел еще в середине десятых.
Потом появилась
django-ninja, которая хоть и намного лучше, но все равно не решает главную задачу: интеграция с существующими тулами. Конечно, если затащить FastAPI дизайн в чужой мир, то ничего не будет нормально работать 🌚️️Вот такие проблемы мы решаем.
Одной строкой:
- Супер строгая OpenAPI схема и валидация при разработке, что мы ее соблюдаем
- Полная типизация всего
- Нормальный способ создания АПИ, без god-functions a-la FastAPI
-
async без sync_to_async- Быстро:
msgspec для парсинга json (самый быстрый способ в питоне), практически 0 работы в рантайме (все делаем при импорте), оптимизации роутера (быстрее дефолтного в 51 раз)- Пидантик,
msgspec, или любой другой способ выражать модели. Хоть adaptix- Полная поддержка всего существующего в Django. От декораторов до миддлварь (с полной валидацией и OpenAPI схемой!)
- OpenAPI схема из коробки
- Удобное тестирование с polyfactory
- property-based тесты вашего АПИ одной командой благодаря schemathesis
Что еще будет:
- RSGI (да, на #rust скорее всего) под granian, в теории можем побить FastAPI после такого
- SSE с автоматической OpenAPI спекой и умной валидацией схемы
- JWT или любая другая аутентификация
- Какие-то части (скорее всего валидацию) мы компильнем cython, чтобы было еще быстрее
Modern? Modern!
Осталось дождаться. Релиз скоро!
И еще скоро будут несколько новых видео.
Мы регулярно постим задачки в @opensource_findings_python, так что можно нам помочь.
А если кто хочет мне закинуть на развитие опенсорса (за написание 32500 строк кода за 2 недели), то мой бусти открыт: https://boosty.to/sobolevn
Ну и звезды можно ставить, конечно же. Там посмотрите, какие люди нас уже советуют.
Большое спасибо Александру, Алексею, Роману, Максиму и всем остальным за неоценимую помощь. Пацаны, без вас никак! Лучшее сообщество!
Обсуждение: а чего бы вам хотелось в modern rest фреймворке? Чего сильно не хватает сейчас?
68👍151🔥58❤53💩6😁2