Tutorial: Use GitLab Duo to create a shop application in Python

You have been hired as a developer at an online bookstore. The current system for managing inventory is a mix of spreadsheets and manual processes, leading to inventory errors and delayed updates. Your team needs to create a web application that can:

  • Track book inventory in real time.
  • Enable staff to add new books as they arrive.
  • Prevent common data entry errors, like negative prices or quantities.
  • Provide a foundation for future customer-facing features.

This tutorial guides you through creating and debugging a Python web application with a database backend that meets these requirements.

You’ll use GitLab Duo Chat and GitLab Duo Code Suggestions to help you:

  • Set up an organized Python project with standard directories and essential files.
  • Configure the Python virtual environment.
  • Install the Flask framework as the foundation for the web application.
  • Install required dependencies, and prepare the project for development.
  • Set up the Python configuration file and environment variables for Flask application development.
  • Implement core features, including article models, database operations, API routes, and inventory management features.
  • Test that the application works as intended, comparing your code with example code files.

Before you begin

Use GitLab Duo Chat and Code Suggestions

In this tutorial, you will use Chat and Code Suggestions to create the Python web application. Multiple ways exist to use these features.

Use GitLab Duo Chat

You can use Chat in the GitLab UI, the Web IDE, or in your IDE.

Use Chat in the GitLab UI

  1. In the upper-right corner, select GitLab Duo Chat. A drawer opens on the right side of your browser tab.
  2. Enter your question in the chat input box. Press Enter, or select Send. It might take a few seconds for the interactive AI chat to produce an answer.

Use Chat in the Web IDE

  1. Open the Web IDE:
    1. In the GitLab UI, on the left sidebar, select Search or go to and find your project.
    2. Select a file. Then in the upper right, select Edit > Open in Web IDE.
  2. Open Chat by using one of these methods:
    • On the left sidebar, select GitLab Duo Chat.
    • In the file that you have open in the editor, select some code.
      1. Right-click and select GitLab Duo Chat.
      2. Select Explain selected code, Generate Tests, or Refactor.
    • Use the keyboard shortcut: ALT+d (on Windows and Linux) or Option+d (on Mac).
  3. In the message box, enter your question. Press Enter, or select Send.

Use Chat in your IDE

How you use Chat in your IDE differs depending on which IDE you use.

  1. In VS Code, open a file. The file does not need to be a file in a Git repository.
  2. On the left sidebar, select GitLab Duo Chat ( duo-chat ).
  3. In the message box, enter your question. Press Enter, or select Send.
  4. In the chat pane, on the top right corner, select Show Status to show information in the Command Palette.

You can also interact with Duo Chat while you’re working with a subset of code.

  1. In VS Code, open a file. The file does not need to be a file in a Git repository.
  2. In the file, select some code.
  3. Right-click and select GitLab Duo Chat.
  4. Select an option, or Open Quick Chat and ask a question, like Can you simplify this code? and press Enter.

For more information, see Use GitLab Duo Chat in VS Code.

Use Code Suggestions

To use Code Suggestions:

  1. Open your Git project in a supported IDE.

  2. Add the project as a remote of your local repository using git remote add.

  3. Add your project directory, including the hidden .git/ folder, to your IDE workspace or project.

  4. Author your code. As you type, suggestions are displayed. Code Suggestions provides code snippets or completes the current line, depending on the cursor position.

  5. Describe the requirements in natural language. Code Suggestions generates functions and code snippets based on the context provided.

  6. When you receive a suggestion, you can do any of the following:

    • To accept a suggestion, press Tab.
    • To accept a partial suggestion, press either Control+Right arrow or Command+Right arrow.
    • To reject a suggestion, press Esc.
    • To ignore a suggestion, keep typing as you usually would.

For more information, see the Code Suggestions documentation.

Now that you know how to use Chat and Code Suggestions, let’s start building the web application. First, you will create an organized Python project structure.

Create the project structure

To start with, you need a well-organized project structure that follows Python best practices. A proper structure makes your code more maintainable, testable, and easier for other developers to understand.

