Transcription
Hello, you are on the Cyberfaculty channel, and today we have another compilation of five Python topics that will make your code more powerful than ever. In this video, we will explore how to extend a function using decorators, how to store and read data from JSON and CSV, what asynchronous programming is and how to run tasks in parallel, how to test your code using automated tests. And finally, we will create a real web application on Flask. This video will suit you if you are already familiar with the basics of Python and want to move to the next level from simple scripts to a professional approach. I will explain everything simply, visually, with examples, and at the end, we will create a mini-project that will combine all these topics into a useful application. Be sure to subscribe if you want to continue your developer journey with me. Let's go. [music] Imagine that you can add behavior to a function without changing its code. like a superpower, by wrapping a function and giving it new capabilities. This is what decorators are. In Python, they are created using the at symbol and allow, for example, logging calls, checking access rights, or modifying execution time. Let's look at an example. Here is the code for a simple decorator. Here we created the LCK call decorator, which wraps the Say hello function. When launched, we see not just hello, but also messages before and after. This approach is often used to avoid touching the function itself, but to add useful functionality around it. Python already includes built-in decorators that we use without even thinking about it. For example, staticmethod and classmethod are used within classes. [music] Here is an example of using these two methods. A static method does not take self or cls arguments. It works like a regular function but lives within the class. A class method, on the other hand, receives the class as the first argument, which is convenient when you need to work with the class, not the object. And now, a lambda function is a mini-function that is written directly within the code. It is used when you need a quick, nameless function for a single expression. Here is an example of a lambda function. This is the same as lambdas are especially useful when you use them inside other functions, for example, when sorting or filtering. So, you have learned how to extend function behavior using decorators, and how to write compact and fast code using lambda functions. Next, we will dive into the world of data, learning to read and save information in JSON and CSV formats. When you work with data, it is important not only to compute but also to save the results so that you can use them again later, analyze them, or transfer them to another application. In Python, JSON and CSV formats are most often used for this. What is JSON? JSON is a text-based data storage format, similar to Python dictionaries. It is human-readable and easily processed by programs. Here is an example of saving data to JSON. [music] Here we save the dictionary data, and then save it to the file data.json using json.dump. Here is an example of reading from JSON. [music] So, we read the data back. The file is converted into a Python object. [music] What is CSV? CSV is a tabular format, similar to Excel. Data is separated by commas, and rows follow one after another. [music] Here is an example of saving data to CSV. [music] Here we write a list of lists, each nested list as a separate row in the table. Here is an example of reading CSV, or rather, reading line by line. The CSV file is converted into a list of strings. Let's say we have a list of orders. We want to save them to a CSV file and then analyze them. [music] After that, open the file and use it in Excel, Google Sheets, or again in Python. We have learned to save and read data in JSON and CSV formats. JSON for structured data, dictionaries, and lists. CSV for tables. Let's move on to the world of asynchronous programming, where code runs in parallel without waiting in line. [music] Imagine your program is downloading data from the internet. It waits for a response, and during this time, everything stops. But you can make it so that while one task is waiting, another is already executing. This is exactly how asynchronous programming works. What is the idea behind ASYNC? Regular Python code works step-by-step sequentially, while asynchronous code switches between tasks without waiting for each of them to complete. Here is a start with a regular delay. Here the program sleeps for 3 seconds. Everything else waits. Here is an example of an asynchronous version. [music] Thanks to ASYNC DEF and await, we don't just sleep, but yield control and allow other tasks to run. Let's consider an example of an asynchronous task. Imagine you need to perform several delays at once. Let's compare the regular and asynchronous approaches. [music] All three tasks start almost simultaneously and complete as they are ready, without interfering with each other. This is the parallel magic of await. What else is important to know? Python uses the asyncio library to work with asynchronous code. It allows you to create timers, requests, queues, sockets, and much more without blocking other tasks. Now you know how to create asynchronous functions, how to use await and async, and why it's needed in real projects from chats to web applications. Next, and no less important, is code testing. [music] Let's move on to unittest. You wrote code, it works, but tomorrow you will change it, or someone else will rewrite part of the project, and suddenly something breaks, and you don't even notice until it's too late. This is precisely why code testing exists. It allows you to check that everything works exactly as intended, even after changes. What is Unittest? Python has a built-in library for tests, unittest. With its help, you can write special functions that will automatically check your code. Here is a simple function and a test for it. Let's say we have a simple addition function. Let's write this test for it. [music] We write each check using assertEqual. This means we expect the result to be a certain way. If the result matches, the test passes. If not, there will be an error with an explanation at the end. What else can be checked besides assertEqual? There are many other useful checks. AssertTrue. We expect the expression to be true. AssertFalse. We expect it to be false. AssertRaises. We check that an error is raised. Here is the code with exception checking. Here we expect division by zero to raise an error. If there is an error, the test passes. If not, it means something is wrong. Why write tests at all? They are needed so you don't fear changes, so you can easily check logic, and write truly reliable code. Yes, it takes a lot of time, but it saves tens of hours of debugging in the future. We have become acquainted with the unittest library. Now you know how to write tests, check results, and catch errors using assertRaises. It will get even cooler. We will write our first web application using Flask. [music] Do you want your program to open in a browser, to respond to requests, to accept data, and to display pages? Then you need Flask, one of the most popular frameworks for creating websites in Python. It is simple, lightweight, and perfect for a first project. What is Flask? Flask is a framework. It helps a Python program turn into a web server that responds to user requests. Let's install Flask via pip. Then let's write the code. [music] Here we create an app object. Using app.route, we tell Flask that if the user goes to the main page, call the home function. It returns a string, and this string will be displayed in the browser. [music] We can add multiple pages. [music] Here we have created two pages. This is the About page and the Contacts page. [music] Flask can also accept data from the user, for example, a name. [music] [music] If we go to Hello Anya, we get a response. Hello, Anya. Let's create a small web application that will display a greeting and the current date. [music] [music] Flask opens the world of web development. Routes, templates, forms, databases. All this can be mastered now. You have just created your first web application, and this is just the beginning. [music] Now let's create a mini-service on Flask that uses five advanced Python topics at once. We will work with JSON and CSV, add decorators, asynchronous programming, and even write unit tests. Let's go. Let's start by installing Flask and the aiofiles library, which will allow us to work with files asynchronously. This is what the project structure will look like. app.py will contain the web application, utils.py will have helper functions and decorators, and test.py will contain unit tests. We create a Flask application and a route. We create an asynchronous route Task, which returns a list of tasks from the data file. Now we implement asynchronous data loading from JSON. The load_data function asynchronously reads tasks from JSON. This is especially useful for large amounts of data. [music] Let's create a logging decorator. We add the LogRequest decorator, which will print the name of the called function to the console. This is an excellent way for debugging. [music] [music] [music] [music] [music] And now we import tasks from the CSV file and convert them into a list of dictionaries. [music] [music] [music] For filtering tasks by priority, we use a lambda function. Concise, convenient, readable. [music] We create a unit test to ensure that at least some tasks are imported from CSV. This is useful for automatic code correctness checks. [music] [music] So, we have built a mini-service using Flask, asynchronous programming, file handling, decorators, lambda functions, and unit tests. We have learned to combine these topics in a real project. Congratulations. We have completed another set of five Python topics. These are decorators and lambda functions, working with JSON and CSV, asynchronous programming, code testing, and creating a full-fledged web application. Keep learning, and you will be surprised how far you can go in Python development. Subscribe to the Cyberfaculty channel, give a like if the video was useful for you, and also write in the comments if you have any questions. Thank you for learning with me. See you in the next video. M.