Python/ django
58.9K subscribers
2.07K photos
61 videos
47 files
2.79K links
по всем вопросам @haarrp

@itchannels_telegram - 🔥 все ит-каналы

@ai_machinelearning_big_data -ML

@ArtificialIntelligencedl -AI

@datascienceiot - 📚

@pythonlbooks

РКН: clck.ru/3FmxmM
加入频道
🖥 beets

Beets is the media library management system for obsessive music geeks.

Beets - это система управления медиатекой для одержимых музыкальных гиков.

🖥 Github

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Мы собрали для вас подборку свежих и актуальных книг, по всем языкам программирования.

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

🍍 Папка с книгами:
https://yangx.top/addlist/BkskQciUW_FhNjEy

Я подписан на многие каналы из подборки, но не на все, так что будет из чего выбрать – от глубоко технических авторов, до понятных всем и тп.

Настоящий кладезь книг и знаний здесь
🖥 FeinCMS - An extensible Django-based CMS

A Django-based CMS with a focus on extensibility and concise code.

CMS на основе Django с упором на расширяемость и лаконичный код

🖥 Github

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 PlatformIO Core

PlatformIO is a professional collaborative platform for embedded development.

PlatformIO - это профессиональная платформа для совместной разработки встраиваемых систем.

🖥 Github

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
How to Implement Screen Navigation in Your Kivy App

Гайд по реализации экранной навигацию в приложении Kivy

https://noudedata.com/2023/04/kivy-screen-navigation/

@pythonl
🖥 transitions

A lightweight, object-oriented state machine implementation in Python with many extensions.

Легкая, объектно-ориентированная реализация конечных автоматов на Python.

🖥 Github

@python
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 HTTPie for Terminal: human-friendly CLI HTTP client for the API era

HTTPie (pronounced aitch-tee-tee-pie) is a command-line HTTP client. Its goal is to make CLI interaction with web services as human-friendly as possible.

HTTPie - это HTTP-клиент командной строки. Его цель - сделать взаимодействие CLI с веб-сервисами максимально удобным при работе.

🖥 Github

@python
Please open Telegram to view this post
VIEW IN TELEGRAM
📚9 Best Python Game Development Libraries/Frameworks

Лучшие библиотеки для создания игр на Python

1. The Python Arcade Library

2. PANDA3D

3. HARFANG Framework

4. Ren’Py

5. Kivy

6. Pygame

7. Pyglet

8. OGRE

9. Cocos2d

@python
🔩 Attrs

Its main goal is to help you to write concise and correct software without slowing down your code.

attrs - это пакет Python, который вернет радость от написания классов, избавив вас от муторной работы по реализации объектных протоколов (они же методы Дандера). Доверенный NASA для миссий на Марсе с 2020 года!

Его основная цель - помочь вам писать лаконичное и корректное программное обеспечение.


🖥 Github
🗒 Docs

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🐍 Box

Box will automatically make otherwise inaccessible keys safe to access as an attribute. You can always pass conversion_box=False to Box to disable that behavior. Also, all new dict and lists added to a Box or BoxList object are converted automatically.

Словари Python с расширенным функциналом, которые помогут вам в написании скриптов.

from box import Box

movie_box = Box({ "Robin Hood: Men in Tights": { "imdb stars": 6.7, "length": 104 } })

movie_box.Robin_Hood_Men_in_Tights.imdb_stars


🖥 Github

#github #python

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Python security best practices cheat sheet

Updated cheat sheet to make sure you keep your Python code secur

Список полезных советов про работу с внешними данными, сканированию кода, загрузке пакетов, сериализации данных, форматированию строк и другим мерам безопасности:

https://snyk.io/blog/python-security-best-practices-cheat-sheet/

@pythonl
📚9 must-have Python developer tools.

9 обязательных инструментов Python разработчика.

1. PyCharm IDE

2. Jupyter notebook

3. Keras

4. Pip Package

5. Python Anywhere

6. Scikit-Learn

7. Sphinx

8. Selenium

9. Sublime Text

@pythonl
🤖Errbot

Errbot is a chatbot. It allows you to start scripts interactively from your chatrooms for any reason: random humour, chatops, starting a build, monitoring commits, triggering alerts...

Errbot - это чат-бот, который можно подключить к чату, при этом бот будет вести осмысленный и интересный диалог.

🖥 Github

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 PyGitHub

If you want to manage your Github resources (repositories, user profiles, organizations, etc.) from Python scripts, try PyGithub. Above is an example to get a list of Github repositories when searching for a certain topic.

Если вы хотите управлять Github (репозиториями, профилями пользователей, организациями и т.д.) с помощью скриптов на Python, попробуйте PyGithub. Выше приведен пример получения списка репозиториев Github при поиске определенной темы.

$ pip install PyGithub

🖥 Github
📌 Документация

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 tmuxp

A session manager for tmux. Built on libtmux.

Менеджер сессий для tmux. Написан на базе libtmux.

🖥 Github

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
This media is not supported in your browser
VIEW IN TELEGRAM
D-Tale: A Python Library to Visualize and Analyze your Data Without Code

The GIF above shows how your DataFrame will look like when using D-Tale. D-Tale is also useful for analyzing and visualizing your data without code.

D-Tale: Библиотека Python для визуализации и анализа данных без кода

В приведенном выше GIF показано, как будет выглядеть ваш DataFrame при использовании D-Tale. D-Tale также полезен для анализа и визуализации данных без кода.

D-Tale.

@pythonl
🖥 Difference between Numpy’s All and Any Methods

If you want to get the row whose ALL values satisfy a certain condition, use numpy’s all method. To get the row whose AT LEAST one value satisfies a certain condition, use numpy’s any method.