You can use Chat to help you understand Python project organization conventions and generate the appropriate files. This saves you time researching best practices, and ensures you do not miss critical components.

  1. Open Chat in your IDE and enter:

    Copy to clipboard
    What is the recommended project structure for a Python web application? Include
    common files, and explain the purpose of each file.

    This prompt helps you understand Python project organization before creating files.

  2. Create a new folder for the Python project and create a directory and file structure based on Chat’s response. It will probably be similar to the following:

    Copy to clipboard
    python-shop-app/
    ├── LICENSE
    ├── README.md
    ├── requirements.txt
    ├── setup.py
    ├── .gitignore
    ├── .env
    ├── app/
    │   ├── __init__.py
    │   ├── models/
    │   │   ├── __init__.py
    │   │   └── article.py
    │   ├── routes/
    │   │   ├── __init__.py
    │   │   └── shop.py
    │   └── database.py
    └── tests/
        ├── __init__.py
        └── test_shop.py
  3. You must populate the .gitignore file. Enter the following into Chat:

    Copy to clipboard
    Generate a .gitignore file for a Python project that uses Flask, SQLite, and
    virtual environments. Include common IDE files.
  4. Copy the response into the .gitignore file.

  5. For the README file, enter the following into Chat:

    Copy to clipboard
    Generate a README.md file for a Python web application that manages a bookstore
    inventory. Make sure that it includes all sections for requirements, setup, and usage.

You have now created a properly-structured Python project that follows industry best practices. This organization makes your code easier to maintain and test. Next, you’ll set up your development environment to start writing code.

Set up the development environment

A properly isolated development environment prevents dependency conflicts and makes your application deployable.

You will use Chat to help you set up a Python virtual environment and create a requirements.txt file with the right dependencies. This ensures you have a stable foundation for development.

Copy to clipboard
   python-shop-app/
   ├── LICENSE
   ├── README.md
   ├── requirements.txt <= File you are updating
   ├── setup.py
   ├── .gitignore
   ├── .env
   ├── app/
   │   ├── __init__.py
   │   ├── models/
   │   │   ├── __init__.py
   │   │   └── article.py
   │   ├── routes/
   │   │   ├── __init__.py
   │   │   └── shop.py
   │   └── database.py
   └── tests/
       ├── __init__.py
       └── test_shop.py
  1. Optional. Ask Chat about how Python and Flask work together to produce web applications.

  2. Use Chat to understand the best practices for setting up a Python environment:

    Copy to clipboard
    What are the recommended steps for setting up a Python virtual environment with
    Flask? Include information about requirements.txt and pip.

    Ask any follow-up questions that you need to. For example:

    Copy to clipboard
    What does the requirements.txt do in a Python web app?
  3. Based on the response, first create and activate a virtual environment (for example, on MacOS using Homebrew’s python3 package):

    Copy to clipboard
    python3 -m venv myenv
    source myenv/bin/activate
  4. You must also create a requirements.txt file. Ask Chat the following:

    Copy to clipboard
    What should be included in requirements.txt for a Flask web application with
    SQLite database and testing capabilities? Include specific version numbers.

    Copy the response to the requirements.txt file.

  5. Install the dependencies named in the requirements.txt file:

    Copy to clipboard
    pip install -r requirements.txt

Your development environment is now configured with all necessary dependencies isolated in a virtual environment to prevent conflicts. Next, you’ll configure the project’s package and environment settings.

Configure the project

Proper configuration, including environment variables, enables your application to run consistently across different environments.

You’ll use Code Suggestions to help generate and refine the configuration. Then, you’ll ask Chat to explain the purpose of each setting, so you understand what you’re configuring and why.

  1. You have already created a Python configuration file called setup.py in your project folder:

    Copy to clipboard
       python-shop-app/
       ├── LICENSE
       ├── README.md
       ├── requirements.txt
       ├── setup.py <= File you are updating
       ├── .gitignore
       ├── .env
       ├── app/
       │   ├── __init__.py
       │   ├── models/
       │   │   ├── __init__.py
       │   │   └── article.py
       │   ├── routes/
       │   │   ├── __init__.py
       │   │   └── shop.py
       │   └── database.py
       └── tests/
           ├── __init__.py
           └── test_shop.py

    Open this file, and enter this comment at the top of the file:

    Copy to clipboard
    # Populate this setup.py configuration file for a Flask web application
    # Include dependencies for Flask, testing, and database functionality
    # Use semantic versioning

    Code Suggestions generates the configuration for you.

  2. Optional. Select the generated configuration code and use the following slash commands:

    • Use /explain to understand what each configuration setting does.
    • Use /refactor to identify potential improvements in the configuration structure.
  3. Review and adjust the generated code as needed.

    If you are not sure what you can adjust in the configuration file, ask Chat.

    If you want to ask Chat what to adjust, do so in the IDE in the setup.py file, instead of in the GitLab UI. This provides Chat with the context you’re working in, including the setup.py file you just created.

    Copy to clipboard
    You have used Code Suggestions to generate a Python configuration file, `setup.py`,
    for a Flask web application. This file includes dependencies for Flask, testing,
    and database functionality. If I were to review this file, what might I want
    to change and adjust?
  4. Save the file.

