Функция asyncio.wait() это еще один способ вызвать множество асинхронных задач.
Она работает в нескольких режимах.
1. Самый простой - ждем завершения всех задач
async def main():
tasks = [asyncio.create_task(do_it(i)) for i in range(10)]
done, pending = await asyncio.wait(
tasks,
return_when=asyncio.ALL_COMPLETED
)
for task in done:
try:
print(task.result())
except Exception as e:
print(e)
Очень похоже на gather, но работает не так.
▫️возвращает не результаты, а два сета с объектами Task у которых можно забрать результат через task.result() если они в списке done
▫️не гарантирует порядок результатов так как оба объекта это set
▫️не выбрасывает исключение когда оно появляется, а сохраняет его в Task. Исключение появится когда попробуете забрать резултьтат.
2. Ждем завершения первой задачи, даже если там ошибка.
async def main():
tasks = [asyncio.create_task(do_it(i)) for i in range(3)]
done, pending = await asyncio.wait(
tasks,
return_when=asyncio.FIRST_COMPLETED
)
# в done может быть несколько задач!
for task in done:
try:
print(task.result())
except Exception as e:
print(f"Fail: {e}")
# Оставшиеся задачи в pending, как правило, нужно отменить, иначе они будут продолжать работать
for task in pending:
task.cancel()
В сете done будут таски которые успели завершится, причем как успешно так и нет.
3. До первой ошибки.
Тоже самое, но с аргументом FIRST_EXCEPTION
done, pending = await asyncio.wait(
tasks,
return_when=asyncio.FIRST_EXCEPTION
)
Функция завершается как только первая задача упадет с ошибкой.
Учтите, что в любом случае done вы можете обранужить несколько задач, как с ошибками так и успешные.
↗️ Полный листинг примеров здесь
#async
💻 Бесплатный мини-курс: MySQL для новичков.
• Еще один бесплатный курс от Selectel для новичков, который описывает установку и настройку базы данных MySQL и как ими управлять, Вы научитесь работать с таблицами и разными типами данных, создавать ключи и настраивать права доступа. В конце курса — подборка полезных книг, которые точно пригодятся в начале пути.
- Как установить MySQL на Windows;
- Как установить и настроить MySQL в Ubuntu 20.04;
- Создание базы данных в MySQL;
- Типы данных в MySQL;
- Как создавать таблицы в MySQL (Create Table);
- Создание нового пользователя и настройка прав в MySQL;
- Сброс пароля root в MySQL;
- ALTER TABLE — изменение таблицы в SQL;
- Insert в MySQL — добавление данных в таблицу;
- Работа с командой UPDATE — как обновить данные в таблице MySQL;
- Как установить и использовать MySQL Workbench;
- Как создать первичные и внешние ключи MySQL;
- Книги по MySQL: пособия для начинающих и продолжающих.
#MySQL
https://www.tutorialspoint.com/python/python_database_access.htm
Python - #MySQL#Database Access
The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard.
You can choose the right database for your application. Python Database API supports a wide range of database servers such as
#python#django#MySQL
🐍
The Ultimate Django Series Part 3
Description
This course is the 3 part of a series. Build production-grade backends with industry best practices.A comprehensive, fun and highly-practical course that prepares you for the job
• Building an API to upload files
• Sending emails
• Running background tasks with Celery
• Scheduling periodic tasks
• Monitoring scheduled tasks
• Writing automated tests with PyTest
• Running performance tests with Locust
• Profiling with Silk
• Implementing caching with Redis
• Managing static assets
• Logging
• Managing development and production configuration
• Deploying to Heroku
• Django best practices
• And much, much more!
Author: Mosh Hamedani
Language: English
Duration: 4h+
🔗Link
-----
Main channel:@repo_science
Coupons: @freecoupons_reposcience
-----
#python#django#MySQL
🐍
The Ultimate Django Series Part2
Description
This course is the second part of a series. The first part covers the fundamentals of building websites with Python and Django. In this part, you'll learn:
• Fundamentals of RESTful APIs
• Working with class-based views
• Creating serializers
• Using mixins and generic views
• Generating routes with routers
• Filtering, searching, sorting, and pagination
• Django authentication system
• Creating custom User models
• Securing APIs with JSON Web Tokens (JWT)
• Using signals to decouple apps
• Troubleshooting common errors
• Applying best practices
• And much, much more!
Author: Mosh Hamedani
Language: English
Duration: 5h 41m
🔗Link
-----
Main channel:@repo_science
Coupons: @freecoupons_reposcience
-----
#python#django#MySQL
🐍
The Ultimate Django Series
Description
Master Django to Build Awesome Backends! This course is the first part of a series. In this part, you'll learn
• The fundamentals of web development
• Installing Django
• Creating and understanding Django projects
• Building reusable Django apps
• Building a data model for an e-commerce application
• Implementing generic relationships using Content Types Framework
• Setting up and using MySQL in your Django projects
• Creating and updating database tables using Django migrations
• Populating your database dummy data
• Querying and manipulating data using Django ORM
• Managing your application data using Django admin
• Django best practices
• And much, much more!
Author: Mosh Hamedani
Language: English
Duration: 4h 48m
Subtitle: Included
🔗Link
-----
Main channel:@repo_science
Coupons: @freecoupons_reposcience
-----
https://github.com/aio-libs/aiomysql
#aiomysql is a "driver" for accessing a #MySQL database from the #asyncio (PEP-3156/tulip) framework. It depends on and reuses most parts of #PyMySQL . aiomysql tries to be like awesome #aiopg library and preserve same api, look and feel.
Internally aiomysql is copy of PyMySQL, underlying io calls switched to async, basically yield from and asyncio.coroutine added in proper places)). sqlalchemy support ported from aiopg.