Integerating Python Django in Blazor

Overview

Blazor is a web framework developed by Microsoft that allows developers to build interactive web applications using C# and . NET. It offers a productive environment for building web apps that can run in a browser using WebAssembly (Blazor WebAssembly) or on the server (Blazor Server). While Blazor is inherently tied to the .NET ecosystem, there is significant value in integrating Python into Blazor applications, leveraging Python's powerful libraries and simplicity for tasks such as data analysis, machine learning, and automation.

Introduction

This article introduces using Python with Blazor, detailing the benefits of this integration and offering a basic guide to setting up and configuring a Blazor project that incorporates Python.

Blazor

Basic Setup and Configuration with Django
 

Prerequisites

  1. .NET SDK (version 5.0 or later)
  2. Python (version 3.6 or later)
  3. Visual Studio Code or Visual Studio
  4. Django (`pip install Django)

1. Create a Blazor WebAssembly Project

Open a terminal and run the following commands to create a new Blazor WebAssembly project:

dotnet new blazorwasm -o BlazorPythonDjangoApp
cd BlazorPythonDjangoApp

2. Set Up the Django Environment

Create a new directory for your Django project:

mkdir DjangoAPI
cd DjangoAPI

Create and activate a virtual environment.

python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate

Install Django.

pip install django

Create a new Django project.

django-admin startproject mysite
cd mysite
django-admin startapp api

3. Configure Django

Add the new `api` app to your `INSTALLED_APPS` in `mysite/settings.py`.

INSTALLED_APPS = [
    # ...
    'API',
]

Create a view in `api/views.py`.

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json

@csrf_exempt
def process(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        result = {"message": "Processed data", "input": data}
        return JsonResponse(result)

Add a URL pattern for the new view in `api/urls.py`.

from django.urls import path
from .views import process
urlpatterns = [
    path('process/', process, name='process'),
]

Include the `api` URLs in the main `mysite/urls.py`.

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('api.urls')),
]

Run the Django development server.

python manage.py runserver

Your Django API should now be running on `http://127.0.0.1:8000`.

4. Call the Django API from Blazor

Open the Blazor project in your preferred IDE and modify `Pages/Index.razor` to include a form that sends data to the Django API and displays the response.

@page "/"
@using System.Net.Http
@using System.Net.Http.Json
@inject HttpClient Http
<h3>Blazor and Django Integration</h3>
<div>
    <input @bind="inputData" placeholder="Enter some data" />
    <button @onclick="ProcessData">Process</button>
</div>
@if (responseData != null)
{
    <div>
        <h4>Response from Django API:</h4>
        <p>@responseData</p>
    </div>
}
@code {
    private string inputData;
    private string responseData;

    private async Task ProcessData()
    {
        var data = new { input = inputData };
        var response = await Http.PostAsJsonAsync("http://127.0.0.1:8000/api/process/", data);
        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>();
            responseData = result?["message"];
        }
    }
}

Ensure the `Program. cs` file is set up to use the `HttpClient`.

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

5. Run the Blazor Project

Run the Blazor project:

dotnet run

Open the browser and navigate to `http://localhost:5000`. You should see an input field where you can enter data and a button to process it. The data is sent to the Django API upon clicking the button, and the response is displayed on the page.

Conclusion

Integrating Python with Blazor using Django as the backend allows developers to leverage the robust features of Django, such as its built-in admin interface, authentication, and ORM. This setup demonstrates a simple integration that can be extended to more complex scenarios, including advanced data processing, machine learning, and automation tasks. By combining the strengths of both Blazor and Django, developers can create powerful and efficient web applications.


Similar Articles