Set the environment variables

Next, you’re going to use both Chat and Code Suggestions to set the environment variables.

  1. In Chat, ask the following:

    Copy to clipboard
    In a Python project, what environment variables should be set for a Flask application in development mode? Include database configuration.
  2. You have already created a .env file to store environment variables.

    Copy to clipboard
       python-shop-app/
       ├── LICENSE
       ├── README.md
       ├── requirements.txt
       ├── setup.py
       ├── .gitignore
       ├── .env <= File you are updating
       ├── app/
       │   ├── __init__.py
       │   ├── models/
       │   │   ├── __init__.py
       │   │   └── article.py
       │   ├── routes/
       │   │   ├── __init__.py
       │   │   └── shop.py
       │   └── database.py
       └── tests/
           ├── __init__.py
           └── test_shop.py

    Open this file, and enter the following comment at the top of the file, including the environment variables that Chat recommended:

    Copy to clipboard
    # Populate this .env file to store environment variables
    # Include the following
    # ...
    # Use semantic versioning
  3. Review and adjust the generated code as needed, and save the file.

You have configured your project and set the environment variables. This ensures your application can be deployed consistently across different environments. Next, you’ll create the application code for the inventory system.

Create the application code

The Flask web framework has three core components:

  • Models: Contains the data and business logic, and the database model. Specified in the article.py file.
  • Views: Handles HTTP requests and responses. Specified in the shop.py file.
  • Controller: Manages data storage and retrieval. Specified in the database.py file.

You will use Chat and Code Suggestions to help you define each of these three components in three files in your Python project structure:

  • article.py defines the models component, specifically the database model.
  • shop.py defines the views component, specifically the API routes.
  • database.py defines the controller component.

Create the article file to define the database model

Your bookstore needs database models and operations to manage inventory effectively.

To create the application code for the bookstore inventory system, you will use an article file to define the database model for articles.

You will use Code Suggestions to help generate the code, and Chat to implement best practices for data modeling and database management.

  1. You have already created an article.py file:

    Copy to clipboard
       python-shop-app/
       ├── LICENSE
       ├── README.md
       ├── requirements.txt
       ├── setup.py
       ├── .gitignore
       ├── .env
       ├── app/
       │   ├── __init__.py
       │   ├── models/
       │   │   ├── __init__.py
       │   │   └── article.py <= File you are updating
       │   ├── routes/
       │   │   ├── __init__.py
       │   │   └── shop.py
       │   └── database.py
       └── tests/
           ├── __init__.py
           └── test_shop.py

    In this file, use Code Suggestions and enter the following:

    Copy to clipboard
    # Create an Article class for a bookstore inventory system
    # Include fields for: name, price, quantity
    # Add data validation for each field
    # Add methods to convert to/from dictionary format
  2. Optional. Use the following slash commands:

    • Use /explain to understand how the article class works and its design patterns.
    • Use, /refactor to identify potential improvements in the class structure and methods.
  3. Review and adjust the generated code as needed, and save the file.

Next you will define the API routes.

Create the shop file to define the API routes

Now that you have created the article file to define the database model, you will create the API routes.

API routes are crucial for a web application because they:

  • Define the public API for clients to interact with your application.
  • Map HTTP requests to the appropriate code in your application.
  • Handle input validation and error responses.
  • Transform data between your internal models and the JSON format expected by API clients.

For your bookstore inventory system, these routes will allow staff to:

  • View all books in inventory.
  • Look up specific books by ID.
  • Add new books as they arrive.
  • Update book information such as price or quantity.
  • Remove books that are no longer needed.

