Showing posts with label django. Show all posts
Showing posts with label django. Show all posts

Thursday

Django URLs

In Django, the urls.py file is where you define the URL patterns for your web application. There are several ways to write the urls.py file, depending on your project’s structure and requirements. Let’s explore some common approaches:

  1. Basic URL Patterns:

    • The simplest way is to define URL patterns directly in the urls.py file using the path() function. For example:
      from django.urls import path
      from . import views
      
      urlpatterns = [
          path('home/', views.home, name='home'),
          path('about/', views.about, name='about'),
      ]
      
    • In this example, the URLs /home/ and /about/ will be routed to the corresponding view functions (home and about).
  2. Include URLs from Other Apps:

    • If you have multiple apps in your Django project, you can include their URL patterns in the project’s main urls.py using the include() function. This keeps the app-specific URLs organized.
      from django.contrib import admin
      from django.urls import include, path
      
      urlpatterns = [
          path('admin/', admin.site.urls),
          path('members/', include('members.urls')),  # Include app-specific URLs
      ]
      
    • In this example, any URL starting with /members/ will be handled by the app-specific members.urls.
  3. Using Regular Expressions:

    • You can use regular expressions (regex) to define more complex URL patterns. For example:
      from django.urls import re_path
      from . import views
      
      urlpatterns = [
          re_path(r'^articles/(?P<year>\d{4})/$', views.article_by_year),
      ]
      
    • Here, the URL pattern matches /articles/2023/ and captures the year as a parameter.
  4. Class-Based Views:

    • If you’re using class-based views, you can define URL patterns using the as_view() method:
      from django.urls import path
      from .views import MyListView, MyDetailView
      
      urlpatterns = [
          path('list/', MyListView.as_view(), name='list-view'),
          path('detail/<int:pk>/', MyDetailView.as_view(), name='detail-view'),
      ]
      
    • In this example, the MyListView and MyDetailView views are associated with the URLs /list/ and /detail/<pk>/.
  5. Namespacing URLs:

    • If you have multiple apps with similar URL patterns, you can namespace them to avoid conflicts:
      app_name = 'blog'
      urlpatterns = [
          path('articles/', include('blog.urls')),
      ]
      
    • In this case, the app-specific URLs will be prefixed with /articles/.
  6. Using url() Function (Deprecated):

    • Although not recommended, you can use the url() function (deprecated since Django 3.1) instead of path() or re_path():
      from django.conf.urls import url
      from . import views
      
      urlpatterns = [
          url(r'^articles/$', views.article_list),
      ]
      


Sunday

SQLAlchemy and Alembic

 

SQLAlchemy and Alembic: Explained with Example

SQLAlchemy:

  • A powerful Python library for interacting with relational databases.
  • Provides an object-relational mapper (ORM) that lets you define your data model as Python classes and map them to tables in a database.
  • Simplifies writing SQL queries and manipulating data through its object-oriented interface.

Alembic:

  • A migration tool built on top of SQLAlchemy.
  • Allows you to track changes to your database schema over time and manage upgrades and downgrades.
  • Generates migration scripts as your data model evolves, providing version control for your database schema.

Example:

Let's consider a model that defines a User table with two attributes: id (primary key) and username.

Python code (SQLAlchemy):

Python
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

classUser(Base):
    __tablename__ = "users"id = Column(Integer, primary_key=True)
    username = Column(String(50), nullable=False)

engine = create_engine("sqlite:///database.db")
Base.metadata.create_all(engine)

# Creating new User objects and writing to the database
user1 = User(username="alice")
user2 = User(username="bob")

session = Session(engine)
session.add_all([user1, user2])
session.commit()

# Reading users from the database
users = session.query(User).all()
print(users)

Creating a Migration with Alembic:

  1. Initialize Alembic:
alembic init
  1. Generate a migration script for the initial schema:
alembic revision --autogenerate

This creates a migration script containing the necessary SQL statements to create the users table.

  1. Upgrade the database schema:
alembic upgrade

This executes the migration script and creates the users table in the database.

Adding a new attribute to the model:

We can add a new attribute email to the User model:

Python
class User(Base):
    # ... existing code
    email = Column(String(100))

Base.metadata.alter(engine)

This will alter the existing users table in the database and add the email column.

  1. Generate a new migration script:
alembic revision --autogenerate
  1. Upgrade the database schema:
alembic upgrade

Benefits of using SQLAlchemy and Alembic:

  • Code readability: Focuses on the data model structure rather than writing raw SQL queries.
  • Maintainability: Easier to evolve the database schema and track changes.
  • Version control: Migration scripts act as version control for the database schema.
  • Portability: Code can be ported to different databases with minimal changes.

Remember: This is a simplified example. For real-world scenarios, you can define much more complex models with relationships, constraints, and other features.

You can find more example in internet also can check my github repo here https://github.com/dhirajpatra

ETL with Python

  Photo by Hyundai Motor Group ETL System and Tools: ETL (Extract, Transform, Load) systems are essential for data integration and analytics...