Если вы хотите получить строку, ВСЕ значения которой удовлетворяют определенному условию, используйте метод numpy's all. Чтобы получить строку, в которой хотя бы одно значение удовлетворяет определенному условию, используйте метод numpy's any.

В приведенном коде показана разница в выводах между all и any.


import numpy as np

a = np.array([[1, 2, 1], [2, 2, 5]])

# get the rows whose all values are fewer than 3
mask_all = (a<3).all(axis=1)
print(a[mask_all])
"""
[[1 2 1]]
"""

mask_any = (a<3).any(axis=1)
print(a[mask_any])
"""
[[1 2 1]
[2 2 5]]
"""

Numpy docs

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 Pydantic: 10 Most Common Usage Patterns

Pydantic: 10 наиболее распространенных вариантов использования

1. Basic Data Validation
Use Pydantic models to validate incoming data easily.

from pydantic import BaseModel

class User(BaseModel):
name: str
age: int

user = User(name='John Doe', age=30)

2. Default Values
Define default values for your model fields.

class User(BaseModel):
name: str
age: int = 18 # Default value


3. Optional Fields
Mark fields as optional using the Optional type.

from typing import Optional

class User(BaseModel):
name: str
age: Optional[int] = None

4. Custom Validators
Create custom validators with the @validator decorator.

from pydantic import validator

class User(BaseModel):
name: str
age: int

@validator('age')
def validate_age(cls, value):
if value < 18:
raise ValueError('User must be 18+')
return value


5. Nested Models

Use Pydantic models to validate nested data structures.

class Address(BaseModel):
street: str
city: str

class User(BaseModel):
name: str
age: int
address: Address

6. Lists of Models
Handle lists of a specific model.

from typing import List

class User(BaseModel):
name: str
age: int

class UserList(BaseModel):
users: List[User]

7. Union Fields
Use Union to allow a field to be one of several types.

from typing import Union

class User(BaseModel):
identifier: Union[str, int]


8. Value Constraints
Impose constraints on values using Field.

from pydantic import Field

class User(BaseModel):
name: str
age: int = Field(..., gt=0, lt=120) # Greater than 0, less than 120

9. Aliases for Fields

Define aliases for model fields, which can be useful for fields that are Python keywords.

class User(BaseModel):
name: str
class_: str = Field(alias='class')


10. Recursive Models
Make models that can contain themselves.

from typing import Optional

class TreeNode(BaseModel):
value: int
left: Optional['TreeNode'] = None
right: Optional['TreeNode'] = None

TreeNode.update_forward_refs() # Resolve string annotations

pydantic

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 6 Python f-strings tips and tricks

f-строки в Python обеспечивают более читабельный, лаконичный и менее подверженный ошибкам способ форматирования строк, чем традиционное форматирование строк. Они обладают множеством полезных функций, которые обязательно пригодятся в повседневной работе.

1. String Interpolation
The most used f-string feature by far is string interpolation. All you need to do is wrap the value or variable in curly braces ({}) and you're good to go.

str_val = 'apples'
num_val = 42

print(f'{num_val} {str_val}') # 42 apples


2. Variable names
Apart from getting a variable's value, you can also get its name alongside the value.

str_val = 'apples'
num_val = 42

print(f'{str_val=}, {num_val = }') # str_val='apples', num_val = 42


3. Mathematical operations
Not syntactically unlike variable names, you can also perform mathematical operations in f-strings.

num_val = 42

print(f'{num_val % 2 = }') # num_val % 2 = 0

4. Printable representation
Apart from plain string interpolation, you might want to get the printable representation of a value.

str_val = 'apples'

print(f'{str_val!r}') # 'apples'


5. Number formatting
Numbers are a great candidate for this. If, for example, you want to trim a numeric value to two digits after the decimal, you can use the .2f format specifier.

price_val = 6.12658

print(f'{price_val:.2f}') # 6.13


6. Date formatting
Finally, dates can also be formatted the same way as numbers, using format specifiers. As usual, %Y denotes the full year, %m is the month and %d is the day of the month.

from datetime import datetime;

date_val = datetime.utcnow()

print(f'{date_val=:%Y-%m-%d}') # date_val=2021-07-09


String Formatting Best Practices
F-strings или как сделать код чуть более быстрым

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Example that demonstrates how to use Redis with the redis-py library, which is a popular Redis client for Python.

Redis – это быстрое хранилище данных типа «ключ‑значение» в памяти с открытым исходным кодом.
Ниже приведен пример, демонстрирующий, как использовать Redis с библиотекой redis-py, которая является популярным клиентом Redis для Python.

$ pip install redis

import redis

# Create a Redis client
r = redis.Redis(host='localhost', port=6379, db=0)

# String Operations
r.set('mykey', 'Hello Redis!')
value = r.get('mykey')
print(value) # Output: b'Hello Redis!'

# List Operations
r.lpush('mylist', 'element1')
r.lpush('mylist', 'element2')
r.rpush('mylist', 'element3')
elements = r.lrange('mylist', 0, -1)
print(elements) # Output: [b'element2', b'element1', b'element3']

# Set Operations
r.sadd('myset', 'member1')
r.sadd('myset', 'member2')
r.sadd('myset', 'member3')
members = r.smembers('myset')
print(members) # Output: {b'member2', b'member1', b'member3'}

# Hash Operations
r.hset('myhash', 'field1', 'value1')
r.hset('myhash', 'field2', 'value2')
value = r.hget('myhash', 'field1')
print(value) # Output: b'value1'

# Sorted Set Operations
r.zadd('mysortedset', {'member1': 1, 'member2': 2, 'member3': 3})
members = r.zrange('mysortedset', 0, -1)
print(members) # Output: [b'member1', b'member2', b'member3']

# Delete a key
r.delete('mykey')

# Close the Redis connection
r.close()


Github

@pythonl