In Flask, routes are functions that handle requests to specific URL endpoints. For example, a route for GET /books would return a list of all books, while POST /books would add a new book to the inventory.

You will use Chat and Code Suggestions to create these routes in the shop.py file that you’ve already set up in your project structure:

Copy to clipboard
python-shop-app/
├── LICENSE
├── README.md
├── requirements.txt
├── setup.py
├── .gitignore
├── .env
├── app/
│   ├── __init__.py
│   ├── models/
│   │   ├── __init__.py
│   │   └── article.py
│   ├── routes/
│   │   ├── __init__.py
│   │   └── shop.py <= File you are updating
│   └── database.py
└── tests/
   ├── __init__.py
   └── test_shop.py

Create the Flask application and routes

  1. Open the shop.py file. To use Code Suggestions, enter this comment at the top of the file:
Copy to clipboard
# Create Flask routes for a bookstore inventory system
# Include routes for:
# - Getting all books (GET /books)
# - Getting a single book by ID (GET /books/<id>)
# - Adding a new book (POST /books)
# - Updating a book (PUT /books/<id>)
# - Deleting a book (DELETE /books/<id>)
# Use the Article class from models.article and database from database.py
# Include proper error handling and HTTP status codes
  1. Review the generated code. It should include:

    • Import statements for Flask, request, and jsonify.
    • Import statements for your Article class and database module.
    • Route definitions for all CRUD operations (Create, Read, Update, Delete).
    • Proper error handling and HTTP status codes.
  2. Optional. Use these slash commands:

    • Use /explain to understand how the Flask routing works.
    • Use /refactor to identify potential improvements.
  3. If the generated code doesn’t fully meet your needs, or you want to understand how to improve it, you can ask Chat from within the shop.py file:

Copy to clipboard
Can you suggest improvements for my Flask routes in this shop.py file?
I want to ensure that:
1. The routes follow RESTful API design principles
2. Responses include appropriate HTTP status codes
3. Input validation is handled properly
4. The code follows Flask best practices
  1. You also need to create the Flask application instance in the __init__.py file inside the app directory. Open this file and use Code Suggestions to generate the appropriate code:
Copy to clipboard
# Create a Flask application factory
# Configure the app with settings from environment variables
# Register the shop blueprint
# Return the configured app
  1. Save both files.

Create the database file to manage data storage and retrieval

Finally, you will create the database operations code. You have already created a database.py file:

Copy to clipboard
   python-shop-app/
   ├── LICENSE
   ├── README.md
   ├── requirements.txt
   ├── setup.py
   ├── .gitignore
   ├── .env
   ├── app/
   │   ├── __init__.py
   │   ├── models/
   │   │   ├── __init__.py
   │   │   └── article.py
   │   ├── routes/
   │   │   ├── __init__.py
   │   │   └── shop.py
   │   └── database.py <= File you are updating
   └── tests/
       ├── __init__.py
       └── test_shop.py
  1. Enter the following into Chat:

    Copy to clipboard
    Generate a Python class that manages SQLite database operations for a bookstore inventory. Include:
    - Context manager for connections
    - Table creation
    - CRUD operations
    - Error handling
    Show the complete code with comments.
  2. Review and adjust the generated code as needed, and save the file.

You have successfully created the foundational code for your inventory management system and defined the core components of a Python web application built using the Flask framework.

Next you’ll check your created code against example code files.

Check your code against example code files

The following examples show complete, working code that should be similar to the code you end up with after following the tutorial.

This file shows standard Python project exclusions:

Copy to clipboard
# Virtual Environment
myenv/
venv/
ENV/
env/
.venv/

# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg

# SQLite database files
*.db
*.sqlite
*.sqlite3

# Environment variables
.env
.env.local
.env.*.local

# IDE specific files
.idea/
.vscode/
*.swp
*.swo
.DS_Store
  1. Check your code files against these examples.

  2. To verify if your code works, ask Chat how to start a local application server:

    Copy to clipboard
    How do I start a local application server for my Python web application?
  3. Follow the instructions, and check if your application is working.

If your application is working, congratulations! You have successfully used GitLab Duo Chat and Code Suggestions to build working online shop application.

If it is not working, then you need to find out why. Chat and Code Suggestions can help you create tests to ensure your application works as expected and identify any issues that need to be fixed. Issue 1284 exists to create this tutorial.