<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yashnarbek Samiyev on Medium]]></title>
        <description><![CDATA[Stories by Yashnarbek Samiyev on Medium]]></description>
        <link>https://medium.com/@yashnarsamiyev2?source=rss-1775992469b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lIMrZhhtlXT2qsovawv1LA.jpeg</url>
            <title>Stories by Yashnarbek Samiyev on Medium</title>
            <link>https://medium.com/@yashnarsamiyev2?source=rss-1775992469b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:45:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yashnarsamiyev2/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What Are Models in Laravel?]]></title>
            <link>https://medium.com/@yashnarsamiyev2/what-are-models-in-laravel-a2ec69d9f7ca?source=rss-1775992469b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2ec69d9f7ca</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Yashnarbek Samiyev]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 10:20:22 GMT</pubDate>
            <atom:updated>2024-12-03T10:20:22.111Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Are Models in Laravel?</h3><p>Models in Laravel are the core of the framework’s MVC architecture, and they manage how data is used and organized throughout your application.</p><p>Laravel models represent tables in your database, enabling you to perform essential operations — like <strong>querying</strong>, <strong>updating</strong>, and <strong>deleting data</strong> — through expressive, human-readable code.</p><p>Beyond basic database interaction, Laravel models empower you to add business logic directly to your models, making your code more modular and organized.</p><h3>What Is the Purpose of Creating a Model in Laravel?</h3><p>Models in Laravel are the powerhouse behind managing and organizing your app’s data, making it easy to interact with your database effortlessly.</p><p>Here’s why creating a model is so valuable:</p><ul><li><strong>Direct Database Interaction:</strong> Models bridge your database tables, allowing you to <strong>retrieve</strong>, <strong>create</strong>, <strong>update</strong>, and <strong>delete data</strong> easily without writing raw SQL.</li><li><strong>Logical Data Organization:</strong> Each model represents a specific table, like <strong>User </strong>or <strong>Order</strong>, giving your data a clear, meaningful structure that matches your app’s needs.</li><li><strong>Simplified Relationships:</strong> Models allow you to define relationships, like “<strong>one-to-many</strong>” or “<strong>many-to-many</strong>,” which lets you access related data (like a user’s posts) with minimal code.</li><li><strong>Built-in Data Security:</strong> Models include features like mass-assignment protection and attribute casting, making it easier to handle data securely and prevent common vulnerabilities.</li></ul><h3>How to Create a Model in Laravel?</h3><p>Creating a model in Laravel involves a few clear steps, each handled by specific commands and file modifications.</p><p>Here’s how to create a model in Laravel, step by step, with code and explanations:</p><h3>Step 1: Use Artisan Command</h3><p>To create a model in Laravel, use the Artisan command-line tool in your SSH terminal with the following command:</p><ol><li>php artisan make:model Post</li></ol><p>This command generates a new model file. We’re creating a Post model. By default, the model file is created in the app/Models directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><h3>Step 2: Define Model Properties</h3><p>Once the model file is created, you can add properties to define how it interacts with the database.</p><p>Add the following line of code in app/Models/Post.php that you just created in the previous step.</p><ol><li>namespace App\Models;</li><li>use Illuminate\Database\Eloquent\Factories\HasFactory;</li><li>use Illuminate\Database\Eloquent\Model;</li><li>class Post extends Model</li><li>{</li><li>use HasFactory;</li><li>// Add fillable properties</li><li>protected $fillable = [‘title’, ‘content’, ‘author’];</li><li>// Specify the table name if it’s different from ‘posts’</li><li>// protected $table = ‘my_custom_table’;</li><li>}</li></ol><ul><li>Here, title, content, and author are fields that can be filled by the application.</li><li>You can also specify custom table names or add relationships to other models if needed.</li></ul><h3>Step 3: Database Migration</h3><p>To create the actual table in the database, generate a migration file and define the columns.</p><ol><li>php artisan make:migration create_posts_table</li></ol><p>This command creates a new migration file in the <strong>database/migrations</strong> folder.</p><p>Add the following line of code inside the new migration file in the database/migrations.</p><ol><li>&lt;?php</li><li>use Illuminate\Database\Migrations\Migration;</li><li>use Illuminate\Database\Schema\Blueprint;</li><li>use Illuminate\Support\Facades\Schema;</li><li>return new class extends Migration</li><li>{</li><li>public function <strong>up</strong>()</li><li>{</li><li>Schema::<strong>create</strong>(‘posts’, <strong>function</strong> (Blueprint $table) {</li><li>$table-&gt;<strong>id</strong>();</li><li>$table-&gt;<strong>string</strong>(‘title’);</li><li>$table-&gt;<strong>text</strong>(‘content’);</li><li>$table-&gt;<strong>string</strong>(‘author’);</li><li>$table-&gt;<strong>timestamps</strong>();</li><li>});</li><li>}</li><li>public function <strong>down</strong>()</li><li>{</li><li>Schema::<strong>dropIfExists</strong>(‘posts’);</li><li>}</li><li>};</li></ol><p>This migration file defines the structure of the posts table, including its columns.</p><p>Each field specified here (title, content, author) corresponds to a column in the database. The timestamps() method automatically adds created_at and updated_at columns.</p><p>After defining the migration, run it with:</p><ol><li>php artisan migrate</li></ol><p>Till now, you have created a basic model in Laravel for managing Post records in a posts database table.</p><p>This includes defining the model (Post) and a migration file to create the table with columns like title, content, and author.</p><p>Running the migration with php artisan migrate creates the posts table in the database.</p><h3>Step 4: Using Models With Eloquent ORM</h3><p>After setting up this model, you can use Eloquent ORM to interact with the database, such as:</p><ol><li>// Create a new Post record</li><li>Post::<strong>create</strong>([‘title’ =&gt; ‘First Post’, ‘content’ =&gt; ‘This is the content.’, ‘author’ =&gt; ‘Author Name’]);</li><li>// Retrieve all posts</li><li>$posts = Post::<strong>all</strong>();</li></ol><p>Using Eloquent ORM, you can use the User Interface to Post records in your database. You can access them with Post::all() or find specific records by ID using Post::find(1).</p><h3>What are Views in Laravel?</h3><p>In Laravel, views are like the front end of your application. They display the information that your application generates.</p><p>Views are typically written in <strong>Blade</strong>, a templating engine provided by Laravel. Blade allows you to create dynamic and reusable HTML templates. You can embed PHP code within your HTML to generate content dynamically.</p><p>To use a <strong>view</strong>, you typically return it from a <strong>controller</strong>. The controller collects the necessary data and passes it to the view, which then renders the HTML with the given data. This separation of content helps keep your code organized and maintainable.</p><h3>What Is the Purpose of Using Views in Laravel?</h3><p>Views in Laravel are the key to making your data secure and manageable. Laravel views let you keep your code clean, separate, and organized. Here’s why they’re essential:</p><ul><li><strong>Effortless Content Display:</strong> Views are the templates that display your application’s data, making it easy to show dynamic content on web pages without cluttering your backend code.</li><li><strong>Separation of Logic and Design:</strong> Views keep your HTML and CSS separate from your business logic, making your code cleaner and easier to maintain. This structure also simplifies updates since the logic and design don’t overlap.</li><li><strong>Reusable Layouts:</strong> You can create reusable layouts, such as headers, footers, and sidebars, that appear across multiple pages with a consistent design, saving you time and effort.</li><li><strong>Dynamic User Experience:</strong> By passing data to views, you can create interactive and dynamic pages that enhance the user experience, all while keeping your code streamlined.</li></ul><h3>How to Create a Views in Laravel?</h3><p>Creating and rendering views in Laravel is a fundamental task for web applications. Here’s how to achieve it step by step, including code examples and explanations for each part:</p><h3>Step 1: Creating and Rendering Views</h3><p>To create a view, place the HTML template file in the resources/views directory.</p><p>Create a new file with a .blade.php extension. This extension tells Laravel to use the Blade template engine to parse the view.</p><p>In the view file, add the HTML, PHP, and/or Blade templates that define the page’s structure and layout. You can use placeholders for dynamic content.</p><p>Save the view file.</p><ol><li>&lt;! — resources/views/greeting.blade.php →</li><li>&lt;h1&gt;Step 1 output&lt;/h1&gt;</li><li>&lt;h1&gt;Hello, world!&lt;/h1&gt;</li></ol><p>To render this view, use the view() helper in a controller or route:</p><ol><li>// In a route (routes/web.php)</li><li>Route::<strong>get</strong>(‘/’, <strong>function</strong> () {</li><li>return <strong>view</strong>(‘welcome’);</li><li>});</li></ol><h4>Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><h3>Step 2: Nested View Directories</h3><p>You can organize views into subdirectories to keep them organized.</p><ol><li>&lt;! — resources/views/posts/index.blade.php →</li><li>&lt;!DOCTYPE html&gt;</li><li>&lt;html&gt;</li><li>&lt;head&gt;</li><li>&lt;title&gt;Posts&lt;/title&gt;</li><li>&lt;/head&gt;</li><li>&lt;body&gt;</li><li>&lt;h1&gt;All Posts&lt;/h1&gt;</li><li>&lt;/body&gt;</li><li>&lt;/html&gt;</li></ol><p>To render a nested view, use dot notation:</p><ol><li>// In a route (routes/web.php)</li><li>Route::<strong>get</strong>(‘/posts’, <strong>function</strong> () {</li><li>return <strong>view</strong>(‘posts.index’);</li><li>});</li></ol><p>The view posts.index uses dot notation to access the nested directory.</p><h3>Step 3: Creating the First Available View</h3><p>Use View::first() to render the first available view from various options.</p><ol><li>use Illuminate\Support\Facades\View;</li><li>// In a route (routes/web.php)</li><li>Route::<strong>get</strong>(‘/landing’, <strong>function</strong> () {</li><li>return View::<strong>first</strong>([‘custom.landing’, ‘default.landing’]);</li><li>});</li></ol><p>If resources/views/custom/landing.blade.php exists, it loads that view. Otherwise, it will return to resources/views/default/landing.blade.php.</p><h3>Step 4: Determining if a View Exists</h3><p>Checks if a view exists before trying to render it.</p><ol><li>use Illuminate\Support\Facades\View;</li><li>// In a route (routes/web.php)</li><li>Route::<strong>get</strong>(‘/check-view’, <strong>function</strong> () {</li><li><strong>if</strong> (View::<strong>exists</strong>(‘posts.index’)) {</li><li>return <strong>view</strong>(‘posts.index’);</li><li>} else {</li><li>return ‘View does not exist’;</li><li>}</li><li>});</li></ol><h3>Step 5: Passing Data to Views</h3><p>You can pass data directly to a view using an array.</p><ol><li>Route::<strong>get</strong>(‘/post’, <strong>function</strong> () {</li><li>$post = [</li><li>‘title’ =&gt; ‘My First Post’,</li><li>‘content’ =&gt; ‘This is the content of my first post.’,</li><li>];</li><li>return <strong>view</strong>(‘posts.show’, <strong>compact</strong>(‘post’));</li><li>});</li></ol><p>Also, update the view in resources/views/posts/show.blade.php:</p><ol><li>&lt;! — resources/views/posts/show.blade.php →</li><li>&lt;!DOCTYPE html&gt;</li><li>&lt;html&gt;</li><li>&lt;head&gt;</li><li>&lt;title&gt;{{ $post[‘title’] }}&lt;/title&gt;</li><li>&lt;/head&gt;</li><li>&lt;body&gt;</li><li>&lt;h1&gt;{{ $post[‘title’] }}&lt;/h1&gt;</li><li>&lt;p&gt;{{ $post[‘content’] }}&lt;/p&gt;</li><li>&lt;/body&gt;</li><li>&lt;/html&gt;</li></ol><h3>Step 6: Sharing Data with All Views</h3><p>You can share data globally in your application with all views using the View::share() method.</p><ol><li>use Illuminate\Support\Facades\View;</li><li>// In App\Providers\AppServiceProvider.php</li><li>public function <strong>boot</strong>()</li><li>{</li><li>View::<strong>share</strong>(‘appName’, ‘My Laravel App’);</li><li>}</li></ol><p>Now to access this view any view file, you can use appName:</p><ol><li>&lt;! — Example in any view file →</li><li>&lt;h1&gt;Step 6 output&lt;/h1&gt;</li><li>&lt;h1&gt;Welcome to {{ $appName }}&lt;/h1&gt;</li></ol><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>Using this code, you can build and display different pages in Laravel, organize those pages efficiently, handle missing views, and display dynamic data on the pages.</p><p>This structure is fundamental for building a functional, organized, and dynamic web application.</p><h3>Laravel Model Tips</h3><p>Here are some essential Laravel model tips to help you build secure and maintainable applications. Using these techniques, you can keep your code efficient and safe, ensuring better control over your models and data.</p><p>Let’s dive into each tip!</p><h3>1. Spotting and Preventing N+1 Issues</h3><p>The N+1 query problem happens when multiple queries are sent to the database for related data, causing slow performance. Avoid it by using Eager Loading with Laravel’s with() method in your queries.</p><p>This speeds up your queries by loading related data in a single call, preventing performance lags and unnecessary database calls.</p><ol><li>// Instead of this (causes N+1 issue)</li><li>$posts = Post::<strong>all</strong>();</li><li><strong>foreach</strong> ($posts as $post) {</li><li>echo $post-&gt;author-&gt;name;</li><li>}</li><li>// Use this (solves N+1 issue)</li><li>$posts = Post::<strong>with</strong>(‘author’)-&gt;<strong>get</strong>();</li><li><strong>foreach</strong> ($posts as $post) {</li><li>echo $post-&gt;author-&gt;name;</li><li>}</li></ol><h3>2. Prevent Accessing Missing Attributes</h3><p>Accessing a non-existent attribute on a model can cause confusing bugs. Use $guarded or $fillable in your models to control which attributes are accessible.</p><p>By defining $fillable attributes, you ensure that only these specified fields can be accessed and mass-assigned, protecting your model from unexpected data.</p><ol><li>class Post extends Model</li><li>{</li><li>protected $fillable = [‘title’, ‘content’, ‘author_id’];</li><li>}</li></ol><h3>3. Prevent Silently Discarding Attributes</h3><p>Laravel can silently ignore attributes that aren’t in $fillable, causing confusion. To avoid this, enable guarded for fields you want to protect and strictly define only what’s allowed.</p><p>This approach helps prevent Laravel from discarding attributes without alerting you, keeping your data secure and your code clear.</p><ol><li>class Post extends Model</li><li>{</li><li>protected $guarded = [‘id’];</li><li>}</li></ol><h3>4. Enable Strict Mode for Models</h3><p>Laravel’s strict mode ensures errors are thrown for unrecognized attributes, making your app safer. Enable strict mode in your AppServiceProvider.</p><p>With strict mode enabled, Laravel alerts you when something unexpected happens, helping you catch issues early.</p><ol><li>use Illuminate\Database\Eloquent\Model;</li><li>public function <strong>boot</strong>()</li><li>{</li><li>Model::<strong>shouldBeStrict</strong>(true);</li><li>}</li></ol><h3>5. Using UUIDs</h3><p>UUIDs are unique identifiers that make models more secure, especially in public-facing URLs. Add the Str::uuid() helper to generate UUIDs.</p><p>Using UUIDs hides your database’s numeric IDs, making your application’s data more secure and harder to predict.</p><ol><li>use Illuminate\Support\Str;</li><li>class Post extends Model</li><li>{</li><li>protected static function <strong>booted</strong>()</li><li>{</li><li>static::<strong>creating</strong>(<strong>function</strong> ($post) {</li><li>$post-&gt;uuid = (string) Str::<strong>uuid</strong>();</li><li>});</li><li>}</li><li>}</li></ol><h3>6. Use UUIDs as the Primary Key</h3><p>For an added layer of security, use UUIDs as your primary key. Override $primaryKey and $keyType in the model and set incrementing to false.</p><p>Using UUIDs as primary keys makes your database less predictable and enhances security by preventing sequential ID guessing.</p><ol><li>class Post extends Model</li><li>{</li><li>protected $primaryKey = ‘uuid’;</li><li>protected $keyType = ‘string’;</li><li>public $incrementing = false;</li><li>}</li></ol><h3>7. Using ULIDs</h3><p>ULIDs are alternative unique identifiers that combine randomness with sequential sorting. You can generate ULIDs with Str::ulid().</p><p>In simple words, ULIDs offer a unique, sortable ID that’s great for use cases that require ordering but secure IDs in the URL.</p><ol><li>use Illuminate\Support\Str;</li><li>class Post extends Model</li><li>{</li><li>protected static function <strong>booted</strong>()</li><li>{</li><li>static::<strong>creating</strong>(<strong>function</strong> ($post) {</li><li>$post-&gt;ulid = (string) Str::<strong>ulid</strong>();</li><li>});</li><li>}</li><li>}</li></ol><h3>8. Changing the Field Used for Route Model Binding</h3><p>By default, Laravel binds models to routes using the primary key. You can change this to use a UUID or any other field by overriding getRouteKeyName().</p><p>This change makes your routes more flexible by allowing you to use unique fields like uuid instead of numeric IDs, adding both clarity and security.</p><ol><li>class Post extends Model</li><li>{</li><li>public function <strong>getRouteKeyName</strong>()</li><li>{</li><li>return ‘uuid’;</li><li>}</li><li>}</li></ol><h3>9. Use Custom Model Collections</h3><p>Laravel allows you to create custom collections for specific models, making it easier to add specialized methods for handling groups of models.</p><p>With custom collections, you can add methods like published() that filter your collection data, making it more readable and convenient.</p><ol><li>use Illuminate\Database\Eloquent\Collection;</li><li>class PostCollection extends Collection</li><li>{</li><li>public function <strong>published</strong>()</li><li>{</li><li>return $this-&gt;<strong>where</strong>(‘is_published’, true);</li><li>}</li><li>}</li><li>// In the Post model</li><li>class Post extends Model</li><li>{</li><li>public function <strong>newCollection</strong>(array $models = [])</li><li>{</li><li>return new <strong>PostCollection</strong>($models);</li><li>}</li><li>}</li></ol><h3>Using Models and Views together in Laravel?</h3><p>Building dynamic web apps requires integrating Laravel’s Models and Views. In this part, we will learn how to use Models and Views together.</p><p>Let’s develop a basic application that retrieves and displays items or products from a database.</p><p>Here is a step-by-step guide on doing it:</p><h3>Step 1: Database Setup</h3><p>First, configure your database connection in the environment file. Once the database is set up, create a table for storing your products. Use the following Artisan command to create a products table:</p><ol><li>php artisan make:migration create_products_table — create=products</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>Next, we will define the migration. To define the migration, locate the migration file created for the products table. You’ll find this file under database/migrations/, with a name similar to create_products_table. In our case, it’s named 2024_11_12_125426_create_products_table.php.</p><p>Once you locate the file, open it and define the schema as shown below:</p><ol><li>public function <strong>up</strong>()</li><li>{</li><li>Schema::<strong>create</strong>(‘products’, <strong>function</strong> (Blueprint $table) {</li><li>$table-&gt;<strong>id</strong>();</li><li>$table-&gt;<strong>string</strong>(‘name’);</li><li>$table-&gt;<strong>text</strong>(‘description’);</li><li>$table-&gt;<strong>timestamps</strong>();</li><li>});</li><li>}</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>Save the file, then run the migration to create the products table in the database. To do this, navigate to your project’s root directory and execute the following command:</p><ol><li>php artisan migrate</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><h3>Step 2: Creating a Model for Products</h3><p>In this step, we will create a model for the products using the following Artisan command:</p><ol><li>php artisan make:model Product</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>Once it’s done, we will define the fillable properties. We can achieve this by adding the code line shared below in the product.php file located under <strong>app/Models/Product.php</strong>.</p><p>You will need to add it under the product class, as shown in the screenshot below:</p><ol><li>protected $fillable = [‘name’, ‘description’];</li></ol><h3>Step 3: Creating Controller</h3><p>Now we will create the <strong>Controller</strong>, which will be used to handle product-related requests. You will need to run the following command under the <strong>root </strong>directory:</p><ol><li>php artisan make:controller ProductController</li></ol><p>Now we need to define the <strong>Index Method</strong> by adding the following index code block under the file path <strong>app/Http/Controllers/ProductController.php</strong>.</p><p>Add the following code block to your ProductController.php file. Your ProductController.php should contain only this code:</p><ol><li>&lt;?php</li><li>namespace App\Http\Controllers;</li><li>use App\Models\Product; // Import the Product model</li><li>use Illuminate\Http\Request;</li><li>class ProductController extends Controller</li><li>{</li><li>// Define the index method</li><li>public function <strong>index</strong>()</li><li>{</li><li>// Fetch all products from the database</li><li>$products = Product::<strong>all</strong>();</li><li>// Pass the products data to the view</li><li>return <strong>view</strong>(‘products.index’, <strong>compact</strong>(‘products’));</li><li>}</li><li>}</li></ol><h3>Step 4: Creating View and Layout</h3><p>In this step, we will create a product and layout directory under <strong>resources/views/</strong>.</p><p>Now we will create a layout directory under views, the same as we did for the product directory.</p><p>Next, we will create a View File named<strong> index.blade.php</strong> under <strong>resources/views/products/</strong> with the following code block and <strong>save </strong>it:</p><ol><li>@<strong>extends</strong>(‘layouts.app’)</li><li>@<strong>section</strong>(‘content’)</li><li>&lt;h1&gt;Our Products&lt;/h1&gt;</li><li>@<strong>foreach</strong>($products as $product)</li><li>&lt;div class=”product”&gt;</li><li>&lt;h2&gt;{{ $product-&gt;name }}&lt;/h2&gt;</li><li>&lt;p&gt;{{ $product-&gt;description }}&lt;/p&gt;</li><li>&lt;/div&gt;</li><li>@endforeach</li><li>@endsection</li></ol><p>Now we will add the following code under the layout directory by creating a <strong>new file</strong> with the name <strong>app.blade.php</strong> and <strong>save </strong>it.</p><ol><li>&lt;html lang=”en”&gt;</li><li>&lt;head&gt;</li><li>&lt;meta charset=”UTF-8&quot;&gt;</li><li>&lt;meta name=”viewport” content=”width=device-width, initial-scale=1.0&quot;&gt;</li><li>&lt;title&gt;My Laravel App&lt;/title&gt;</li><li>&lt;link rel=”stylesheet” href=”{{ asset(‘css/app.css’) }}”&gt; &lt;! — Link to your CSS →</li><li>&lt;/head&gt;</li><li>&lt;body&gt;</li><li>&lt;div class=”container”&gt;</li><li>@<strong>yield</strong>(‘content’) &lt;! — This is where your content will be injected →</li><li>&lt;/div&gt;</li><li>&lt;/body&gt;</li><li>&lt;/html&gt;</li></ol><h3>Step 5: Defining Routes</h3><p>Here we will open the Routes File under routes/web.php. We will add the Route for Products Index shared in the code block below:</p><ol><li>use App\Http\Controllers\ProductController;</li><li>.</li><li>.</li><li>.</li><li>// Define route for products index</li><li>Route::<strong>get</strong>(‘/products’, [ProductController::class, ‘index’]);</li></ol><p>Following these steps has allowed you to successfully show products from your database using Laravel’s models and views. This method improves the user experience while maintaining your code’s organization by providing dynamic information in response to user queries.</p><p>A list of your items should now be appropriately displayed on your homepage when you visit /products. We added the following product details as samples — you can add your products to get your expected output.</p><h3>Final Words.</h3><p>In this guide, we explored the essential concepts of Models and Views in Laravel, helping you understand how data management and user interfaces are structured within this framework.</p><p>We looked at how Models simplify interactions with the database and how Views, using the Blade templating engine, allow for dynamic and flexible presentation of data.</p><p>Using these concepts, you can build applications that balance powerful back-end functionality with a responsive user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2ec69d9f7ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Welcome to django-taggit! ]]></title>
            <link>https://medium.com/@yashnarsamiyev2/welcome-to-django-taggit-a38c1ff4bb9a?source=rss-1775992469b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a38c1ff4bb9a</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-taggit]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Yashnarbek Samiyev]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 12:29:35 GMT</pubDate>
            <atom:updated>2024-02-06T12:29:35.860Z</atom:updated>
            <content:encoded><![CDATA[<h3>django-taggit’s documentation</h3><p>django-taggit is a reusable Django application designed to make adding tagging to your project easy and fun.</p><p>django-taggit works with Django 4.1+ and Python 3.8+.</p><h3>Getting Started</h3><p>To get started using django-taggit simply install it with pip:</p><pre>$ pip install django-taggit</pre><p>Add &quot;taggit&quot; to your project’s INSTALLED_APPS setting.</p><p>Run ./manage.py migrate.</p><p>And then to any model you want tagging on do the following:</p><pre>from django.db import models</pre><pre>from taggit.managers import TaggableManager</pre><pre>class Food(models.Model):<br>    # ... fields here</pre><pre>    tags = TaggableManager()</pre><p>If you want django-taggit to be <strong>CASE-INSENSITIVE</strong> when looking up existing tags, you’ll have to set TAGGIT_CASE_INSENSITIVE (in settings.py or wherever you have your Django settings) to True (False by default):</p><pre>TAGGIT_CASE_INSENSITIVE = True</pre><h3>Settings</h3><p>The following Django-level settings affect the behavior of the library</p><ul><li>TAGGIT_CASE_INSENSITIVE</li><li>When set to True, tag lookups will be case insensitive. This defaults to False.</li><li>TAGGIT_STRIP_UNICODE_WHEN_SLUGIFYING When this is set to True, tag slugs will be limited to ASCII characters. In this case, if you also have unidecode installed, then tag sluggification will transform a tag like あい うえお to ai-ueo. If you do not have unidecode installed, then you will usually be outright stripping unicode, meaning that something like helloあい will be slugified as hello.</li><li>This value defaults to False, meaning that unicode is preserved in slugification.</li><li>Because the behavior when True is set leads to situations where slugs can be entirely stripped to an empty string, we recommend not activating this.</li></ul><h3>Tags in forms</h3><p>The TaggableManager will show up automatically as a field in a ModelForm or in the admin. Tags input via the form field are parsed as follows:</p><ul><li>If the input doesn’t contain any commas or double quotes, it is simply treated as a space-delimited list of tag names.</li><li>If the input does contain either of these characters:</li><li>Groups of characters which appear between double quotes take precedence as multi-word tags (so double quoted tag names may contain commas). An unclosed double quote will be ignored.</li><li>Otherwise, if there are any unquoted commas in the input, it will be treated as comma-delimited. If not, it will be treated as space-delimited.</li></ul><h3>Examples:</h3><p>Tag input string</p><p>Resulting tags</p><p>Notes</p><p>apple ball cat</p><p>[&quot;apple&quot;, &quot;ball&quot;, &quot;cat&quot;]</p><p>No commas, so space delimited</p><p>apple, ball cat</p><p>[&quot;apple&quot;, &quot;ball cat&quot;]</p><p>Comma present, so comma delimited</p><p>“apple, ball” cat dog</p><p>[&quot;apple, ball&quot;, &quot;cat&quot;, &quot;dog&quot;]</p><p>All commas are quoted, so space delimited</p><p>“apple, ball”, cat dog</p><p>[&quot;apple, ball&quot;, &quot;cat dog&quot;]</p><p>Contains an unquoted comma, so comma delimited</p><p>apple “ball cat” dog</p><p>[&quot;apple&quot;, &quot;ball cat&quot;, &quot;dog&quot;]</p><p>No commas, so space delimited</p><p>“apple” “ball dog</p><p>[&quot;apple&quot;, &quot;ball&quot;, &quot;dog&quot;]</p><p>Unclosed double quote is ignored</p><h3>commit=False</h3><p>If, when saving a form, you use the commit=False option you’ll need to call save_m2m() on the form after you save the object, just as you would for a form with normal many to many fields on it:</p><pre>if request.method == &quot;POST&quot;:<br>    form = MyFormClass(request.POST)<br>    if form.is_valid():<br>        obj = form.save(commit=False)<br>        obj.user = request.user<br>        obj.save()<br>        # Without this next line the tags won&#39;t be saved.<br>        form.save_m2m()</pre><h3>Using tags in the admin</h3><p>By default if you have a <a href="https://django-taggit.readthedocs.io/en/latest/api.html#TaggableManager"><strong>TaggableManager</strong></a> on your model it will show up in the admin, just as it will in any other form.</p><p>If you are specifying <a href="https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fieldsets"><strong>ModelAdmin.fieldsets</strong></a>, include the name of the <a href="https://django-taggit.readthedocs.io/en/latest/api.html#TaggableManager"><strong>TaggableManager</strong></a> as a field:</p><pre>fieldsets = (<br>    (None, {&#39;fields&#39;: (&#39;tags&#39;,)}),<br>)</pre><h3>Including tags in ModelAdmin.list_display</h3><p>One important thing to note is that you <em>cannot</em> include a <a href="https://django-taggit.readthedocs.io/en/latest/api.html#TaggableManager"><strong>TaggableManager</strong></a> in <a href="https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display"><strong>ModelAdmin.list_display</strong></a>. If you do you’ll see an exception that looks like:</p><pre>AttributeError: &#39;_TaggableManager&#39; object has no attribute &#39;name&#39;</pre><p>This is for the same reason that you cannot include a <a href="https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.ManyToManyField"><strong>ManyToManyField</strong></a>: it would result in an unreasonable number of queries being executed.</p><p>If you want to show tags in <a href="https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display"><strong>ModelAdmin.list_display</strong></a>, you can add a custom display method to the <a href="https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin"><strong>ModelAdmin</strong></a>, using <a href="https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.prefetch_related"><strong>prefetch_related()</strong></a> to minimize queries:</p><pre>class MyModelAdmin(admin.ModelAdmin):<br>    list_display = [&#39;tag_list&#39;]</pre><pre>    def get_queryset(self, request):<br>        return super().get_queryset(request).prefetch_related(&#39;tags&#39;)</pre><pre>    def tag_list(self, obj):<br>        return u&quot;, &quot;.join(o.name for o in obj.tags.all())</pre><h3>Usage With Django Rest Framework</h3><p>Because the tags in django-taggit need to be added into a TaggableManager() we cannot use the usual Serializer that we get from Django REST Framework. Because this is trying to save the tags into a list, which will throw an exception.</p><p>To accept tags through a REST API call we need to add the following to our Serializer:</p><pre>from taggit.serializers import (TagListSerializerField,<br>                                TaggitSerializer)<br></pre><pre>class YourSerializer(TaggitSerializer, serializers.ModelSerializer):</pre><pre>    tags = TagListSerializerField()</pre><pre>    class Meta:<br>        model = YourModel<br>        fields = &#39;__all__&#39;</pre><h3>The API</h3><p>After you’ve got your TaggableManager added to your model you can start playing around with the API.</p><p><em>class </em><strong>TaggableManager</strong>([<em>verbose_name=”Tags”</em>, <em>help_text=”A comma-separated list of tags.”</em>, <em>through=None</em>, <em>blank=False</em>])Parameters:</p><ul><li><strong>verbose_name</strong> — The verbose_name for this field.</li><li><strong>help_text</strong> — The help_text to be used in forms (including the admin).</li><li><strong>through</strong> — The through model, see <a href="https://django-taggit.readthedocs.io/en/latest/custom_tagging.html">Customizing taggit</a> for more information.</li><li><strong>blank</strong> — Controls whether this field is required.</li></ul><p><strong>add</strong>(<em>*tags</em>, <em>through_defaults=None</em>, <em>tag_kwargs=None</em>)</p><p>This adds tags to an object. The tags can be either Tag instances, or strings:</p><pre>&gt;&gt;&gt; apple.tags.all()<br>[]<br>&gt;&gt;&gt; apple.tags.add(&quot;red&quot;, &quot;green&quot;, &quot;fruit&quot;)</pre><p>Use the through_defaults argument to specify values for your custom through model, if needed.</p><p>The tag_kwargs argument allows one to specify parameters for the tags themselves.</p><p><strong>remove</strong>(<em>*tags</em>)</p><p>Removes a tag from an object. No exception is raised if the object doesn’t have that tag.</p><p><strong>clear</strong>()</p><p>Removes all tags from an object.</p><p><strong>set</strong>(<em>tags</em>, <em>*</em>, <em>through_defaults=None</em>, <em>clear=False</em>)</p><p>If clear = True removes all the current tags and then adds the specified tags to the object. Otherwise sets the object’s tags to those specified, removing only the missing tags and adding only the new tags.</p><p>Use the through_defaults argument to specify values for your custom through model, if needed.</p><p><strong>similar_objects</strong>()</p><p>Returns a list (not a lazy QuerySet) of other objects tagged similarly to this one, ordered with most similar first. Each object in the list is decorated with a similar_tags attribute, the number of tags it shares with this object.</p><p>If the model is using generic tagging (the default), this method searches tagged objects from all classes. If you are querying on a model with its own tagging through table, only other instances of the same model will be returned.</p><p><strong>names</strong>()</p><p>Convenience method, returning a ValuesListQuerySet (basically just an iterable) containing the name of each tag as a string:</p><pre>&gt;&gt;&gt; apple.tags.names()<br>[&quot;green and juicy&quot;, &quot;red&quot;]</pre><p><strong>slugs</strong>()</p><p>Convenience method, returning a ValuesListQuerySet (basically just an iterable) containing the slug of each tag as a string:</p><pre>&gt;&gt;&gt; apple.tags.slugs()<br>[&quot;green-and-juicy&quot;, &quot;red&quot;]</pre><p>Hint</p><p>You can subclass _TaggableManager (note the underscore) to add methods or functionality. TaggableManager takes an optional manager keyword argument for your custom class, like this:</p><pre>class Food(models.Model):<br>    # ... fields here<br>    tags = TaggableManager(manager=_CustomTaggableManager)</pre><h3>Filtering</h3><p>To find all of a model with a specific tags you can filter, using the normal Django ORM API. For example if you had a Food model, whose TaggableManager was named tags, you could find all the delicious fruit like so:</p><pre>&gt;&gt;&gt; Food.objects.filter(tags__name__in=[&quot;delicious&quot;])<br>[&lt;Food: apple&gt;, &lt;Food: pear&gt;, &lt;Food: plum&gt;]</pre><p>If you’re filtering on multiple tags, it’s very common to get duplicate results, because of the way relational databases work. Often you’ll want to make use of the distinct() method on QuerySets:</p><pre>&gt;&gt;&gt; Food.objects.filter(tags__name__in=[&quot;delicious&quot;, &quot;red&quot;])<br>[&lt;Food: apple&gt;, &lt;Food: apple&gt;]<br>&gt;&gt;&gt; Food.objects.filter(tags__name__in=[&quot;delicious&quot;, &quot;red&quot;]).distinct()<br>[&lt;Food: apple&gt;</pre><p>You can also filter by the slug on tags. If you’re using a custom Tag model you can use this API to filter on any fields it has.</p><h3>Frequently Asked Questions</h3><ul><li>How can I get all my tags?</li></ul><blockquote><em>If you are using just an out-of-the-box setup, your tags are stored in the Tag model (found in taggit.models). If this is a custom model (for example you have your own models derived from ItemBase), then you’ll need to query that one instead.</em></blockquote><blockquote><em>So if you are using the standard setup, </em><em>Tag.objects.all() will give you the tags.</em></blockquote><ul><li>How can I use this with factory_boy?</li></ul><blockquote><em>Since these are all built off of many-to-many relationships, you can check out </em><a href="https://factoryboy.readthedocs.io/en/stable/recipes.html#simple-many-to-many-relationship"><em>factory_boy’s documentation on this topic</em></a><em> and get some ideas on how to deal with tags.</em></blockquote><blockquote><em>One way to handle this is with post-generation hooks:</em></blockquote><blockquote><strong><em>class</em></strong><em> ProductFactory</em><strong><em>(</em></strong><em>DjangoModelFactory</em><strong><em>):</em></strong><em> </em># Rest of the stuff<em> @post_generation </em><strong><em>def</em></strong><em> tags</em><strong><em>(</em></strong><em>self</em><strong><em>,</em></strong><em> create</em><strong><em>,</em></strong><em> extracted</em><strong><em>,</em></strong><em> **kwargs</em><strong><em>):</em></strong><em> </em><strong><em>if</em></strong><em> </em><strong><em>not</em></strong><em> create</em><strong><em>:</em></strong><em> </em><strong><em>return</em></strong><em> </em><strong><em>if</em></strong><em> extracted</em><strong><em>:</em></strong><em> self.tags.add</em><strong><em>(</em></strong><em>*extracted</em><strong><em>)</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a38c1ff4bb9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to add CkEditor in Django ]]></title>
            <link>https://medium.com/@yashnarsamiyev2/how-to-add-ckeditor-in-django-aa6de5a09862?source=rss-1775992469b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa6de5a09862</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[ckeditor]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Yashnarbek Samiyev]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 06:38:22 GMT</pubDate>
            <atom:updated>2024-01-19T06:38:22.182Z</atom:updated>
            <content:encoded><![CDATA[<p>Ckeditor, a WYSIWYG rich text editor allows users to write content directly inside web pages or online applications. A Django WYSIWYG editor built upon CKEditor, you can use it as a standalone widget, or use the provided RichTextField or RichTextUploadingField on your models.</p><p>In this tutorial we will discuss:</p><blockquote>Installation and configuration</blockquote><blockquote>django-ckeditor integration with admin</blockquote><blockquote>django-ckeditor integration in your forms and views.</blockquote><blockquote>Following django-ckeditor functionalities: Image upload, Youtube videos integration, GIFs integration, Code editor</blockquote><h3>Installation and Configuration.</h3><p>Install django-ckeditor.</p><p><em>pip install django-ckeditor</em></p><p><strong>Note: In this tutorial, I am using django==3.2.15 and django-ckeditor==6.0.0</strong></p><p><strong>Please make sure you use the same versions. I tried using django-ckeditor==6.3.2 but RichTextUploadingField field was not appearing in the admin panel. So please follow the same steps and versions.</strong></p><p>Add ckeditor in INSTALLED_APPS in your settings.py</p><pre># settings.py</pre><pre>INSTALLED_APPS = [<br>    ...<br>    &#39;ckeditor&#39;,<br>]</pre><p>Then set STATIC_ROOT in your settings.py file.</p><pre># settings.py</pre><pre># if you are using pathlib Path<br>STATIC_ROOT = BASE_DIR / &#39;static&#39;</pre><pre>#if you are using os<br>STATIC_ROOT = os.path.join(BASE_DIR, &#39;static&#39;)</pre><p>Then run python manage.py collectstatic command. This command will copy the django-ckeditor static and media resources into the directory given by the STATIC_ROOT.</p><p>After running this command you will get this message in the terminal and also a folder named static/ckeditor</p><blockquote><em>1383 static files copied to ‘your path’.</em></blockquote><p>Also, add media file settings in the settings.py file.</p><pre># settings.py</pre><pre>MEDIA_URL = &#39;/media/&#39;<br>MEDIA_ROOT = BASE_DIR / &#39;media&#39;</pre><p>Then set some ckeditor settings in your settings file</p><pre># settings.py </pre><pre># CKEditor Settings<br>CKEDITOR_UPLOAD_PATH = &#39;uploads/&#39;<br>CKEDITOR_IMAGE_BACKEND = &quot;pillow&quot;<br>CKEDITOR_JQUERY_URL = &#39;//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js&#39; </pre><pre>CKEDITOR_CONFIGS = {<br>    &#39;default&#39;:<br>        {<br>            &#39;toolbar&#39;: &#39;full&#39;,<br>            &#39;width&#39;: &#39;auto&#39;,<br>            &#39;extraPlugins&#39;: &#39;,&#39;.join([<br>                &#39;codesnippet&#39;,<br>            ]),<br>        },<br>}</pre><p>You can check more configurations from the <a href="https://pypi.org/project/django-ckeditor/#example-ckeditor-configuration">documentation</a>.</p><h3>Main urls.py</h3><p>Go to main_project/urls.py and add the following URL.</p><pre>#urls.py</pre><pre>from django.contrib import admin<br>from django.urls import path, include<br>from django.conf.urls.static import static<br>from django.conf import settings</pre><pre>urlpatterns = [<br>    .....<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;ckeditor/&#39;, include(&#39;ckeditor_uploader.urls&#39;)),<br>]</pre><pre>urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)</pre><pre>if settings.DEBUG:<br>    urlpatterns+=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)<br>    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)</pre><h3>Models.py</h3><p>We are using <strong>RichTextUploadingField </strong>for file support.</p><pre># models.py</pre><pre>from django.db import models<br>from django.utils.translation import gettext_lazy as _<br>from ckeditor_uploader.fields import RichTextUploadingField</pre><pre>class BlogPost(models.Model):<br>    title = models.CharField(<br>        _(&quot;Blog Title&quot;), max_length=250,<br>        null=False, blank=False<br>    )<br>    body = RichTextUploadingField()</pre><pre>    def __str__(self):<br>        return self.title</pre><p>Then run migrations.</p><h3>Register your models in admin.py</h3><pre># admin.py</pre><pre>from django.contrib import admin<br>from .models import BlogPost<br></pre><pre>admin.site.register(BlogPost)</pre><p>Then open the admin panel. You will see Ckeditor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iHdYE1p7tlXM8dbr.PNG" /></figure><h3>django-ckeditor integration in your forms and views.</h3><pre># forms.py</pre><pre>from django import forms<br>from ckeditor_uploader.widgets import CKEditorUploadingWidget</pre><pre>from blogs.models import BlogPost</pre><pre>class BlogForm(forms.ModelForm):<br>    body = forms.CharField(widget=CKEditorUploadingWidget())</pre><pre>    class Meta:<br>        model = BlogPost<br>        fields = &#39;__all__&#39;</pre><pre># views.py</pre><pre>from django.urls import reverse<br>from django.views.generic.edit import CreateView<br>from django.contrib.messages.views import SuccessMessageMixin</pre><pre>from .forms import BlogForm<br>from .models import BlogPost<br></pre><pre>class AddBlog(SuccessMessageMixin, CreateView):<br>    form_class = BlogForm<br>    model = BlogPost<br>    template_name = &quot;blogs/add_blogs.html&quot;<br>    success_message = &quot;Added Succesfully&quot;</pre><pre>    def get_success_url(https://medium.com/self):<br>        return reverse(&#39;add_blogs&#39;)</pre><pre># app/urls.py</pre><pre>from django.urls import path<br>from .views import AddBlog<br></pre><pre>urlpatterns = [<br>    path(&#39;create/&#39;, AddBlog.as_view(), name=&#39;add_blogs&#39;),<br>]</pre><p>Then add template blogs/add_blogs.html</p><pre>&lt;!-- blogs/add_blogs.html--&gt;</pre><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;<br>    &lt;!-- Bootstrap CSS --&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css&quot; integrity=&quot;sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N&quot; crossorigin=&quot;anonymous&quot;&gt;<br>    &lt;title&gt;CKEditor&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    <br>    &lt;!-- for messages --&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        {% if messages %}<br>            {% for message in messages %}<br>                &lt;div class=&quot;alert alert-{{ message.tags }} alert-dismissible fade show&quot; role=&quot;alert&quot;&gt;<br>                {{message}}<br>                &lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;alert&quot; aria-label=&quot;Close&quot;&gt;<br>                    &lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt;<br>                &lt;/button&gt;<br>                &lt;/div&gt;<br>            {% endfor %}<br>        {% endif %}<br>    &lt;/div&gt;<br>    <br>    &lt;!-- form --&gt;<br>    &lt;div class=&quot;container mt-5&quot;&gt;<br>        &lt;form method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt; <br>            {% csrf_token %} <br>            {{ form.media}}<br>            {% for field in form %}<br>            &lt;div class=&quot;form-group&quot;&gt;<br>                &lt;div&gt;&lt;label for=&quot;{{ field.id_for_label }}&quot; class=&quot;text-dark&quot;&gt;{{ field.label }}: &lt;/label&gt;&lt;/div&gt;<br>                {{ field }}<br>            &lt;/div&gt;<br>            {% endfor %}<br>            &lt;div class=&quot;row justify-content-center&quot;&gt;<br>                &lt;input type=&quot;submit&quot; class=&quot;btn btn-info btn-lg&quot; value=&quot;Create&quot; /&gt;<br>            &lt;/div&gt;<br>        &lt;/form&gt;<br>    &lt;/div&gt;<br>    <br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js&quot; integrity=&quot;sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js&quot; integrity=&quot;sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Go to <a href="http://127.0.0.1:8000/blogs/create/">http://127.0.0.1:8000/blogs/create/.</a> You will see following page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p0k0HJTnetJKPhk9.PNG" /></figure><h3>django-ckeditor Functionalities.</h3><h3>How to upload an image in django-ckeditor.</h3><p>If you are using RichTextField field instead of RichTextUploadingField. Then you won&#39;t see <strong>Upload </strong>option in image upload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*RNyXjGUq84iM51mN.PNG" /></figure><h3>How to add Code snippet in django-ckeditor.</h3><p>You can add code snippets using the option available on the right side of the insert image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*pfdoJ48ebR96Mov0.PNG" /></figure><h3>How to add Youtube videos or GIFs in django-ckeditor.</h3><p>You can also use youtube videos or GIFs in CKEditor using the Iframe option.</p><p>There is another option to add iframes (youtube iframes or any). You can add using the <strong>Source </strong>button which is the first button in the editor toolbar.</p><h3>How can I view/add the HTML (source code) of this blog post?</h3><p>Go to the <strong>Source </strong>button which is the first button in the editor toolbar. You can add and view HTML using the Source button.</p><p><strong>USE CASE: </strong>For example, you have an HTML of your blog and you want to copy that to your ckeditor. Then you can add that HTML easily by pressing the <strong>Source </strong>button.</p><p>If you like this post then show some love by clapping. 👈 😘</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa6de5a09862" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[pre-commit with Django ]]></title>
            <link>https://medium.com/@yashnarsamiyev2/pre-commit-with-django-6d49760ed971?source=rss-1775992469b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d49760ed971</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Yashnarbek Samiyev]]></dc:creator>
            <pubDate>Wed, 17 Jan 2024 11:36:41 GMT</pubDate>
            <atom:updated>2024-01-17T11:36:41.692Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*WDlhxl87Ers_uIvy.png" /></figure><p><a href="https://pre-commit.com/">pre-commit</a> is a widely-used code quality framework. It allows a developer to add <a href="https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks">hooks</a> for various code quality tools that check your code for any errors or issues <em>before</em> committing them to a repository. Django adopted pre-commit in 2020, and for many developers, it is an indispensable tool used on basically every project.</p><p>In this tutorial, we will create a new Django project, install pre-commit, and configure three of the more popular Django-related hooks:</p><ul><li><a href="https://github.com/psf/black">Black</a>, the Python code formatter</li><li><a href="https://github.com/PyCQA/isort">isort</a>, to sort and group imports properly</li><li><a href="https://github.com/astral-sh/ruff">ruff</a>, a Python linter written in Rust</li></ul><h3>Django setup</h3><p>Let’s go through the standard installation for a new Django project. On the command line, navigate to a new directory, create a new virtual environment, and install Django.</p><pre># Windows<br>$ python -m venv .venv<br>$ .venv\Scripts\Activate.ps1<br>(.venv) $ python -m pip install django~=4.2.0</pre><pre># macOS<br>$ python3 -m venv .venv<br>$ source .venv/bin/activate<br>(.venv) $ python3 -m pip install django~=4.2.0</pre><p>Create a new project called django_project and then run runserver to start up the local web server and view the Django welcome page in your web browser at 127.0.0.1:8000.</p><pre>(.venv) $ django-admin startproject django_project .<br>(.venv) $ python manage.py runserver</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JA8nMWSlioq4Iyy3.png" /></figure><h3>Install pre-commit</h3><p>There are multiple ways to <a href="https://pre-commit.com/#installation">install pre-commit</a>. In this tutorial, we will use pip, but some developers on macOS prefer installing it via Homebrew and updating it that way.</p><pre>(.venv) $ python -m pip install pre-commit</pre><p>To confirm it installed correctly, check its version:</p><pre>(.venv) $ pre-commit version<br>pre-commit 3.3.3</pre><h3>Add a configuration file</h3><p>pre-commit is configured via a .pre-commit-config.yaml file located in the root of your directory. Create this new file now with your text editor.</p><pre>├── .pre-commit-config.yaml  # new<br>├── db.sqlite3<br>├── django_project<br>│   ├── ...<br>└── manage.py</pre><p>There is a helpful command to output a sample configuration.</p><pre>(.venv) $ pre-commit sample-config<br># See https://pre-commit.com for more information<br># See https://pre-commit.com/hooks.html for more hooks<br>repos:<br>-   repo: https://github.com/pre-commit/pre-commit-hooks<br>    rev: v3.2.0<br>    hooks:<br>    -   id: trailing-whitespace<br>    -   id: end-of-file-fixer<br>    -   id: check-yaml<br>    -   id: check-added-large-files</pre><p>Briefly, this configuration references the source repository, version number, and contains four <em>hooks</em> that respectively remove whitespace, make sure text files end with a newline, check that YAML files are valid, and prevent large files (the default is 500kB) from being committed.</p><p>Copy and paste this into the .pre-commit-config.yaml file.</p><pre># .pre-commit-config.yaml<br>repos:<br>-   repo: https://github.com/pre-commit/pre-commit-hooks<br>    rev: v3.2.0<br>    hooks:<br>    -   id: trailing-whitespace<br>    -   id: end-of-file-fixer<br>    -   id: check-yaml<br>    -   id: check-added-large-files</pre><p>It is also possible — and highly recommended — to specify which version of Python pre-commit should be used to run hooks. This can be done via the default_language_version <a href="https://pre-commit.com/#pre-commit-configyaml---top-level">top-level key</a>. We are using Python 3.11 here.</p><pre># .pre-commit-config.yaml<br>default_language_version:<br>  python: python3.11</pre><pre>repos:<br>-   repo: <a href="https://github.com/pre-commit/pre-commit-hooks">https://github.com/pre-commit/pre-commit-hooks</a><br>    rev: v3.2.0<br>    hooks:<br>    -   id: trailing-whitespace<br>    -   id: end-of-file-fixer<br>    -   id: check-yaml<br>    -   id: check-added-large-files</pre><h3>Git setup</h3><p>Make sure that git is <a href="https://git-scm.com/book/en/v2/Getting-Started-Installing-Git">already installed</a> since we can’t use pre-commit without git itself.</p><p>Confirm that git is installed by checking its version number.</p><pre>(.venv) $ git --version<br>git version 2.39.2 (Apple Git-143)</pre><p>Then add a .gitignore file to the root directory and include one line excluding the virtual environment directory, .venv.</p><pre># .gitignore<br>.venv</pre><p>We can now initialize a new repository and add all changed files, but <em>do not</em> commit it yet.</p><pre>(.venv) $ git init<br>(.venv) $ git add .</pre><h3>Install git hook scripts</h3><p>Run the pre-commit install command to set up the git hook scripts in our repository.</p><pre>(.venv) $ pre-commit install<br>pre-commit installed at .git/hooks/pre-commit</pre><p>pre-commit will now run automatically on any future git commit command!</p><p>When adding new hooks, it is a good idea to run them against <em>all</em> files since usually, pre-commit only runs on changed files during git hooks.</p><pre>(.venv)<br>$ pre-commit run --all-files<br>Trim Trailing Whitespace.................................................Passed<br>Fix End of Files.........................................................Failed<br>- hook id: end-of-file-fixer<br>- exit code: 1<br>- files were modified by this hook</pre><pre>Fixing .gitignore</pre><pre>Check Yaml...............................................................Passed<br>Check for added large files..............................................Passed</pre><p>What’s this? Our pre-commit hook noticed an error already: we failed to add an extra line to the end of the .gitignore file, so it flagged it as &quot;failed&quot; and then fixed it automatically. If you look at the .gitignore file, you&#39;ll see a second line now.</p><pre># .gitignore<br>.venv</pre><p>Everything will pass if you run pre-commit run --all-files again.</p><pre>(.venv) $ pre-commit run --all-files<br>Trim Trailing Whitespace.................................................Passed<br>Fix End of Files.........................................................Passed<br>Check Yaml...............................................................Passed<br>Check for added large files..............................................Passed</pre><p>It’s time to stage the changes to the .gitignore file and make our first git commit.</p><pre>(.venv) $ git add .<br>(.venv) $ git commit -m &quot;initial commit&quot;</pre><h3>Add hooks: Black</h3><p><a href="https://black.readthedocs.io/">Black</a> is a popular Python code formatter that checks all code against the <a href="https://peps.python.org/pep-0008/">PEP 8</a> standard. Django has formally adopted it per <a href="https://github.com/django/deps/blob/main/final/0008-black.rst">DEP 8</a>. We can add it to our .pre-commit-config.yaml file as a hook.</p><pre># .pre-commit-config.yaml<br>default_language_version:<br>  python: python3.11</pre><pre>repos:<br>-   repo: <a href="https://github.com/pre-commit/pre-commit-hooks">https://github.com/pre-commit/pre-commit-hooks</a><br>    rev: v4.4.0<br>    hooks:<br>    -   id: trailing-whitespace<br>    -   id: end-of-file-fixer<br>    -   id: check-yaml<br>    -   id: check-added-large-files<br>-   repo: <a href="https://github.com/psf/black">https://github.com/psf/black</a><br>    rev: 23.7.0<br>    hooks:<br>    -   id: black</pre><p>Make sure to include that extra line at the end of the file, or pre-commit will complain. Now add our changes to git. Since we are adding a new hook, it is necessary to run it initially against <em>all</em> files.</p><pre>(.venv) $ git add .<br>(.venv) $ pre-commit run --all-files <br>trim trailing whitespace.................................................Passed<br>fix end of files.........................................................Passed<br>check yaml...............................................................Passed<br>check for added large files..............................................Passed<br>black....................................................................Passed</pre><p>Everything passed, so we can make a git commit with a message about adding a hook for Black.</p><pre>(.venv) $ git commit -m &quot;add Black hook&quot;<br>trim trailing whitespace.................................................Passed<br>fix end of files.........................................................Passed<br>check yaml...............................................................Passed<br>check for added large files..............................................Passed<br>black................................................(no files to check)Skipped<br>[main b29d356] add black<br> 1 file changed, 4 insertions(+), 4 deletions(-)</pre><p>Notice that Black “Skipped” running because the only change was to the .pre-commit-config.yaml file, and Black only applies to Python files.</p><h3>pyproject.toml</h3><p>A pyproject.toml file acts as a <a href="https://peps.python.org/pep-0518/">unified Python project settings file</a>. Create a new blank file in your root project directory.</p><pre>├── .pre-commit-config.yaml<br>├── db.sqlite3<br>├── django_project<br>│   ├── ...<br>├── manage.py<br>└── pyproject.toml  # new</pre><p>We can use it to add another layer of configuration to our hooks. First, set a target-version for Python 3.11 within the pyproject.toml file. We can also specify a Python version for our Black hook.</p><pre># pyproject.toml<br>target-version = &quot;py311&quot;</pre><pre>[tool.black]<br>target-version = [&quot;py311&quot;]</pre><p>Now git add the new pyproject.toml file and create a git commit.</p><pre>(.venv) $ git add .<br>(.venv) $ git commit -m &quot;add pyproject.toml file&quot;<br>trim trailing whitespace.................................................Passed<br>fix end of files.........................................................Passed<br>check yaml...........................................(no files to check)Skipped<br>check for added large files..............................................Passed<br>black................................................(no files to check)Skipped<br>[main d247439] pyproject.toml<br> 1 file changed, 4 insertions(+)<br> create mode 100644 pyproject.toml</pre><h3>Add hooks: isort</h3><p><a href="https://pycqa.github.io/isort/">isort</a> is a code formatter that sorts imports automatically. It is a very popular package and has been used by Django since 2015. To add it as a hook, update the .pre-commit-config.yaml file as follows:</p><pre># .pre-commit-config.yaml<br>default_language_version:<br>  python: python3.11</pre><pre>repos:<br>-   repo: <a href="https://github.com/pre-commit/pre-commit-hooks">https://github.com/pre-commit/pre-commit-hooks</a><br>    rev: v4.4.0<br>    hooks:<br>    -   id: trailing-whitespace<br>    -   id: end-of-file-fixer<br>    -   id: check-yaml<br>    -   id: check-added-large-files<br>-   repo: <a href="https://github.com/psf/black">https://github.com/psf/black</a><br>    rev: 23.7.0<br>    hooks:<br>    -   id: black<br>-   repo: <a href="https://github.com/pycqa/isort">https://github.com/pycqa/isort</a> <br>    rev: 5.12.0<br>    hooks:<br>    -   id: isort</pre><p>Then run the new hook against all files.</p><pre>(.venv) $ pre-commit run --all-files<br>trim trailing whitespace.................................................Passed<br>fix end of files.........................................................Passed<br>check yaml...............................................................Passed<br>check for added large files..............................................Passed<br>black....................................................................Passed<br>isort....................................................................Passed</pre><p>Now it can be added to git and commited with a message.</p><pre>(.venv) $ git add .<br>(.venv) $ git commit -m &quot;add isort hook&quot;<br>trim trailing whitespace.................................................Passed<br>fix end of files.........................................................Passed<br>check yaml...............................................................Passed<br>check for added large files..............................................Passed<br>black................................................(no files to check)Skipped<br>isort................................................(no files to check)Skipped<br>[main 8af5fa2] add isort hook<br> 1 file changed, 4 insertions(+)</pre><h3>Add hooks: ruff</h3><p>Historically, <a href="https://github.com/PyCQA/flake8">flake8</a> was the Python linter of choice, but recently <a href="https://github.com/astral-sh/ruff">ruff</a> has emerged, an alternative written in Rust and promising much faster speeds. I will avoid any deep discussion of flake8 vs ruff other than to say I appreciate both tools but will focus on ruff here. You can see ruff&#39;s take on <a href="https://beta.ruff.rs/docs/faq/#is-ruff-compatible-with-black">comptability with Black</a> in the docs.</p><p>Add ruff as follows to the pre-commit config file.</p><pre># .pre-commit-config.yaml<br>default_language_version:<br>  python: python3.11</pre><pre>repos:<br>-   repo: <a href="https://github.com/pre-commit/pre-commit-hooks">https://github.com/pre-commit/pre-commit-hooks</a><br>    rev: v4.4.0<br>    hooks:<br>    -   id: trailing-whitespace<br>    -   id: end-of-file-fixer<br>    -   id: check-yaml<br>    -   id: check-added-large-files<br>-   repo: <a href="https://github.com/psf/black">https://github.com/psf/black</a><br>    rev: 23.7.0<br>    hooks:<br>    -   id: black<br>        alias: autoformat<br>-   repo: <a href="https://github.com/pycqa/isort">https://github.com/pycqa/isort</a><br>    rev: 5.12.0<br>    hooks:<br>    -   id: isort<br>-   repo: <a href="https://github.com/astral-sh/ruff-pre-commit">https://github.com/astral-sh/ruff-pre-commit</a><br>    rev: v0.0.285<br>    hooks:<br>    -   id: ruff<br>        alias: autoformat<br>        args: [--fix]</pre><p>Then in pyproject.toml, we&#39;ll add some additional configuration to enable Pyflakes by default and ignore errors around line lengths (E501) and ambiguous file names (<a href="https://beta.ruff.rs/docs/rules/ambiguous-variable-name/">E741</a>).</p><pre># pyproject.toml <br>target-version = &quot;py311&quot;</pre><pre>[tool.black]<br>target-version = [&quot;py311&quot;]</pre><pre>[tool.ruff]<br># Enable Pyflakes `E` and `F` codes by default.<br>select = [&quot;E&quot;, &quot;F&quot;]<br>ignore = [&quot;E501&quot;, &quot;E741&quot;]</pre><p>Run ruff against all files now.</p><pre>(.venv) $ pre-commit run --all-files<br>trim trailing whitespace.................................................Passed<br>fix end of files.........................................................Passed<br>check yaml...............................................................Passed<br>check for added large files..............................................Passed<br>black....................................................................Passed<br>isort....................................................................Passed<br>ruff.....................................................................Passed</pre><p>Then we can git add changes to the .pre-commit-config.yaml and pyproject.toml and make a git commit.</p><pre>(.venv) $ git add .<br>(.venv) $ git commit -m &quot;add ruff&quot;<br>trim trailing whitespace.................................................Passed<br>fix end of files.........................................................Passed<br>check yaml...............................................................Passed<br>check for added large files..............................................Passed<br>black................................................(no files to check)Skipped<br>isort................................................(no files to check)Skipped<br>ruff.................................................(no files to check)Skipped<br>[main 979212f] add ruff<br> 2 files changed, 12 insertions(+)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d49760ed971" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Telegram Django Bot за пару строк]]></title>
            <link>https://medium.com/@yashnarsamiyev2/telegram-django-bot-%D0%B7%D0%B0-%D0%BF%D0%B0%D1%80%D1%83-%D1%81%D1%82%D1%80%D0%BE%D0%BA-a714bd030068?source=rss-1775992469b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a714bd030068</guid>
            <category><![CDATA[django-telegram-bot]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Yashnarbek Samiyev]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 15:12:05 GMT</pubDate>
            <atom:updated>2024-01-15T15:12:05.045Z</atom:updated>
            <content:encoded><![CDATA[<p>На Хабре много статей про разработку Телеграм ботов на Python, в том числе при помощи Django. Однако, большинство из них направлено на первичное ознакомление с API Телеграм.</p><p>В этой статье я хочу рассказать как можно упростить разработку ботов, сократив количество кода в разы, и не создавать велосипед.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vVYDDg20zJMZxS7l.png" /></figure><p>Всем, привет! Меня зовут Александр Алескин, и я участвовал в создании десятков Telegram ботов. Достаточно часто я встречался с одними и теми же проблемами при разработке из-за нехватки инструментов: в Телеграме нет web-форм －невозможно от пользователя одновременно запросить несколько атрибутов; поддержка локализации; учет состояния пользователя для отображения информации; над разными типами данных происходят схожие действия, но нужно писать отдельные обработчики под каждый тип и т.д.</p><p>На самом деле все эти проблемы достаточно легко решаются по одиночке. Однако, при расширении функциональности бота это неминуемо приводит к дублированию кода в той или иной степени, а также к путанице среди функций.</p><p>В этой статье пойдет речь об инструментах, которые позволяют стандартизировать разработку ботов. Большинство из них широко применяется в Web-разработке и присутствуют в Django (или Django Rest Framework). Данные инструменты кастомизированы для использования под Телеграм ботов в библиотеке <a href="https://github.com/alexanderaleskin/telegram_django_bot_bridge">Telegram Django Bot</a>, о которой и будет рассказано далее.</p><h3>Telegram-Django-Bot библиотека</h3><p>В основе Telegram-Django-Bot лежит использование следующих двух библиотек:</p><ol><li><a href="https://github.com/python-telegram-bot/python-telegram-bot">Python-Telegram-Bot</a> — библиотека для взаимодействия с Telegram API (22k звезд на github).</li><li><a href="https://github.com/django/django">Django</a> — фреймворк для разработки веб-сервисов (в ТОП-10 фреймворков в мире).</li></ol><p>По факту Telegram-Django-Bot плотно связывает между собой эти библиотеки и предоставляет схожий с <a href="https://www.django-rest-framework.org/">Django Rest Framework</a> инструмент для управления данными.</p><h4>Viewsets и Формы</h4><p>Ключевой сущностью Telegram-Django-Bot является TelegramViewSet – абстрактный класс для управления моделями (таблицами) базы данных, описанных через Django ORM. Данный класс позволяет создавать, отображать, удалять и отображать элементы сущности. Как и в Django Rest Framework Viewsets по необходимости вы можете добавлять свои методы для обработки данных. Однако, в отличие от web аналога, данный класс формирует ответ не в виде json или xml, а на естественном языке в виде текста и кнопок для дальнейшего отображения пользователю в Телеграмме. То есть совмещает обработку данных и формирование интерфейса для пользователей.</p><p>Такой подход шаблонизирует обработку данных и общение бота с пользователем. В итоге это позволяет значительно сократить количество кода.</p><p>Легче всего продемонстрировать этот подход на примере <a href="https://github.com/alexanderaleskin/telergam_django_bot_template">Telegram_django_bot_template</a>. Данный репозиторий создан как шаблон для создания ботов и содержит небольшие примеры по использованию.</p><blockquote><em>Для более подробного и реального примера можно рассмотреть живого бота </em><a href="https://t.me/Disk_Drive_Bot"><em>@Disk_Drive_Bot</em></a><em> (</em><a href="https://github.com/alexanderaleskin/drive_bot"><em>исходный код бота</em></a><em>). Основная цель бота — хранение файлов в Телеграме, так же как это делает Яндекс диск или Гугл драйв.</em></blockquote><p>Так, например, в коде шаблона задается управление некоторой сущностью BotMenuElem (таблицей в базе данных) в 40 строчках кода:</p><pre>class BotMenuElemViewSet(TelegramViewSet):<br>    viewset_name = &#39;BotMenuElem&#39;    # Название Вьюсета для отображения<br>    model_form = BotMenuElemForm   # Форма, где указываются поля для забора от клиента и их валидация. Дочерний класс от Django.forms.ModelForm<br>    queryset = BotMenuElem.objects.all()  # указываем, что за модель базы данных<br>    foreign_filter_amount = 1  # количество переменных окружения (дополнительный атрибут, детали в документации)</pre><pre>    prechoice_fields_values = {  # Часто используемые варианты значений атрибутов или просто формат отображения некоторых значений атрибутов<br>        &#39;is_visable&#39;: (  # варианты для переменной is_visable в формате (значение, текст)<br>            (True, &#39;👁 Visable&#39;),<br>            (False, &#39;🚫 Disabled&#39;),<br>        )<br>    }</pre><pre>    def get_queryset(self):  # переопределение вспомогательной функции для учета бизнес логики<br>        queryset = super().get_queryset()<br>        if self.foreign_filters[0]:  # хотим, чтобы если указана переменная окружения, то отображали только те элементы, в которых поле команда начинались со значения переменной окружения<br>            queryset = queryset.filter(command__contains=self.foreign_filters[0])<br>        return queryset</pre><pre>    def create(self, field=None, value=None, initial_data=None):  # переопределение функции создания элемента<br>        initial_data = {  # просто хотим указать стартовые значения для некоторых атрибутов<br>            &#39;is_visable&#39;: True,<br>            &#39;callbacks_db&#39;: &#39;[]&#39;,<br>            &#39;buttons_db&#39;: &#39;[]&#39;,<br>        }<br>        return super().create(field, value, initial_data)</pre><pre>    def show_list(self, page=0, per_page=10, columns=1):  # переопределение функции отображения списка элементов<br>        reply_action, (mess, buttons) = super().show_list(page, per_page, columns)<br>        buttons += [   # к дефолтному отображению элементов в виде текста и кнопок добавляем кнопки «создание» и «назад»<br>            [InlineKeyboardButtonDJ(<br>                text=_(&#39;➕ Add&#39;),<br>                callback_data=self.gm_callback_data(&#39;create&#39;)<br>            )],<br>            [InlineKeyboardButtonDJ(<br>                text=_(&#39;🔙 Back&#39;),<br>                callback_data=settings.TELEGRAM_BOT_MAIN_MENU_CALLBACK<br>            )],<br>        ]<br>        return reply_action, (mess, buttons)  # для ответа пользователю возвращаем формат ответа и атрибуты ответа (в данном случае текст сообщения и кнопки)</pre><p>И эти 40 строчек позволяют создавать, изменять, удалять и просматривать список элементов BotMenuElem в боте. В результате такого описания BotMenuElemViewSet получаем необходимую бизнес логику и пользовательский интерфейс в боте:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F0wLY1Wxawe4Cgos.png" /></figure><p>Магия заключается в том, что базовая логика взаимодействия и отображения элементов описана в родительском классе TelegramViewSet. В нем присутствуют следующие стандартные функции:</p><p>Метод</p><p>Описание</p><p>create</p><p>Создание модели</p><p>change</p><p>Изменения атрибутов</p><p>delete</p><p>Удаление модели</p><p>show_elem</p><p>Отображение элемента</p><p>show_list</p><p>Отображение списка элементов</p><p>Для удобства кастомизации бизнес логики эти функции вызывают вспомогательные методы внутри. Так, например, в BotMenuElemViewSet переопределяется только одна вспомогательная функция get_queryset под особенности контекста.</p><p>Среди функций TelegramViewSet особый интерес представляют create и update, так как они осуществляют плотную работу с формами (структурой из нескольких атрибутов, которые указывает пользователей). Так как Телеграм не умеет работать с формами, то здесь используется последовательный подход (как и <a href="https://pythontelegramrobot.readthedocs.io/en/latest/telegram.ext.conversationhandler.html">ConversationHandler</a>: сначала пользователей указывает одно поле, затем второе и т.д.:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DCVA-k5NK-_l8qhM.png" /></figure><p>Для этого, как и в Django, создается форма данных, которая указывается в BotMenuElemViewSet:</p><pre># base/forms.py<br>from telegram_django_bot import forms as td_forms</pre><pre>class BotMenuElemForm(td_forms.TelegramModelForm):<br>    class Meta:<br>        model = BotMenuElem<br>        fields = [&#39;command&#39;, &quot;is_visable&quot;, &quot;callbacks_db&quot;, &quot;message&quot;, &quot;buttons_db&quot;]<br></pre><pre># base/views.py<br>class BotMenuElemViewSet(TelegramViewSet): <br>    model_form = BotMenuElemForm<br>    …</pre><h4>Роутинг</h4><p>Структурность кода одна из важных составляющих для поддержания проекта. Для этого Django предлагает разбивать проект на приложения (apps), каждое из которых отвечают за свою задачу (например, оплата или интеграция с каким-нибудь другим сервисом).</p><p>Telegram-Django-Bot делает возможным использование этого механизма при разработке ботов через универсальный обработчик RouterCallbackMessageCommandHandler. Данный класс необходимо добавить в перечень обработчиков веб-сервера Python-Telegram-Bot:</p><pre>from telegram_django_bot.tg_dj_bot import TG_DJ_Bot<br>from telegram_django_bot.routing import RouterCallbackMessageCommandHandler</pre><pre># look in the template: <a href="https://github.com/alexanderaleskin/telergam_django_bot_template/blob/main/run_bot.py#L19">https://github.com/alexanderaleskin/telergam_django_bot_template/blob/main/run_bot.py#L19</a><br>#  in 13.x version of Python-Telegram-Bot:<br>updater = Updater(bot=TG_DJ_Bot(settings.TELEGRAM_TOKEN))<br>updater.dispatcher.add_handler(RouterCallbackMessageCommandHandler())</pre><pre>#  or in 20.x version :<br>bot = TG_DJ_Bot(settings.TELEGRAM_TOKEN)<br>application = ApplicationBuilder().bot(bot).build()<br>application.add_handler(RouterCallbackMessageCommandHandler())</pre><p>После чего можно прописывать пути к конкретным обработчикам (endpoints) и viewsets в стандартной для Django нотации:</p><pre># файл bot_conf/utrls.py (основной)<br>urlpatterns = [<br>    re_path(&#39;&#39;, include((&#39;base.utrls&#39;, &#39;base&#39;), namespace=&#39;base&#39;)),  # подключаем пути из модуля base<br>]<br></pre><pre># файл base/utrls.py<br>from django.urls import re_path, include<br>from .views import start, BotMenuElemViewSet, UserViewSet  # импорт veiwset и обычной функции  <br></pre><pre>urlpatterns = [  # добавляем пути<br>    re_path(&#39;start&#39;, start, name=&#39;start&#39;),<br>    re_path(&#39;main_menu&#39;, start, name=&#39;start&#39;),</pre><pre>    re_path(&#39;sb/&#39;, BotMenuElemViewSet, name=&#39;BotMenuElemViewSet&#39;),<br>    re_path(&#39;us/&#39;, UserViewSet, name=&#39;UserViewSet&#39;),<br>]<br># Теперь по нажатию на кнопку с callback_data=&#39;sb/&lt;suffix&gt;&#39; будут вызываться методы BotMenuElemViewSet</pre><blockquote><em>Как и в Django, необходимо указать главный файл с маршрутизацией запросов в настройках проекта (в </em><a href="http://settings.py/"><em>settings.py</em></a><em> фале):</em></blockquote><blockquote><em>TELEGRAM_ROOT_UTRLCONF = &#39;bot_conf.utrls&#39;</em></blockquote><p>Как результат таких манипуляций приложение может быть разбито на несколько папок, в каждой из которых храниться своя независимая бизнес логика (а если вы пишите не один бот, а несколько, то такой подход позволяет легко подключать отдельные модули).</p><h3>Дополнительные инструменты библиотеки</h3><p>В библиотеке есть также ряд инструментов, которые часто нужны в продакшн ботах:</p><p>Встроенные модели в базе данных:</p><ol><li><strong>ActionLog</strong> — хранит действие пользователей (нажатия на кнопки, нажатие на команды и тд). Данная модель позволяет анализировать активность и действия пользователей;</li><li><strong>TeleDeepLink</strong> — хранит информацию откуда пришел пользователей (если пользователей перешел в бота по <a href="https://core.telegram.org/bots/features#deep-linking">deeplink</a>). Это информация помогает строить воронку продаж и отслеживать эффективность рекламы;</li><li><strong>BotMenuElem</strong> — достаточно часто в боте есть блоки, где указывается статическая информация (например, сообщение о контактах поддержки, база знаний или стартовое сообщение). Данная модель дает возможность создавать такие блоки меню в боте, при этом указывать ссылки на другие элементы или функции/вьюсеты через кнопки. В примере темплейта как раз используется эта модель (стандартное создание предполагается через администраторскую панель).</li><li><strong>Trigger</strong> — при наступлении определенных событий (смотрит в ActionLog) отправляет определенные сообщения пользователям (BotMenuElem). Так, например, можно отправлять сообщения пользователям, которые стартанули бота и не продолжили взаимодействия, или попросить пользователей, которые пользуются больше 7 дней к примеру, дать обратную связь о взаимодействии с ботом;</li><li>Дополнительные функции:</li><li>telegram_django_bot.utils.<strong>handler_decor</strong> — обертка для своих обработчиков (<a href="https://github.com/alexanderaleskin/telergam_django_bot_template/blob/main/base/views.py#L16">Пример использования</a>; вьюсеты автоматически оборачиваются в декоратор). Позволяет логировать действие пользователей, ловить и логировать все ошибки, а также обрабатывать создание пользователей;</li><li>Telegram_django_bot.utils.<strong>CalendarPagination</strong>– класс для генерации календаря в меню бота в виде активных кнопок (по нажатию можно перейти в другие разделы);</li><li>Telegram_django_bot.tg_dj_bot.<strong>TG_DJ_Bot</strong> — дочерний класс telegram.Bot, который добавляет ряд функций в том числе task_send_message_handler для безопасной рассылки сообщений группе пользователей (обрабатывает ошибки при отправке сообщений).</li><li><strong>Локализация</strong> — используется инструменты локализации Django.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a714bd030068" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective Python Testing With Pytest ]]></title>
            <link>https://medium.com/@yashnarsamiyev2/effective-python-testing-with-pytest-c6be7079143c?source=rss-1775992469b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6be7079143c</guid>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Yashnarbek Samiyev]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 13:07:32 GMT</pubDate>
            <atom:updated>2024-01-13T13:10:22.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*YhcHUn0BynIx7cOS2Rg6wg.png" /></figure><p><a href="https://realpython.com/python-testing/">Testing your code</a> brings a wide variety of benefits. It increases your confidence that the code behaves as you expect and ensures that changes to your code won’t cause regressions. Writing and maintaining tests is hard work, so you should leverage all the tools at your disposal to make it as painless as possible. <a href="https://docs.pytest.org/">pytest</a> is one of the best tools that you can use to boost your testing productivity.</p><p><strong>In this tutorial, you’ll learn:</strong></p><ul><li>What <strong>benefits</strong> pytest offers</li><li>How to ensure your tests are <strong>stateless</strong></li><li>How to make repetitious tests more <strong>comprehensible</strong></li><li>How to run <strong>subsets</strong> of tests by name or custom groups</li><li>How to create and maintain <strong>reusable</strong> testing utilities</li></ul><h3>How to Install pytest</h3><p>To follow along with some of the examples in this tutorial, you’ll need to install pytest. As most <a href="https://realpython.com/python-modules-packages/">Python packages</a>, pytest is available on <a href="https://realpython.com/pypi-publish-python-package/">PyPI</a>. You can install it in a <a href="https://realpython.com/python-virtual-environments-a-primer/">virtual environment</a> using <a href="https://realpython.com/what-is-pip/">pip</a>:</p><pre>PS&gt; python -m venv venv<br>PS&gt; .\venv\Scripts\activate<br>(venv) PS&gt; python -m pip install pytest</pre><h3>What Makes pytest So Useful?</h3><p>If you’ve written unit <a href="https://realpython.com/python-testing/">tests</a> for your Python code before, then you may have used Python’s built-in <strong>unittest</strong> module. unittest provides a solid base on which to build your test suite, but it has a few shortcomings.</p><p>A number of third-party testing frameworks attempt to address some of the issues with unittest, and pytest has proven to be one of the most popular. pytest is a feature-rich, plugin-based ecosystem for testing your Python code.</p><p>If you haven’t had the pleasure of using pytest yet, then you’re in for a treat! Its philosophy and features will make your testing experience more productive and enjoyable. With pytest, common tasks require less code and advanced tasks can be achieved through a variety of time-saving commands and plugins. It’ll even run your existing tests out of the box, including those written with unittest.</p><p>As with most frameworks, some development patterns that make sense when you first start using pytest can start causing pains as your test suite grows. This tutorial will help you understand some of the tools pytest provides to keep your testing efficient and effective even as it scales.</p><h3>Less Boilerplate</h3><p>Most functional tests follow the Arrange-Act-Assert model:</p><ol><li><strong>Arrange</strong>, or set up, the conditions for the test</li><li><strong>Act</strong> by calling some function or method</li><li><strong>Assert</strong> that some end condition is true</li></ol><p>Testing frameworks typically hook into your test’s <a href="https://realpython.com/python-assert-statement/">assertions</a> so that they can provide information when an assertion fails. unittest, for example, provides a number of helpful assertion utilities out of the box. However, even a small set of tests requires a fair amount of <a href="https://en.wikipedia.org/wiki/Boilerplate_code">boilerplate code</a>.</p><p>Imagine you’d like to write a test suite just to make sure that unittest is working properly in your project. You might want to write one test that always passes and one that always fails:</p><pre># test_with_unittest.py</pre><pre>from unittest import TestCase</pre><pre>class TryTesting(TestCase):<br>    def test_always_passes(self):<br>        self.assertTrue(True)</pre><pre>    def test_always_fails(self):<br>        self.assertTrue(False)</pre><p>You can then run those tests from the command line using the discover option of unittest:</p><pre>(venv) $ python -m unittest discover<br>F.<br>======================================================================<br>FAIL: test_always_fails (test_with_unittest.TryTesting)<br>----------------------------------------------------------------------<br>Traceback (most recent call last):<br>  File &quot;...\effective-python-testing-with-pytest\test_with_unittest.py&quot;,<br>  line 10, in test_always_fails<br>    self.assertTrue(False)<br>AssertionError: False is not true</pre><pre>----------------------------------------------------------------------</pre><pre>Ran 2 tests in 0.006s</pre><pre>FAILED (failures=1)</pre><p>As expected, one test passed and one failed. You’ve proven that unittest is working, but look at what you had to do:</p><ol><li>Import the TestCase class from unittest</li><li>Create TryTesting, a <a href="https://realpython.com/python3-object-oriented-programming/">subclass</a> of TestCase</li><li>Write a method in TryTesting for each test</li><li>Use one of the self.assert* methods from unittest.TestCase to make assertions</li></ol><p>That’s a significant amount of code to write, and because it’s the minimum you need for <em>any</em> test, you’d end up writing the same code over and over. pytest simplifies this workflow by allowing you to use normal functions and Python’s assert keyword directly:</p><pre># test_with_pytest.py</pre><pre>def test_always_passes():<br>    assert True</pre><pre>def test_always_fails():<br>    assert False</pre><p>That’s it. You don’t have to deal with any imports or classes. All you need to do is include a function with the test_ prefix. Because you can use the assert keyword, you don’t need to learn or remember all the different self.assert* methods in unittest, either. If you can write an expression that you expect to evaluate to True, and then pytest will test it for you.</p><p>Not only does pytest eliminate a lot of boilerplate, but it also provides you with a much more detailed and easy-to-read output.</p><h3>Nicer Output</h3><p>You can run your test suite using the pytest command from the top-level folder of your project:</p><pre>(venv) $ pytest<br>============================= test session starts =============================<br>platform win32 -- Python 3.10.5, pytest-7.1.2, pluggy-1.0.0<br>rootdir: ...\effective-python-testing-with-pytest<br>collected 4 items</pre><pre>test_with_pytest.py .F                                                   [ 50%]<br>test_with_unittest.py F.                                                 [100%]</pre><pre>================================== FAILURES ===================================<br>______________________________ test_always_fails ______________________________</pre><pre>    def test_always_fails():<br>&gt;       assert False<br>E       assert False</pre><pre>test_with_pytest.py:7: AssertionError<br>________________________ TryTesting.test_always_fails _________________________</pre><pre>self = &lt;test_with_unittest.TryTesting testMethod=test_always_fails&gt;</pre><pre>    def test_always_fails(self):<br>&gt;       self.assertTrue(False)<br>E       AssertionError: False is not true</pre><pre>test_with_unittest.py:10: AssertionError<br>=========================== short test summary info ===========================<br>FAILED test_with_pytest.py::test_always_fails - assert False<br>FAILED test_with_unittest.py::TryTesting::test_always_fails - AssertionError:...</pre><pre>========================= 2 failed, 2 passed in 0.20s =========================</pre><p>pytest presents the test results differently than unittest, and the test_with_unittest.py file was also automatically included. The report shows:</p><ol><li>The system state, including which versions of Python, pytest, and any plugins you have installed</li><li>The rootdir, or the directory to search under for configuration and tests</li><li>The number of tests the runner discovered</li></ol><p>These items are presented in the first section of the output:</p><pre>============================= test session starts =============================<br>platform win32 -- Python 3.10.5, pytest-7.1.2, pluggy-1.0.0<br>rootdir: ...\effective-python-testing-with-pytest<br>collected 4 items</pre><p>The output then indicates the status of each test using a syntax similar to unittest:</p><ul><li><strong>A dot (</strong><strong>.)</strong> means that the test passed.</li><li><strong>An </strong><strong>F</strong> means that the test has failed.</li><li><strong>An </strong><strong>E</strong> means that the test raised an unexpected exception.</li></ul><p>The special characters are shown next to the name with the overall progress of the test suite shown on the right:</p><pre>test_with_pytest.py .F                                                   [ 50%]<br>test_with_unittest.py F.                                                 [100%]</pre><p>For tests that fail, the report gives a detailed breakdown of the failure. In the example, the tests failed because assert False always fails:</p><pre>================================== FAILURES ===================================<br>______________________________ test_always_fails ______________________________</pre><pre>    def test_always_fails():<br>&gt;       assert False<br>E       assert False</pre><pre>test_with_pytest.py:7: AssertionError<br>________________________ TryTesting.test_always_fails _________________________</pre><pre>self = &lt;test_with_unittest.TryTesting testMethod=test_always_fails&gt;</pre><pre>    def test_always_fails(self):<br>&gt;       self.assertTrue(False)<br>E       AssertionError: False is not true</pre><pre>test_with_unittest.py:10: AssertionError</pre><p>This extra output can come in extremely handy when debugging. Finally, the report gives an overall status report of the test suite:</p><pre>=========================== short test summary info ===========================<br>FAILED test_with_pytest.py::test_always_fails - assert False<br>FAILED test_with_unittest.py::TryTesting::test_always_fails - AssertionError:...</pre><pre>========================= 2 failed, 2 passed in 0.20s =========================</pre><p>When compared to unittest, the pytest output is much more informative and readable.</p><p>In the next section, you’ll take a closer look at how pytest takes advantage of the existing assert keyword.</p><h3>Less to Learn</h3><p>Being able to use the <a href="https://realpython.com/python-assert-statement/">assert</a> keyword is also powerful. If you’ve used it before, then there’s nothing new to learn. Here are a few assertion examples so you can get an idea of the types of test you can make:</p><pre># test_assert_examples.py</pre><pre>def test_uppercase():<br>    assert &quot;loud noises&quot;.upper() == &quot;LOUD NOISES&quot;</pre><pre>def test_reversed():<br>    assert list(reversed([1, 2, 3, 4])) == [4, 3, 2, 1]</pre><pre>def test_some_primes():<br>    assert 37 in {<br>        num<br>        for num in range(2, 50)<br>        if not any(num % div == 0 for div in range(2, num))<br>    }</pre><p>They look very much like normal Python functions. All of this makes the learning curve for pytest shallower than it is for unittest because you don’t need to learn new constructs to get started.</p><p>Note that each test is quite small and self-contained. This is common — you’ll see long function names and not a lot going on within a function. This serves mainly to keep your tests isolated from each other, so if something breaks, you know exactly where the problem is. A nice side effect is that the labeling is much better in the output.</p><p>To see an example of a project that creates a test suite along with the main project, check out the <a href="https://realpython.com/python-hash-table/">Build a Hash Table in Python With TDD</a> tutorial. Additionally, you can work on Python practice problems to try test-driven development yourself while you <a href="https://realpython.com/python-practice-problems/">get ready for your next interview</a> or <a href="https://realpython.com/python-interview-problem-parsing-csv-files/">parse CSV files</a>.</p><p>In the next section, you’re going to be examining fixtures, a great pytest feature to help you manage test input values.</p><h3>Easier to Manage State and Dependencies</h3><p>Your tests will often depend on types of data or <a href="https://en.wikipedia.org/wiki/Test_double">test doubles</a> that mock objects your code is likely to encounter, such as <a href="https://realpython.com/python-dicts/">dictionaries</a> or <a href="https://realpython.com/python-json/">JSON</a> files.</p><p>With unittest, you might extract these dependencies into .setUp() and .tearDown() methods so that each test in the class can make use of them. Using these special methods is fine, but as your test classes get larger, you may inadvertently make the test’s dependence entirely <strong>implicit</strong>. In other words, by looking at one of the many tests in isolation, you may not immediately see that it depends on something else.</p><p>Over time, implicit dependencies can lead to a complex tangle of code that you have to unwind to make sense of your tests. Tests should help to make your code more understandable. If the tests themselves are difficult to understand, then you may be in trouble!</p><p>pytest takes a different approach. It leads you toward <strong>explicit</strong> dependency declarations that are still reusable thanks to the availability of <a href="https://docs.pytest.org/en/latest/fixture.html">fixtures</a>. pytest fixtures are functions that can create data, test doubles, or initialize system state for the test suite. Any test that wants to use a fixture must explicitly use this fixture function as an argument to the test function, so dependencies are always stated up front:</p><pre># fixture_demo.py</pre><pre>import pytest</pre><pre>@pytest.fixture<br>def example_fixture():<br>    return 1</pre><pre>def test_with_fixture(example_fixture):<br>    assert example_fixture == 1</pre><p>Looking at the test function, you can immediately tell that it depends on a fixture, without needing to check the whole file for fixture definitions.</p><p><strong>Note:</strong> You usually want to put your tests into their own folder called tests at the root level of your project.</p><p>For more information about structuring a Python application, check out the <a href="https://realpython.com/courses/structuring-python-application/">video course</a> on that very topic.</p><p>Fixtures can also make use of other fixtures, again by declaring them explicitly as dependencies. That means that, over time, your fixtures can become bulky and modular. Although the ability to insert fixtures into other fixtures provides enormous flexibility, it can also make managing dependencies more challenging as your test suite grows.</p><p>Later in this tutorial, you’ll learn <a href="https://realpython.com/pytest-python-testing/#fixtures-managing-state-and-dependencies">more about fixtures</a> and try a few techniques for handling these challenges.</p><h3>Easy to Filter Tests</h3><p>As your test suite grows, you may find that you want to run just a few tests on a feature and save the full suite for later. pytest provides a few ways of doing this:</p><ul><li><strong>Name-based filtering</strong>: You can limit pytest to running only those tests whose fully qualified names match a particular expression. You can do this with the -k parameter.</li><li><strong>Directory scoping</strong>: By default, pytest will run only those tests that are in or under the current directory.</li><li><strong>Test categorization</strong>: pytest can include or exclude tests from particular categories that you define. You can do this with the -m parameter.</li></ul><p>Test categorization in particular is a subtly powerful tool. pytest enables you to create <strong>marks</strong>, or custom labels, for any test you like. A test may have multiple labels, and you can use them for granular control over which tests to run. Later in this tutorial, you’ll see an example of <a href="https://realpython.com/pytest-python-testing/#marks-categorizing-tests">how </a><a href="https://realpython.com/pytest-python-testing/#marks-categorizing-tests">pytest marks work</a> and learn how to make use of them in a large test suite.</p><h3>Allows Test Parametrization</h3><p>When you’re testing functions that process data or perform generic transformations, you’ll find yourself writing many similar tests. They may differ only in the <a href="https://realpython.com/python-input-output/">input or output</a> of the code being tested. This requires duplicating test code, and doing so can sometimes obscure the behavior that you’re trying to test.</p><p>unittest offers a way of collecting several tests into one, but they don’t show up as individual tests in result reports. If one test fails and the rest pass, then the entire group will still return a single failing result. pytest offers its own solution in which each test can pass or fail independently. You’ll see <a href="https://realpython.com/pytest-python-testing/#parametrization-combining-tests">how to parametrize tests</a> with pytest later in this tutorial.</p><h3>Has a Plugin-Based Architecture</h3><p>One of the most beautiful features of pytest is its openness to customization and new features. Almost every piece of the program can be cracked open and changed. As a result, pytest users have developed a rich ecosystem of helpful plugins.</p><p>Although some pytest plugins focus on specific frameworks like <a href="https://www.djangoproject.com/">Django</a>, others are applicable to most test suites. You’ll see <a href="https://realpython.com/pytest-python-testing/#useful-pytest-plugins">details on some specific plugins</a> later in this tutorial.</p><h3>Fixtures: Managing State and Dependencies</h3><p>pytest fixtures are a way of providing data, test doubles, or state setup to your tests. Fixtures are functions that can return a wide range of values. Each test that depends on a fixture must explicitly accept that fixture as an argument.</p><h3>When to Create Fixtures</h3><p>In this section, you’ll simulate a typical <a href="https://realpython.com/courses/test-driven-development-pytest/">test-driven development</a> (TDD) workflow.</p><p>Imagine you’re writing a function, format_data_for_display(), to process the data returned by an API endpoint. The data represents a list of people, each with a given name, family name, and job title. The function should output a list of strings that include each person’s full name (their given_name followed by their family_name), a colon, and their title:</p><pre># format_data.py</pre><pre>def format_data_for_display(people):<br>    ...  # Implement this!</pre><p>In good TDD fashion, you’ll want to first write a test for it. You might write the following code for that:</p><pre># test_format_data.py</pre><pre>def test_format_data_for_display():<br>    people = [<br>        {<br>            &quot;given_name&quot;: &quot;Alfonsa&quot;,<br>            &quot;family_name&quot;: &quot;Ruiz&quot;,<br>            &quot;title&quot;: &quot;Senior Software Engineer&quot;,<br>        },<br>        {<br>            &quot;given_name&quot;: &quot;Sayid&quot;,<br>            &quot;family_name&quot;: &quot;Khan&quot;,<br>            &quot;title&quot;: &quot;Project Manager&quot;,<br>        },<br>    ]</pre><pre>    assert format_data_for_display(people) == [<br>        &quot;Alfonsa Ruiz: Senior Software Engineer&quot;,<br>        &quot;Sayid Khan: Project Manager&quot;,<br>    ]</pre><p>While writing this test, it occurs to you that you may need to write another function to transform the data into comma-separated values for use in <a href="https://realpython.com/openpyxl-excel-spreadsheets-python/">Excel</a>:</p><pre># format_data.py</pre><pre>def format_data_for_display(people):<br>    ...  # Implement this!</pre><pre>def format_data_for_excel(people):<br>    ... # Implement this!</pre><p>Your to-do list grows! That’s good! One of the advantages of TDD is that it helps you plan out the work ahead. The test for the format_data_for_excel() function would look awfully similar to the format_data_for_display() function:</p><pre># test_format_data.py</pre><pre>def test_format_data_for_display():<br>    # ...</pre><pre>def test_format_data_for_excel():<br>    people = [<br>        {<br>            &quot;given_name&quot;: &quot;Alfonsa&quot;,<br>            &quot;family_name&quot;: &quot;Ruiz&quot;,<br>            &quot;title&quot;: &quot;Senior Software Engineer&quot;,<br>        },<br>        {<br>            &quot;given_name&quot;: &quot;Sayid&quot;,<br>            &quot;family_name&quot;: &quot;Khan&quot;,<br>            &quot;title&quot;: &quot;Project Manager&quot;,<br>        },<br>    ]</pre><pre>    assert format_data_for_excel(people) == &quot;&quot;&quot;given,family,title<br>Alfonsa,Ruiz,Senior Software Engineer<br>Sayid,Khan,Project Manager<br>&quot;&quot;&quot;</pre><p>Notably, both the tests have to repeat the definition of the people variable, which is quite a few lines of code.</p><p>If you find yourself writing several tests that all make use of the same underlying test data, then a fixture may be in your future. You can pull the repeated data into a single function decorated with @pytest.fixture to indicate that the function is a pytest fixture:</p><pre># test_format_data.py</pre><pre>import pytest</pre><pre>@pytest.fixture<br>def example_people_data():<br>    return [<br>        {<br>            &quot;given_name&quot;: &quot;Alfonsa&quot;,<br>            &quot;family_name&quot;: &quot;Ruiz&quot;,<br>            &quot;title&quot;: &quot;Senior Software Engineer&quot;,<br>        },<br>        {<br>            &quot;given_name&quot;: &quot;Sayid&quot;,<br>            &quot;family_name&quot;: &quot;Khan&quot;,<br>            &quot;title&quot;: &quot;Project Manager&quot;,<br>        },<br>    ]</pre><pre># ...</pre><p>You can use the fixture by adding the function reference as an argument to your tests. Note that you don’t call the fixture function. pytest takes care of that. You’ll be able to use the return value of the fixture function as the name of the fixture function:</p><pre># test_format_data.py</pre><pre># ...</pre><pre>def test_format_data_for_display(example_people_data):<br>    assert format_data_for_display(example_people_data) == [<br>        &quot;Alfonsa Ruiz: Senior Software Engineer&quot;,<br>        &quot;Sayid Khan: Project Manager&quot;,<br>    ]</pre><pre>def test_format_data_for_excel(example_people_data):<br>    assert format_data_for_excel(example_people_data) == &quot;&quot;&quot;given,family,title<br>Alfonsa,Ruiz,Senior Software Engineer<br>Sayid,Khan,Project Manager<br>&quot;&quot;&quot;</pre><p>Each test is now notably shorter but still has a clear path back to the data it depends on. Be sure to name your fixture something specific. That way, you can quickly determine if you want to use it when writing new tests in the future!</p><p>When you first discover the power of fixtures, it can be tempting to use them all the time, but as with all things, there’s a balance to be maintained.</p><h3>When to Avoid Fixtures</h3><p>Fixtures are great for extracting data or objects that you use across multiple tests. However, they aren’t always as good for tests that require slight variations in the data. Littering your test suite with fixtures is no better than littering it with plain data or objects. It might even be worse because of the added layer of indirection.</p><p>As with most abstractions, it takes some practice and thought to find the right level of fixture use.</p><p>Nevertheless, fixtures will likely be an integral part of your test suite. As your project grows in scope, the challenge of scale starts to come into the picture. One of the challenges facing any kind of tool is how it handles being used at scale, and luckily, pytest has a bunch of useful features that can help you manage the complexity that comes with growth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6be7079143c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using FastAPI to Build Python Web APIs ]]></title>
            <link>https://medium.com/@yashnarsamiyev2/using-fastapi-to-build-python-web-apis-3c77d3689f8c?source=rss-1775992469b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c77d3689f8c</guid>
            <dc:creator><![CDATA[Yashnarbek Samiyev]]></dc:creator>
            <pubDate>Mon, 25 Dec 2023 11:31:50 GMT</pubDate>
            <atom:updated>2023-12-25T11:41:51.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*QRLxqUqH44jelz9-mMuk8g.png" /><figcaption>Fastapi</figcaption></figure><p>Creating APIs, or <strong>application programming interfaces</strong>, is an important part of making your software accessible to a broad range of users. In this tutorial, you will learn the main concepts of <strong>FastAPI</strong> and how to use it to quickly create web APIs that implement best practices by default.</p><p>By the end of it, you will be able to start creating production-ready web APIs, and you will have the understanding needed to go deeper and learn more for your specific use cases.</p><p><strong>In this tutorial, you’ll learn how to</strong>:</p><ul><li>Use <strong>path parameters</strong> to get a unique URL path per item</li><li>Receive JSON data in your requests using <strong>pydantic</strong></li><li>Use API best practices, including <strong>validation</strong>, <strong>serialization</strong>, and <strong>documentation</strong></li><li>Continue learning about FastAPI for <strong>your use cases</strong></li></ul><p>This tutorial is written by the <a href="https://realpython.com/team/sramirez/">author of FastAPI</a>. It contains a careful selection of fragments from the official documentation, avoiding getting lost in technical details while helping you get up to speed as fast as possible.</p><p>To get the most out of this tutorial, it would be helpful for you to know the basics of <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview">what HTTP is and how it works</a>, <a href="https://realpython.com/python-json/">what JSON is</a>, and <a href="https://fastapi.tiangolo.com/python-types/">Python type hints</a>. You will also benefit from using a <a href="https://realpython.com/python-virtual-environments-a-primer/">virtual environment</a>, as is the case for any Python project.</p><h3>What Is FastAPI?</h3><p>FastAPI is a modern, high-performance web framework for building APIs with Python based on standard type hints. It has the following key features:</p><ul><li><strong>Fast to run</strong>: It offers very high performance, on par with <strong>NodeJS</strong> and <strong>Go</strong>, thanks to <a href="https://www.starlette.io/">Starlette</a> and <a href="https://pydantic-docs.helpmanual.io/">pydantic</a>.</li><li><strong>Fast to code</strong>: It allows for significant increases in development speed.</li><li><strong>Reduced number of bugs</strong>: It reduces the possibility for human-induced errors.</li><li><strong>Intuitive</strong>: It offers great editor support, with completion everywhere and less time debugging.</li><li><strong>Straightforward</strong>: It’s designed to be uncomplicated to use and learn, so you can spend less time reading documentation.</li><li><strong>Short</strong>: It minimizes code duplication.</li><li><strong>Robust</strong>: It provides production-ready code with automatic interactive documentation.</li><li><strong>Standards-based</strong>: It’s based on the open standards for APIs, <a href="https://github.com/OAI/OpenAPI-Specification">OpenAPI</a> and <a href="https://json-schema.org/">JSON Schema</a>.</li></ul><p>The framework is designed to optimize your developer experience so that you can write simple code to build production-ready APIs with best practices by default.</p><h3>Install FastAPI</h3><p>As with any other Python project, it would be best to start by creating a virtual environment. If you are not familiar with how to do that, then you can check out the <a href="https://realpython.com/python-virtual-environments-a-primer/">Primer on Virtual Environments</a>.</p><p>The first step is to install FastAPI and <a href="https://www.uvicorn.org/#introduction">Uvicorn</a> using <a href="https://realpython.com/what-is-pip/">pip</a>:</p><pre>$ python -m pip install fastapi uvicorn[standard]</pre><p>With that, you have FastAPI and Uvicorn installed and are ready to learn how to use them. FastAPI is the framework you’ll use to build your API, and Uvicorn is the server that will use the API you build to serve requests.</p><h3>First Steps</h3><p>To get started, in this section, you will create a minimal FastAPI app, run it with a server using Uvicorn, and then learn all the interacting parts. This will give you a very quick overview of how everything works.</p><h3>Create a First API</h3><p>A basic FastAPI file looks like this:</p><pre># main.py</pre><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/&quot;)<br>async def root():<br>    return {&quot;message&quot;: &quot;Hello World&quot;}</pre><p>Copy the code above to a file named main.py, and just like that, you have a fully functional API application with some best practices like automatic documentation and serialization built in. You will learn more about those features next.</p><p>This code defines your application, but it won’t run on itself if you call it with python directly. To run it, you need a <strong>server</strong> program. In the steps above, you already installed <a href="https://www.uvicorn.org/">Uvicorn</a>. That will be your server.</p><h3>Run the First API App With Uvicorn</h3><p>Run the live server using Uvicorn:</p><pre>$ uvicorn main:app --reload</pre><pre>INFO:     Uvicorn running on <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a> (Press CTRL+C to quit)<br>INFO:     Started reloader process [28720]<br>INFO:     Started server process [28722]<br>INFO:     Waiting for application startup.<br>INFO:     Application startup complete.</pre><p>The highlighted line in the output shows the URL where your app is being served in your local machine. Since you used --reload for development, when you update your application code, the server will reload automatically.</p><h3>Check the Response</h3><p>Open your browser to http://127.0.0.1:8000, which will make your browser send a request to your application. It will then send a JSON response with the following:</p><pre>{&quot;message&quot;: &quot;Hello World&quot;}</pre><p>That JSON message is the same dictionary that you returned from the function in your application. FastAPI takes care of serializing the <a href="https://realpython.com/python-dicts/">Python </a><a href="https://realpython.com/python-dicts/">dict</a> into a JSON object and setting the appropriate Content-Type.</p><h3>Check the Interactive API Documentation</h3><p>Now open http://127.0.0.1:8000/docs in your browser.</p><p>You will see the automatic interactive API documentation provided by <a href="https://github.com/swagger-api/swagger-ui">Swagger UI</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*zax4cDh9ixL8e9GA.png" /></figure><p>The browser-based user interface documenting your API is provided and integrated by default. You don’t have to do anything else to take advantage of it with FastAPI.</p><h3>Check the Alternative Interactive API Documentation</h3><p>Now, go to http://127.0.0.1:8000/redoc in your browser.</p><p>You’ll see the alternative automatic documentation provided by <a href="https://github.com/Redocly/redoc">ReDoc</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*FsB15qSjP6fhRf-f.png" /></figure><p>As FastAPI is based on standards like OpenAPI, there are many alternative ways to show the API documentation. FastAPI provides these two alternatives by default.</p><h3>The First API, Step by Step</h3><p>Now let’s analyze that code step by step and understand what each part does.</p><p><strong>Step 1</strong> is to import FastAPI:</p><pre># main.py</pre><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/&quot;)<br>async def root():<br>    return {&quot;message&quot;: &quot;Hello World&quot;}</pre><p>FastAPI is a <a href="https://realpython.com/python-classes/">Python class</a> that provides all the functionality for your API.</p><p><strong>Step 2</strong> is to create a FastAPI instance:</p><pre># main.py</pre><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/&quot;)<br>async def root():<br>    return {&quot;message&quot;: &quot;Hello World&quot;}</pre><p>Here the app <a href="https://realpython.com/python-variables/">variable</a> will be an instance of the class FastAPI. This will be the main point of interaction to create your API.</p><p>This app is the same one you referred to above in the command to run the live server with uvicorn :</p><pre>$ uvicorn main:app --reload</pre><pre>INFO:     Uvicorn running on <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a> (Press CTRL+C to quit)</pre><p>Before continuing with step 3, it’s worth taking a moment to get familiar with a couple of terms. <strong>Path</strong> refers to the last part of the URL starting from the first forward slash character (/). So, in a URL like https://example.com/items/foo, the path would be /items/foo.</p><p>A path is also commonly called an <strong>endpoint</strong> or a <strong>route</strong>, but the term <strong>path</strong> will be used in this tutorial. When you’re building an API, the path is the main way you can separate resources.</p><p>Another important term to know is <strong>operation</strong>, which is used in reference to any of the <strong>HTTP request methods</strong>:</p><ul><li>POST</li><li>GET</li><li>PUT</li><li>DELETE</li><li>OPTIONS</li><li>HEAD</li><li>PATCH</li><li>TRACE</li></ul><p>With <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol">HTTP</a>, you can communicate with each path using one (or more) of these operations. Knowing what those two terms mean, you’re ready to continue with step three.</p><p><strong>Step 3</strong> is to define a <strong>path operation decorator</strong>:</p><pre># main.py</pre><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/&quot;)<br>async def root():<br>    return {&quot;message&quot;: &quot;Hello World&quot;}</pre><p>The @app.get(&quot;/&quot;) tells FastAPI that the function right below is in charge of handling requests that go to the path / using a get operation. This is a <strong>decorator</strong> related to a path operation, or a path operation decorator. If you want to learn a bit more about decorators, then check out the <a href="https://realpython.com/primer-on-python-decorators/">Primer on Python Decorators</a>.</p><p>You can also use the other operations mentioned above:</p><ul><li>@app.post()</li><li>@app.put()</li><li>@app.delete()</li><li>@app.options()</li><li>@app.head()</li><li>@app.patch()</li><li>@app.trace()</li></ul><p>In each case, you would use the appropriate path operation decorator above a function that is in charge of handling those requests.</p><p><strong>Step 4</strong> is to define the <strong>path operation function</strong>, or the function that goes below the path operation decorator:</p><pre># main.py</pre><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/&quot;)<br>async def root():<br>    return {&quot;message&quot;: &quot;Hello World&quot;}</pre><p>This function will be called by FastAPI whenever it receives a request to the specified URL (/) using a GET operation. In this case, it is an <a href="https://realpython.com/async-io-python/">async function</a>.</p><p>You could also define it as a normal function instead of using async def:</p><pre># main.py</pre><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/&quot;)<br>def root():<br>    return {&quot;message&quot;: &quot;Hello World&quot;}</pre><p>If you don’t know the difference between normal functions and async functions and when to use them, check out <a href="https://fastapi.tiangolo.com/async/">Concurrency and async/await</a> in the FastAPI documentation.</p><p><strong>Step 5</strong> is to <a href="https://realpython.com/python-return-statement/">return</a> the content:</p><pre># main.py</pre><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/&quot;)<br>async def root():<br>    return {&quot;message&quot;: &quot;Hello World&quot;}</pre><p>You can return a <a href="https://realpython.com/python-dicts/">dictionary</a>, <a href="https://realpython.com/python-lists-tuples/">list</a>, or singular values as <a href="https://realpython.com/python-strings/">strings</a>, <a href="https://realpython.com/python-numbers/">integers</a>, and so on. You can also return pydantic models, which you’ll learn more about later.</p><p>There are many other objects and models that will be automatically converted to JSON, including <a href="https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping">object-relational mappers</a> (ORMs) and others. Try using your favorite ones — it’s highly probable that they are already supported.</p><h3>Path Parameters: Get an Item by ID</h3><p>You can declare path <strong>parameters</strong> or <strong>variables</strong> with the same syntax used by Python <a href="https://realpython.com/python-formatted-output/">formatted strings</a>:</p><pre># main.py</pre><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/items/{item_id}&quot;)<br>async def read_item(item_id):<br>    return {&quot;item_id&quot;: item_id}</pre><p>The value of the path parameter item_id will be passed to your function as the argument item_id.</p><p>So, if you run this example and go to http://127.0.0.1:8000/items/foo, you will see this response:</p><pre>{&quot;item_id&quot;:&quot;foo&quot;}</pre><p>The response contains &quot;foo&quot;, which is what was passed in the item_id path parameter and then returned in a dictionary.</p><h3>Path Parameters With Types</h3><p>You can declare the type of a path parameter in the function using standard Python type hints:</p><pre># main.py</pre><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/items/{item_id}&quot;)<br>async def read_item(item_id: int):<br>    return {&quot;item_id&quot;: item_id}</pre><p>In this case, you declare item_id to be an int.</p><p>Declaring the type of a path parameter will give you editor support inside of your function, with error checks, completion, and so on.</p><h3>Data Conversion</h3><p>If you run the above example and navigate your browser to http://127.0.0.1:8000/items/3, then you will see the following response:</p><pre>{&quot;item_id&quot;:3}</pre><p>Notice that the value your function received and then returned is 3, which is a Python int, not a string (&quot;3&quot;). So, with that type declaration, FastAPI gives you automatic <strong>request parsing</strong>.</p><h3>Data Validation</h3><p>If you point your browser to http://127.0.0.1:8000/items/foo, then you’ll see a nice HTTP error:</p><pre>{<br>    &quot;detail&quot;: [<br>        {<br>            &quot;loc&quot;: [<br>                &quot;path&quot;,<br>                &quot;item_id&quot;<br>            ],<br>            &quot;msg&quot;: &quot;value is not a valid integer&quot;,<br>            &quot;type&quot;: &quot;type_error.integer&quot;<br>        }<br>    ]<br>}</pre><p>This is because the path parameter item_id has a value of &quot;foo&quot;, which is not an int.</p><p>The same error would appear if you provided a float instead of an int, such as if you opened http://127.0.0.1:8000/items/4.2 in your browser. So, with the same Python type hint, FastAPI gives you both <strong>data parsing</strong> and <strong>data validation</strong>.</p><p>Also notice that the error clearly states the exact point where the validation didn’t pass. This is incredibly helpful while developing and debugging code that interacts with your API.</p><h3>Documentation</h3><p>When you open your browser at http://127.0.0.1:8000/docs, you will see an automatic, interactive API documentation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1lkFTS9DpnfWkuu7.png" /></figure><p>Again, with that same Python type declaration, FastAPI gives you automatic, interactive documentation integrating Swagger UI. Notice that the path parameter is declared to be an integer.</p><p>Because FastAPI is built on top of the <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md">OpenAPI</a> standard, it also provides an alternative API documentation using ReDoc, which you can access at <a href="http://127.0.0.1:8000/redoc:">http://127.0.0.1:8000/redoc:</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fB5oG1uwpTGTVKq6.png" /></figure><p>There are many other compatible tools, including code-generation tools for many languages.</p><h3>Data Handling With pydantic</h3><p>All the data validation is performed under the hood by pydantic, so you get all the benefits from it, and you know you are in good hands.</p><p>You can use the same type declarations with str, float, bool and many other complex data types.</p><h3>Order Matters: Put Fixed Paths First</h3><p>When creating path operations, you may find situations where you have a fixed path, like /users/me. Let’s say that it’s to get data about the current user. You might also have the path /users/{user_id} to get data about a specific user by some user ID.</p><p>Because path operations are evaluated in order, you need to make sure that the path for /users/me is declared before the one for /users/{user_id}:</p><pre># main.py</pre><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/users/me&quot;)<br>async def read_user_me():<br>    return {&quot;user_id&quot;: &quot;the current user&quot;}</pre><pre>@app.get(&quot;/users/{user_id}&quot;)<br>async def read_user(user_id: str):<br>    return {&quot;user_id&quot;: user_id}</pre><p>Otherwise, the path for /users/{user_id} would also match for /users/me, thinking that it’s receiving the parameter user_id with a value of &quot;me&quot;.</p><h3>Request Body: Receiving JSON Data</h3><p>When you need to send data from a client to your API, you send it as a request body.</p><p>A <strong>request body</strong> is data sent by the client to your API. A <strong>response body</strong> is the data your API sends to the client. Your API almost always has to send a response body. But clients don’t necessarily need to send request bodies all the time.</p><h3>Use pydantic to Declare JSON Data Models (Data Shapes)</h3><p>First, you need to import BaseModel from pydantic and then use it to create subclasses defining the <strong>schema</strong>, or data shapes, you want to receive.</p><p>Next, you declare your data model as a class that inherits from BaseModel, using standard Python types for all the attributes:</p><pre># main.py</pre><pre>from typing import Optional</pre><pre>from fastapi import FastAPI<br>from pydantic import BaseModel</pre><pre>class Item(BaseModel):<br>    name: str<br>    description: Optional[str] = None<br>    price: float<br>    tax: Optional[float] = None</pre><pre>app = FastAPI()</pre><pre>@app.post(&quot;/items/&quot;)<br>async def create_item(item: Item):<br>    return item</pre><p>hen a model attribute has a default value, it is not required. Otherwise, it is required. To make an attribute optional, you can use <a href="https://realpython.com/null-in-python/">None</a>.</p><p>For example, the model above declares a JSON object (or Python dict) like this:</p><pre>{<br>    &quot;name&quot;: &quot;Foo&quot;,<br>    &quot;description&quot;: &quot;An optional description&quot;,<br>    &quot;price&quot;: 45.2,<br>    &quot;tax&quot;: 3.5<br>}</pre><p>In this case, since description and tax are optional because they have a default value of None, this JSON object would also be valid:</p><pre>{<br>    &quot;name&quot;: &quot;Foo&quot;,<br>    &quot;price&quot;: 45.2<br>}</pre><p>A JSON object that omits the default values is also valid.</p><p>Next, add the new pydantic model to your path operation as a parameter. You declare it the same way you declared path parameters:</p><pre># main.py</pre><pre>from typing import Optional</pre><pre>from fastapi import FastAPI<br>from pydantic import BaseModel</pre><pre>class Item(BaseModel):<br>    name: str<br>    description: Optional[str] = None<br>    price: float<br>    tax: Optional[float] = None</pre><pre>app = FastAPI()</pre><pre>@app.post(&quot;/items/&quot;)<br>async def create_item(item: Item):<br>    return item</pre><p>The parameter item has a type hint of Item, which means that item is declared as an instance of the class Item.</p><p>With that Python type declaration, FastAPI will:</p><ul><li>Read the body of the request as JSON</li><li>Convert the corresponding types if needed</li><li>Validate the data and return a clear error if it is invalid</li><li>Give you the received data in the parameter item—since you declared it to be of type Item, you will also have all the editor support, with completion and type checks for all the attributes and their types</li><li>Generate <a href="https://json-schema.org/">JSON Schema</a> definitions for your model that you can also use anywhere else that makes sense for your project</li></ul><p>By using standard type hints with pydantic, FastAPI helps you build APIs that have all these best practices by default, with little effort.</p><h3>Automatic Documentation With pydantic</h3><p>The JSON Schemas of your pydantic models will be part of the OpenAPI generated for your application and will be shown in the interactive API documentation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i-wFc76Y-r2EhRtD.png" /></figure><p>You can see that the attributes of Item in the API documentation are exactly the ones you declared with your pydantic model.</p><p>These JSON Schemas will also be used in the API documentation inside each path operation that needs them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v1QrugPcSmiOJFw0.png" /></figure><p>Notice that all this automatic documentation is based on <em>your</em> data, using your pydantic models.</p><h3>Editor Support, Autocompletion, and Type Checks</h3><p>In your editor, inside your function, you will get type hints and completion everywhere. This wouldn’t happen if you received a dict instead of a pydantic model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lBwL4K1TOB2RvH6N.png" /></figure><p>This way you can trigger autocompletion for all your data.</p><p>You also get error checks for incorrect type operations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*D-U2xiGrRkOhyAld.png" /></figure><p>In this case, you cannot sum a str with a float, and as the editor knows those types, it can warn you that you have an error in your code. This is not by chance: The whole framework was built around that design. It was thoroughly tested at the design phase, before any implementation, to ensure it would work with all the editors. There were even some changes to pydantic itself to support this feature.</p><p>The previous screenshots were taken with <a href="https://realpython.com/python-development-visual-studio-code/">Visual Studio Code</a>. But you would get the same editor support with <a href="https://realpython.com/pycharm-guide/">PyCharm</a> and most of the other Python editors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/0*zQ27KdfNXbcXCyxH.png" /></figure><p>If you use PyCharm as your editor, then you can use the <a href="https://github.com/koxudaxi/pydantic-pycharm-plugin/">pydantic PyCharm plugin</a> to improve your editor support. And if you use VS Code, then you will get the best developer experience with <a href="https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance">Pylance</a>.</p><h3>Use the pydantic Model</h3><p>Inside the function, you can access all the attributes of the model object directly:</p><pre># main.py</pre><pre>from typing import Optional</pre><pre>from fastapi import FastAPI<br>from pydantic import BaseModel</pre><pre>class Item(BaseModel):<br>    name: str<br>    description: Optional[str] = None<br>    price: float<br>    tax: Optional[float] = None</pre><pre>app = FastAPI()</pre><pre>@app.post(&quot;/items/&quot;)<br>async def create_item(item: Item):<br>    item_dict = item.dict()<br>    if item.tax:<br>        price_with_tax = item.price + item.tax<br>        item_dict.update({&quot;price_with_tax&quot;: price_with_tax})<br>    return item_dict</pre><p>The parameter item is declared as an instance of the class Item, and FastAPI will make sure that you receive <em>exactly that</em> in your function instead of a dictionary or something else.</p><h3>Request Body and Path Parameters</h3><p>You can declare path parameters and a request body at the same time.</p><p>FastAPI will recognize that the function parameters that match path parameters should be taken from the path and that function parameters that are declared to be pydantic models should be taken from the request body:</p><pre># main.py</pre><pre>from typing import Optional</pre><pre>from fastapi import FastAPI<br>from pydantic import BaseModel</pre><pre>class Item(BaseModel):<br>    name: str<br>    description: Optional[str] = None<br>    price: float<br>    tax: Optional[float] = None</pre><pre>app = FastAPI()</pre><pre>@app.put(&quot;/items/{item_id}&quot;)<br>async def create_item(item_id: int, item: Item):<br>    return {&quot;item_id&quot;: item_id, **item.dict()}</pre><p>This way, you can declare path parameters and JSON request bodies, and FastAPI will take care of doing all the data validation, serialization, and documentation for you. You could verify it by going to the same API documentation at /docs or by using other tools like <a href="https://www.postman.com/">Postman</a> with a graphical interface or <a href="https://curl.se/docs/httpscripting.html">Curl</a> in the command line.</p><p>In a similar way, you can declare more complex request bodies, like lists, and other types of request data, like query parameters, cookies, headers, form inputs, files, and so on.</p><h3>Learn More About FastAPI</h3><p>By this point, you already know a lot about FastAPI and how to use it to create robust and production-ready APIs.</p><p>But there’s a lot more that you could learn:</p><ul><li><a href="https://fastapi.tiangolo.com/tutorial/query-params/">Query parameters</a> to customize a request</li><li><a href="https://fastapi.tiangolo.com/tutorial/dependencies/">Dependency injection</a> to handle reusable logic for permissions, database sessions, and others</li><li><a href="https://fastapi.tiangolo.com/tutorial/security/">Security utilities</a> to integrate authentication and authorization based on standards</li><li><a href="https://fastapi.tiangolo.com/tutorial/background-tasks/">Background tasks</a> for simple operations like sending an email notification</li><li><a href="https://fastapi.tiangolo.com/async/">async and </a><a href="https://fastapi.tiangolo.com/async/">await</a> to support <strong>concurrency</strong> and improve performance</li><li><a href="https://fastapi.tiangolo.com/advanced/websockets/">WebSockets</a> for advanced use cases that require real-time communication</li><li><a href="https://fastapi.tiangolo.com/tutorial/bigger-applications/">Bigger applications</a> in multiple files</li></ul><p>FastAPI can cover most of the use cases required for back-end frameworks, even the ones that are not strictly APIs. You can dive deeper into the documentation to solve your specific use case.</p><p>FastAPI is based on modern Python features, and you can take full advantage of FastAPI by learning more about those features, too. Check out <a href="https://realpython.com/python-async-features/">Getting Started With Async Features in Python</a> and <a href="https://realpython.com/async-io-python/">Async IO in Python: A Complete Walkthrough</a> to learn more about asyncronous programming. You can also check out <a href="https://realpython.com/python-type-checking/">Python Type Checking (Guide)</a> to get all the traditional benefits from type hints in your code.</p><h3>Conclusion</h3><p>In this tutorial, you learned about <strong>FastAPI</strong> and how to use it to create production-ready APIs that have best practices by default while providing the best developer experience possible. You learned how to:</p><ul><li>Use <strong>path parameters</strong> to get a unique URL path per item</li><li>Receive JSON data in your requests using <strong>pydantic</strong></li><li>Use API best practices like <strong>validation</strong>, <strong>serialization</strong>, and <strong>documentation</strong></li><li>Continue learning about <strong>FastAPI</strong> and <strong>pydantic</strong> for different use cases</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c77d3689f8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastAPI: Everything you need to know about the most widely used Python web framework for Machine…]]></title>
            <link>https://medium.com/@yashnarsamiyev2/fastapi-everything-you-need-to-know-about-the-most-widely-used-python-web-framework-for-machine-9f8e97acc344?source=rss-1775992469b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f8e97acc344</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Yashnarbek Samiyev]]></dc:creator>
            <pubDate>Mon, 25 Dec 2023 11:19:30 GMT</pubDate>
            <atom:updated>2023-12-25T11:19:30.645Z</atom:updated>
            <content:encoded><![CDATA[<h3>FastAPI: Everything you need to know about the most widely used Python web framework for Machine Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KjEbyAKpNVew_dKrxS1uuA.png" /></figure><h4>A framework is a collection of modules and packages used to develop software and help developers avoid having to deal with low-level details.</h4><p>The three most widely used frameworks for developing web applications in Python are <a href="https://datascientest.com/en/django-all-about-the-python-web-development-framework">Django,</a> Flask and FastAPI. Each has its own advantages and disadvantages, depending on the use case. The three main <a href="https://datascientest.com/en/framework-what-is-it">Python frameworks</a> are Django, Flash and FastAPI.</p><h3>What is FastAPI?</h3><blockquote>FastAPI is a high-performance, <a href="https://datascientest.com/en/open-source-definition-use-cases-and-more">open source web framework</a> for creating APIs with Python from version 3.6. Launched in 2018, it was created by Sebastián Ramírez, who wasn’t satisfied with existing frameworks such as Flask and DRF.</blockquote><blockquote>That’s why he created his own framework using tools like Starlette and <strong>Pydantic.</strong> Today, many world-renowned companies such as Uber, Netflix and Microsoft use FastAPI to build their applications.</blockquote><blockquote>Its first strength is a high level of performance, comparable with <strong>NodeJS</strong> and Go thanks to Starlette and pydantic. The framework is also very quick to code, speeding up development.</blockquote><blockquote>The number of bugs and opportunities for human error is greatly reduced.</blockquote><blockquote>What’s more, <strong>FastAPI</strong> is very intuitive to use, with completion and debugging features.</blockquote><blockquote>Designed to be simple to learn and use, this tool reduces the time spent reading documentation. Code duplication is also minimized.</blockquote><blockquote>In addition, <strong>FastAPI</strong> delivers production-ready code with automatic interactive documentation. Finally, it is based on the open standards <strong>OpenAI and JSON Schema.</strong></blockquote><blockquote>This framework is designed to optimize the developer’s experience, so that they can write simple code to build <a href="https://datascientest.com/en/api-the-path-to-seamless-integration">production-ready APIs using best practices.</a></blockquote><h3>What is FastAPI?</h3><p>One of the main use cases for FastAPI is the creation of API endpoints. This task can be accomplished very easily using the OpenAPI standard, and in particular the Swagger UI interactive user interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*D54mjcTYlmIxOUMTjf36nA.png" /></figure><p>However, <strong>FastAPI is not limited to APIs.</strong> It can be used for any web framework use case, such as the delivery of legacy web pages with the Jinja2 templating engine, or for WebSockets-based applications.</p><p>FastAPI is mainly used for data science and e-commerce applications. It enables developers to use the REST API and a wide range of functions to implement them in applications.</p><h3>FastAPI vs Flask vs Django</h3><p>The three <a href="https://datascientest.com/en/django-all-about-the-python-web-development-framework">main Python frameworks are Django, Flask and FastAPI.</a> Each has its own advantages and disadvantages, depending on the use case. Find out more about their respective advantages and disadvantages.</p><p><strong>Fast API</strong> is a high-performance, open-source Python web framework used to develop web APIs with the hint types of Python 3.6 or higher. It enables data types to be validated even within JSON requests.</p><p>It is based on standards such as JSON Schema, OAuth 2.0 and <strong>OpenAPI.</strong> It also facilitates the creation of GraphQL APIs with a Python library called graphene-python.</p><p>On the other hand, its weak point is that this framework is relatively new. The community is therefore rather small compared with other frameworks, and there is little educational material apart from the official documentation.</p><p><strong>FastAPI</strong> is used in particular for use cases where speed is a priority. For example, Netflix uses it for internal crisis management.</p><p>This framework is also perfectly suited to the deployment of Machine Learning models, since models work best in production when accompanied by a REST API and deployed as microservices.</p><h3>FastAPI vs Flask</h3><p><strong>Flask is a Python microframework</strong>. A web microframework is a development framework with a simple configuration that can be used to develop minimalist web applications.</p><p>This tool offers various options such as template engines like ORM, and caching and authentication functionalities.</p><p>Designed for creating web applications with Python, it is considered simple, fast and extensible.</p><p>It was originally created to develop web applications using the<strong> Python programming language.</strong></p><p>It’s designed to be easy, fast and scalable for microservices and complex applications, i.e. lightweight applications with a reduced list of functionalities.</p><p>Its first strength is its flexibility and convenience, since most aspects of Flask can be manipulated. This is a feature found in very few frameworks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u6oZSTUl6O7BCQw9Oijqcg.png" /></figure><p>It’s also an <strong>ideal framework for beginners,</strong> thanks to its simplicity. Developers can learn how to use it and understand it better over time, so they can build applications quickly and effortlessly. Finally, an integrated development server enables unit testing.</p><p>On the other hand, the absence of a data validation system can cause programs to crash. Another weak point is that queries are handled in turn by a single source, which can be very time-consuming. Flask uses third-party modules, with the attendant risk of security breaches.</p><p>The main use cases for Flask are commercial projects. It is used for <strong>e-commerce systems,</strong> social networking robots, social networks and static websites. It is very useful at the beginning, but may lack performance for larger loads.</p><h3>FastAPI vs Django</h3><p><strong>Django is an open-source Python-based</strong> web development framework. It was created in 2003 by Adrian Holovaty and Simon Willison, and uses the Model-Template-View pattern.</p><p>The framework owes its popularity to its robust, straightforward nature. It’s one of the most widely used frameworks in the world, notably by technology giants such as Instagram and YouTube. It also encourages reusable code.</p><p>Django’s code structure is highly efficient, enabling developers to easily add functionality to their websites. Security is also a priority, with features to defend against <a href="https://datascientest.com/en/sql-tutorial-top-5-most-useful-methods">SQL injection and cross-site false query attacks.</a></p><p>In addition, the Rest (representation state transfer) framework can be defined as a software architectural style to define a set of constraints to be used when creating web services on Django.</p><p>This is the <strong>Django Rest Framework (DRF)</strong>: a flexible set of tools used to design Web APIs on Django, taking advantage of its modularity and customizable architecture.</p><p>Nevertheless, Django’s software is slow and can limit development speed due to its many reusable modules. It is also necessary to ensure that previous versions are always compatible with new updates. Again, this adds to the slowness of the framework. In addition, <strong>Django uses ORM</strong>, which was created before SQLAlchemy and is therefore less flexible.</p><p>Django can be used for projects of any size and capacity. It can be used for both simple and high-performance sites.</p><p>Key use cases include booking engines, shopping platforms, school management systems, CRM systems for internal data, or web applications for iOS and Android.</p><h3>How do I learn to use Python and web development frameworks?</h3><p>The <a href="https://datascientest.com/en/python-all-you-need-to-know">Python programming language</a> is one of the most widely used in the world. To learn how to use it, you can choose DataScientest training courses.</p><p>All our programs start with a module dedicated to the fundamentals of the Python language and its Data Science libraries. By the end of the course, you’ll have all the skills you need to work in one of the Data Science professions.</p><p>Our courses can be completed in Continuing Education or intensive BootCamp mode. Our Blended Learning approach combines individual coaching on an online platform and Masterclasses. All courses are delivered remotely. For financing, all our programs are eligible for state financing.</p><p>After your Data Scientist training, or if you are already a professional Data Scientist, you can take one of our expert courses to acquire additional skills. The <a href="https://datascientest.com/en/unlock-your-future-dive-into-machine-learning-engineer-training">Machine Learning Engineer course</a> enables you to learn Machine Learning models in production, and the Advanced Engineering course to acquire expertise in the Python language and task automation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f8e97acc344" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Belief Networks and Restricted Bolzmann Machines ]]></title>
            <link>https://medium.com/@yashnarsamiyev2/deep-belief-networks-and-restricted-bolzmann-machines-def8b97ebfa4?source=rss-1775992469b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/def8b97ebfa4</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Yashnarbek Samiyev]]></dc:creator>
            <pubDate>Wed, 13 Dec 2023 16:28:10 GMT</pubDate>
            <atom:updated>2023-12-13T16:30:46.742Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In a rapidly developing sphere of machine learning and artificial intelligence, a significant part of research corresponds to unsupervised learning models. Learning without answers allows models to perform feature extraction, making them more resembling of “natural” learning process. In this work, we take advantage of a deep belief network (DBN), used for capturing hidden data representations, based on letter images from EMNIST dataset. Using DBN model allowed for analysis of hidden data representations through visualising neuron receptive fields at several depths. Moreover, linear read-outs are performed, to compare DBN classification performance with a supervised feed forward neural network (FFNN).</p><p>To assess a DBN’s ability to grasp similar visual concepts, an analysis with hierarchical clustering methods and confusion matrices is performed. Finally, both DBN and FFNN robustness are validated, providing gaussian noise, salt &amp; pepper noise, and adversarial attacks.</p><h3>Data</h3><p>Model training is based on letters, provided by EMNIST dataset. Each data instance represents a greyscale-value image of 28 × 28 pixels, like in figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/0*Vfycr_kQtsMO0y_D.jpg" /></figure><p>For this study, we limited the whole dataset with ten classes and 4800 images for each class. Thus, both models are trained on a set of 48000 images, while the accuracy is reported based on 8000 unseen data instances.</p><p>Before training models, it was made sure that the class distribution is uniform for both train and validation sets. This proves accuracy to be a valid metrics for models comparison (image below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/0*a5xgA8c0UC_4mJTu.jpg" /></figure><p>Preprocessing procedure includes max-scaling the data, by dividing the images greyscale value by the maximum of 255.</p><h3>Model, architecture</h3><p>In this work, two types of architectures are presented — a shallow DBN model with 500 hidden units, versus a deep belief network with two hidden layers of 500 units each. One needs to choose an FFNN architecture accordingly with the chosen DBN structure. Hence, the presented FFNN model has one hidden layer of 500 neurons, and 784 input neurons, representing flattened pixels of an input image.</p><p>In addition, several perceptrons were trained for multi-classification task, with DBN hidden layers as input. In latter parts, FFNN performance will be compared with perceptrons, trained on DBN hidden representations, instead of raw images.</p><h3>Training and validating method</h3><p>For comparison purposes, a Feed Forward Neural Network (FFNN) was trained during approximately the same time as the shallow DBN model. This is why number of training epochs varies between two types of architectures — 1500 and 120 epochs perceptron and FFNN model respectively. Since the datasets are balanced, we select accuracy, as a metric to compare models performance.</p><h3>Receptive fields visualization</h3><p>A figure below presents neurons receptive fields of a deep belief network. Each receptive field represents a layer of weight matrix <strong>W</strong>, projected at two dimensional space of 28 × 28 pixels. Thus, a greyscale value highlights the neurons connection strength. The higher the greyscale value, the more important a certain regiou (visual concept) of the image is. In two images, we present the neurons receptive fields of the first and the second hidden layer.</p><p>The receptive fields clearly visualize, how an unsupervised model captures more specific details with deeper hidden layers. While the first layer receptive fields are essentially greyish, (not specified), deeper layers focus on particular types of letters features, as it is demonstrated by bright dots and lines on contrast receptive fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*MBbRG37EiTCp9chG.png" /></figure><p>Thus, deeper level receptive fields indicate a separation of responsibility between neurons. Certain groups of hidden units are responsible for particular features detection.</p><h3>Internal representations clustering</h3><p>In order to understand, if an unsupervised model was able to capture similar visual features, one can calculate mean hidden representations, corresponding to each class. Afterwards, an hierarchical clustering algorithm has to be applied to mean representations, to evaluate their similarity. Please refer to an image below, to see the example.</p><p>What you will see is a <strong>dendrogram</strong>. It summarizes similarities, that the model has learnt from the visual data. For example, it finds, that classes two and four, three and nine, one and seven, and zero with six are very similar (according to the left dendrogram). As the knowledge representations of deeper layers change, they find similarities between different pairs of classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KOm23gkFHrEkR6eu.png" /></figure><p>Let us pair images, according to the similarities, discovered by the model, and visually assess, if they are really similar? 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/0*M8egvtH0-Y5vlPhr.png" /></figure><p>The answer is — yes, indeed, from visual analysis one can conclude, that unsupervised model successfully encodes similarity of visual concepts.</p><h3>Linear read-out performance</h3><p>In this chapter, we report models performance on unseen validation data. We perform <strong>linear read-out</strong>, which is a technique, that uses internal representations of hidden DBN layers as input data for perceptrons, trained for multiclassification problem. In this way, the input for the final model is no longer raw, training data, but the <strong>representations of knowledge</strong>, captured by deep belief network. In theory, it makes the learning process easier, as the raw data was already pre-processed, to discover most meaningful features of input images.</p><p>In this chapter, we compare performance of perceptrons, trained on hidden representations, with FFNN model, trained on raw images. Thus, hidden layer of FFNN network is both responsible for feature extraction, as well as for tuning for the multiclassification task.</p><p>A figure below summarizes accuracies on the validation dataset. It clearly demonstrates benefits of learning from data with pre-extracted features, generated by unsupervised models. Linear read-outs outperform FFNN model by around 10%, with an accuracy above 80% on unseen data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*5KarqQATv4Vf8Xje.jpg" /></figure><p>Moreover, internal representations are favored over raw images, since they serve as “shared” data for multiple tasks (e.g. letter and digit recognition). Thus, using shared representation is beneficial, because one can flexibly readjust model for another task, instead of retraining model from scratch.</p><h3>Noise robustness</h3><p>Let us compare models’ performance with unseen data, distorted by random noise insertions. Two types of noise are introduced. Figure below illustrates distortions, imposed by Salt &amp; Pepper and Gaussian random noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/0*ssBprTU5vFKkFYeV.jpg" /></figure><p>For noise coverage, ranged from 0% (original image) to 50%, we perform accuracy computation on the unseen validation data. Figures 9 and 10 below report models’ accuracies on the test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0cWppt3INs4zlpRZ.png" /></figure><p>In summary, perceptrons, learned on hidden representations of various depths, outperform FFNN model for noise intensities up to 30%. In addition, models behaviour was consistent for both Gaussian and Salt and Pepper noise.</p><h3>Adversarial attacks</h3><p>One beneficial trait of DBN model is the capability for data reconstruction, which is essential for adversarial attacks. For instance, a figure below demonstrates that, by adding specific noise, accounting for loss function gradient, it is feasible to negatively affect model’s predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*2Scr0KUNY0QoIIdK.jpg" /></figure><p>However, DBN capacity for reconstruction allows the this model to stay robust against adversarial examples. For instance, after two reconstruction steps, performed by shallow DBN, resulting image is almost free of adversarial distortions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KvRktyp5377u_E5I.jpg" /></figure><p>To evaluate DBN robustness against adversarial samples, its accuracy was assessed on the test set, exposed to attack intensities <em>ϵ</em> ranged from 0 to 2.25, where <em>ϵ</em> stands for gradient multiplication coefficient. Thus, a plot below emphasizes importance of reconstruction. Compared to FFNN model with the steepest accuracy decline, two reconstruction steps allow perceptrons to maintain accuracy of around 70% for weak attacks with <em>ϵ</em> less than 0.05.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/0*ciWn8J9n-l_mQt6t.jpg" /></figure><h3>Confusion matrix analysis</h3><p>Confusion matrices allow to understand the nature of misclassifications and identify similar alphabet symbols.</p><p>Along the main axes of two confusion matrices below, the underperformance for certain classes is clear. For instance, 18% of FFNN misclassifications account for classes nine and three, which are actually visually similar, as you can make sure from the images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/0*QegSgbPcI6lu4c8n.png" /></figure><p>All confusion matrices exhibit the same pattern. For instance, also the model, learned from internal representations of the first hidden layer, in 17% of cases labels instances of class nine as letters, corresponding to class three. One of possible explanations for underperforming of models is a greater variety of written letters, as opposed to digits in MNIST dataset. EMNIST letters encapsulate both upper-case and lower-case letters as instances, corresponding to the same class, which ensures a greater statistical variety.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*_y5Rndz4QeJz5QaA.jpg" /></figure><h3>Conclusion</h3><p>In this study, we compared visual concept learning, implemented by deep belief network and feed forward neural network. Neuron receptive fields visualizations emphasized how DBN units infer visual features. Mean hidden representations clustering proves DBN ability for capturing similarities between different classes. Finally, perceptrons, learned on internal representations, demonstrate higher accuracy (80%), as opposed to feed forward neural network with 70% accuracy on the validation set. Moreover, DBN model exhibits highter robustness to two types of noise and adversarial attacks. Confusion matrix analysis revealed that mostly, all studied models misclassify visually similar instances.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=def8b97ebfa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the Rosetta translation interface with Django Rest Framework  ]]></title>
            <link>https://medium.com/@yashnarsamiyev2/using-the-rosetta-translation-interface-with-django-rest-framework-4ee9c023b297?source=rss-1775992469b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ee9c023b297</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[translation]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Yashnarbek Samiyev]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 06:42:10 GMT</pubDate>
            <atom:updated>2023-11-30T06:42:10.198Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A Django application that eases the translation of Django projects</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LlJG1QK4stNOgPrF.png" /><figcaption>A Django application that eases the translation of Django projects</figcaption></figure><h3>Project description</h3><blockquote>Rosetta is a <a href="http://www.djangoproject.com/">Django</a> application that eases the translation process of your Django projects.</blockquote><blockquote>Because it doesn’t export any models, Rosetta doesn’t create any tables in your project’s database. Rosetta can be installed and uninstalled by simply adding and removing a single entry in your project’s INSTALLED_APPS and a single line in your main urls.py file.</blockquote><h3>Features</h3><blockquote>Database independent</blockquote><blockquote>Reads and writes your project’s gettext catalogs (po and mo files)</blockquote><blockquote>Installed and uninstalled in under a minute</blockquote><blockquote>Uses Django’s admin interface CSS</blockquote><h3>Requirements</h3><ul><li>Rosetta supports Django 1.4 through 1.8.</li></ul><h3>Installation</h3><p>To install Rosetta:</p><ol><li>pip install django-rosetta</li><li>Add ‘rosetta’ to the INSTALLED_APPS in your project’s settings.py</li><li>Add an URL entry to your project’s urls.py, for example:</li></ol><ul><li>from django.conf import settings if ‘rosetta’ in settings.INSTALLED_APPS: urlpatterns += patterns(‘’, url(https://medium.com/r%E2%80%99%5Erosetta/%E2%80%99,%20include(%E2%80%98rosetta.urls%E2%80%99)), )</li></ul><p>Note: you can use whatever you wish as the URL prefix.</p><p>To uninstall Rosetta, simply comment out or remove the ‘rosetta’ line in your INSTALLED_APPS</p><h3>Configuration</h3><p>Rosetta can be configured via the following parameters, to be defined in your project settings file:</p><blockquote>ROSETTA_MESSAGES_PER_PAGE: Number of messages to display per page. Defaults to 10.</blockquote><blockquote>ROSETTA_ENABLE_TRANSLATION_SUGGESTIONS: Enable AJAX translation suggestions. Defaults to False.</blockquote><blockquote>YANDEX_TRANSLATE_KEY: Translation suggestions from Yandex <a href="http://api.yandex.com/translate/">Yandex.Translate API</a>. To use this service you must first <a href="http://api.yandex.com/key/form.xml?service=trnsl">obtain an AppID key</a>, then specify the key here. Defaults to None.</blockquote><blockquote>ROSETTA_GOOGLE_TRANSLATE: Translation suggestions via the <a href="http://pythonhosted.org/goslate/">Free Google Translate API</a>. You’ll have to pip install goslate. Defaults to False.</blockquote><blockquote>AZURE_CLIENT_ID and AZURE_CLIENT_SECRET: Translation suggestions using the Microsoft Azure API. To use this service, you must first <a href="https://datamarket.azure.com/dataset/5BA839F1-12CE-4CCE-BF57-A49D98D29A44">register for the service</a>, then specify the ‘Customer ID’ and ‘Primary Account Key’ respectively, which you can find on your <a href="https://datamarket.azure.com/account?lang=en">account information page on Azure Marketplace</a>.</blockquote><blockquote>ROSETTA_MESSAGES_SOURCE_LANGUAGE_CODE and ROSETTA_MESSAGES_SOURCE_LANGUAGE_NAME: Change these if the source language in your PO files isn’t English. Default to ‘en’ and ‘English’ respectively.</blockquote><blockquote>ROSETTA_WSGI_AUTO_RELOAD and ROSETTA_UWSGI_AUTO_RELOAD: When running WSGI daemon mode, using mod_wsgi 2.0c5 or later, this setting controls whether the contents of the gettext catalog files should be automatically reloaded by the WSGI processes each time they are modified. For performance reasons, this setting should be disabled in production environments. Default to False.</blockquote><blockquote>ROSETTA_EXCLUDED_APPLICATIONS: Exclude applications defined in this list from being translated. Defaults to ().</blockquote><blockquote>ROSETTA_REQUIRES_AUTH: Require authentication for all Rosetta views. Defaults to True.</blockquote><blockquote>ROSETTA_POFILE_WRAP_WIDTH: Sets the line-length of the edited PO file. Set this to 0 to mimic makemessage’s — no-wrap option. Defaults to 78.</blockquote><blockquote>ROSETTA_STORAGE_CLASS: See the note below on Storages. Defaults to rosetta.storage.CacheRosettaStorage</blockquote><blockquote>ROSETTA_ACCESS_CONTROL_FUNCTION: An alternative function that determines if a given user can access the translation views. This function receives a user as its argument, and returns a boolean specifying whether the passed user is allowed to use Rosetta or not.</blockquote><blockquote>ROSETTA_LANGUAGE_GROUPS: Set to True to enable language-specific groups, which can be used to give different translators access to different languages. Instead of creating a global translators group, create individual per-language groups, e.g. translators-de, translators-fr, and assign users to these.</blockquote><blockquote>ROSETTA_CACHE_NAME: When using rosetta.storage.CacheRosettaStorage, you can store the Rosetta data in a specific cache. This is particularly useful when your default cache is a django.core.cache.backends.dummy.DummyCache (which happens on pre-production environments). If unset, it will default to rosetta if a cache with this name exists, or default if not.</blockquote><blockquote>ROSETTA_POFILENAMES: Defines which po file names are exposed in the web interface. Defaults to (‘django.po’, ‘djangojs.po’)</blockquote><blockquote>ROSETTA_EXCLUDE_PATHS: Exclude paths defined in this list from being searched (usually ends with “locale”). Defaults to ()</blockquote><h3>Storages</h3><p>To prevent re-reading and parsing the PO file catalogs over and over again, Rosetta stores them in a volatile location. This can be either the HTTP session or the Django cache.</p><p>Django 1.4 has introduced a signed cookie session backend, which stores the whole content of the session in an encrypted cookie. Unfortunately this doesn’t work with large PO files, as the limit of 4096 chars that can be stored in a cookie are easily exceeded.</p><p>In this case the Cache-based backend should be used (by setting ROSETTA_STORAGE_CLASS = ‘rosetta.storage.CacheRosettaStorage’). Please make sure that a proper CACHES backend is configured in your Django settings if your Django app is being served in a multi-process environment, or the different server processes, serving subsequent requests, won’t find the storage data left by previous requests.</p><p>Alternatively you can switch back to using the Session based storage by setting ROSETTA_STORAGE_CLASS = ‘rosetta.storage.SessionRosettaStorage in your settings. This is perfectly safe on Django 1.3. On Django 1.4 or higher make sure you have DON’T use the <a href="https://docs.djangoproject.com/en/dev/topics/http/sessions/#using-cookie-based-sessions">signed_cookies</a> SESSION_BACKEND with this Rosetta storage backend or funky things might happen.</p><p><strong>TL;DR</strong>: if you run Django with gunincorn, mod-wsgi or other multi-process environment, the Django-default CACHES LocMemCache backend won’t suffice: use memcache instead, or you will run into issues.</p><h3>Security</h3><p>Because Rosetta requires write access to some of the files in your Django project, access to the application is restricted to the administrator user only (as defined in your project’s Admin interface)</p><p>If you wish to grant editing access to other users:</p><ol><li>Create a ‘translators’ group in your admin interface</li><li>Add the user you wish to grant translating rights to this group</li></ol><h3>Usage</h3><h3>Generate a batch of files to translate</h3><p>See <a href="https://docs.djangoproject.com/en/1.5/topics/i18n/translation/">Django’s documentation on Internationalization</a> to set up your project to use i18n and create the gettext catalog files.</p><h3>Translate away!</h3><p>Start your Django development server and point your browser to the URL prefix you have chosen during the installation process. You will get to the file selection window.</p><p>Select a file and translate each untranslated message. Whenever a new batch of messages is processed, Rosetta updates the corresponding django.po file and regenerates the corresponding mo file.</p><p>This means your project’s labels will be translated right away, unfortunately you’ll still have to restart the web server for the changes to take effect. (NEW: if your web server supports it, you can force auto-reloading of the translated catalog whenever a change was saved. See the note regarding the ROSETTA_WSGI_AUTO_RELOAD variable in conf/settings.py.</p><p>If the webserver doesn’t have write access on the catalog files (as shown in the screen shot below) an archive of the catalog files can be downloaded.</p><h3>Translating Rosetta itself</h3><p>By default Rosetta hides its own catalog files in the file selection interface (shown above.) If you would like to translate Rosetta to your own language:</p><ol><li>Create a subdirectory for your locale inside Rosetta’s locale directory, e.g. rosetta/locale/XX/LC_MESSAGES</li><li>Instruct Django to create the initial catalog, by running django-admin.py makemessages -l XX inside Rosetta’s directory (refer to <a href="http://www.djangoproject.com/documentation/i18n/">Django’s documentation on i18n</a> for details)</li><li>Instruct Rosetta to look for its own catalogs, by appending ?rosetta to the language selection page’s URL, e.g. <a href="http://127.0.0.1:8000/rosetta/pick/?rosetta">http://127.0.0.1:8000/rosetta/pick/?rosetta</a></li><li>Translate as usual</li><li>Send a pull request if you feel like sharing</li></ol><h3>Acknowledgments</h3><ul><li>Rosetta uses the excellent <a href="https://bitbucket.org/izi/polib">polib</a> library to parse and handle gettext files.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ee9c023b297" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>