SoFunction
Updated on 2024-11-12

Python implementation of a simple library management system

In this article, we share the example of Python to achieve a simple library management system specific code for your reference, the details are as follows

First show the home page of the library management system:

This is the Publish Books page of the library management system:

Lastly, the book details page of the library management system has been the management page of the book for deletion.

This library management system is made for the practice phase and is able to realize the functions of searching book details, adding books and deleting books. The following source code is attached:

The code in the file is as follows:

from  import render,redirect,reverse
from  import connection


# Because the cursor object is used in several of the following view functions, it is defined here as a function.
def get_cursor():
    return ()


def index(request):
    cursor = get_cursor()
    ("select * from db01")
    books = ()
    # At this point books is a tuple of tuples #
    # Print to view
    # print(books)
    # ((1, 'Romance of the Three Kingdoms', 'Luo Guanzhong'), (2, 'Journey to the West', 'Luo Guanzhong'), (3, 'Water Margin', 'Shi Neian'))

    # At this point, if we want to display it in the browser, we have to pass it to the DTL template.
    # Instead of defining the intermediate variable context, you can directly pass the retrieved tuple to the context parameter in the render() function.
    # For example, this is the case where an intermediate variable is defined.
    # context = {
    #     'books':books
    # }

    # Below we pass the fetched tuple directly to the render() function.
    return render(request,'',context={'books':books})


def add_book(request):
    # Because DTL templates use post requests to submit data, you need to first determine which way the data is being submitted.
    # If it was submitted as a get request, it returns directly to the view where the book was published, otherwise it adds the data to the database table
    # Be sure to note: the GET here must be the way to submit GET. not a function get ()
    # Otherwise, it will cause, every time you click on "Publish Book", it will add a data message that is all None,None.
    if  == "GET":
        return render(request,'add_book.html')
    else:
        name = ('name')
        author = ('author')
        cursor = get_cursor()
        # When getting name and author, because both are of string type in the database.
        # So here, it's time to wrap it in single quotes and execute the following statement to insert the data into the database.
        ("insert into db01(id,name,author) values(null ,'%s','%s')" % (name,author))
        # Return to the home page, you can use redirection, and you can reverse the url name of the view function.
        return redirect(reverse('index'))


def book_detail(request,book_id):
        cursor = get_cursor()
        # Compare the submitted data with the ids in the database and return a tuple if they match.
        # (only one tuple will be returned based on the uniqueness of the id)
        # Only the name, auhtor fields are fetched here #
        ("select id,name,author from db01 where id=%s" % book_id)
        # Can be fetched using fetchone().
        book = ()
        # Afterwards after getting this tuple of books, you can render it into the template.
        return render(request,'book_detail.html',context={'book':book})


def del_book(request):
    # Determine if the way to submit data is a post request
    if  == "POST":
        # Use POST to get the book_id of the book, # Use POST to get the book_id of the book.
        book_id = ('book_id')
        # Compare the book_id of the obtained book with the id information in the database
        cursor = get_cursor()
        # Note: The information to be deleted here must not specify attributes, otherwise the data will be submitted unsuccessfully.
        # ("delete id,name,author from db01 where id = '%s'" % book_id)
        ("delete from db01 where id=%s" % book_id)
        return redirect(reverse('index'))
    else:
        raise RuntimeError("The way to submit the data is not a post request")

Because the header part of each page is the same. So here the template inheritance is used to optimize the implementation of the template structure.

Where the parent template code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>library management system</title>
    <link rel="stylesheet" href="{% static '' %}">
</head>
<body>
<header>
    <nav>
        <ul class="nav">
            <li><a href="/">home page (of a website)</a></li>
            <li><a href="{% url 'add' %}">Publishing Books</a></li>
        </ul>
    </nav>
</header>
{% block content %}

{% endblock %}
<footer>

</footer>
</body>
</html>

The code in the home page template is as follows:

{% extends '' %}


{% block content %}
    <table>
        <thead>
        <tr>
            <th>serial number</th>
            <th>reputation as calligrapher</th>
            <th>author</th>
        </tr>
        </thead>
        <tbody>
        {% for book in books %}
            <tr>
                <td>{{  }}</td>
                <td><a href="{% url 'detail' book_id=book.0 %}">{{ book.1 }}</a></td>
                <td>{{ book.2 }}</td>
            </tr>
        {% endfor %}

        </tbody>
    </table>
{% endblock %}

The code in the publish book template add_book.html is as follows:

{% extends '' %}


{% block content %}
{# where this action represents the current content of the form that you want to submit to that view to receive, #}
{# Here we submit to the current view add_book() to process the data, so we don't have to write it #}
{# And method method is used which way to submit form data, commonly used get, post, here using post request.  #}
    <form action="" method="post">
    <table>
        <tr>
            <td>reputation as calligrapher:</td>
            <td><input type="text" name="name"></td>
        </tr>
        <tr>
            <td>author:</td>
            <td><input type="text" name="author"></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Submit" name="sub"></td>
        </tr>
    </table>
    </form>
{% endblock %}

Appropriate mapping of view functions to url in the middle:

from  import path
from front import views

urlpatterns = [
    path('', , name = 'index'),
    path('add/', views.add_book, name = 'add'),
    path('book/detail/<int:book_id>/', views.book_detail, name = 'detail'),
    path('book/del/',views.del_book, name = 'del'),
]

And note: csrf validation needs to be turned off in the file.

MIDDLEWARE = [
    '',
    '',
    '',
    # '',
    '',
    '',
    '',
]

And in the file, add the path variable for loading static files

STATICFILES_DIRS = [
    (BASE_DIR,'static')
]

And set up information about pycharm's connection to the mysql database:

DATABASES = {
    'default': {
        'ENGINE': '',
        'NAME': 'db01',
        'USERNAME': 'root',
        'PASSWORD': 'root',
        'HOST': '127.0.0.1',
        'PORT': '3306'
    }
}

This is the whole content of this article.