2 posts tagged with "best practices"

View All Tags

Running Python Scripts in a Virtual Environment: Why It Matters and How to Do It

Conceptual illustration of Python virtual environments

If you're a Python developer, you've probably heard about virtual environments. If not, no worries! In this post, we'll break down what they are, why they're super useful, and, most importantly, how to run your Python scripts inside one. Whether you're just starting out or looking to improve your workflow, this guide has got you covered.

What is a Virtual Environment?#

A virtual environment (often called a "venv") is like a personal workspace for your Python projects. It allows you to keep each project’s dependencies separate from your system’s global Python environment. This means that every project you work on can have its own set of libraries, avoiding conflicts between different versions. Sounds useful, right?

Let’s say you're working on two Python projects:

  • Project A needs Django 3.0.
  • Project B needs Django 4.0.

Without a virtual environment, this would be a problem because you can’t have both versions of Django installed globally at the same time. But with a virtual environment, each project gets its own isolated space with the exact dependencies it needs.

Why Use a Virtual Environment?#

Illustration depicting dependency isolation in Python virtual environments

Now that you know what a virtual environment is, you might be wondering why you should bother using one. Here’s why:

  • Avoid Dependency Conflicts – Each project can have its own versions of libraries without interfering with others.

  • Keep Your Codebase Clean – All dependencies stay inside the project folder, making it easy to share your code. You can also generate a requirements.txt file so others can install the exact dependencies you used.

  • Easier Dependency Management – You can add or remove libraries for a project without worrying about breaking other projects.

  • Simplifies Deployment – When you deploy your project to a server or share it with someone else, using a virtual environment ensures that everything works exactly as it does on your machine. No more "It works on my computer!" issues.

    Official Python venv Documentation

Setting Up a Virtual Environment and Running a Script#

Step-by-step guide to setting up and using a Python virtual environment

Let’s go step by step on how to create a virtual environment and run a Python script inside it.

1. Create a Virtual Environment#

Navigate to your project folder in the terminal or command prompt and run:

python3 -m venv myenv

This creates a new folder called myenv, which contains your virtual environment.

2. Activate the Virtual Environment#

Before using it, you need to activate the environment. The command depends on your operating system:

For macOS/Linux, run:

source myenv/bin/activate

For Windows, run:

myenv\Scripts\activate

Once activated, your terminal prompt will change to show that you’re working inside the virtual environment (you’ll likely see (myenv) at the beginning of the prompt).

3. Install Dependencies#

Now that your virtual environment is active, you can install any required python libraries . For example, if your script needs the requests library, install it like this:

pip install requests

Repeat this for any other libraries your script needs.

4. Run Your Python Script#

Now you’re ready to run your script. Simply use:

python path/to/your_script.py

Your script will now run with the libraries installed in your virtual environment.

5. Deactivate the Virtual Environment#

When you're done, deactivate the virtual environment by running:

deactivate

This will return you to your system’s global Python environment.

Final Thoughts#

Using a virtual environment is one of the best ways to keep your Python projects organized and prevent dependency issues. Each project gets its own isolated space, ensuring everything runs smoothly no matter what libraries you're using.

So, next time you start a new Python project, create a virtual environment—it’ll save you time and headaches down the road.

check out Nife.io (python App on Oikos)

Handling Errors in C# the Easy Way

nginx and docker

You are aware that things don't always go as planned if you have ever dealt with C# or any type of online API. There are instances when you get strange JSON, when a field is missing, and when—well—things just break. The good news is that you don't have to let your app crash and burn because of such problems. We can apprehend them, record them, and continue on.

I'll demonstrate how to use a custom error response object to handle errors in C# in this post. It's similar to building a safety net for your software so that it doesn't go into full panic mode when something goes wrong.

Why Do We Care About Custom Error Responses?#

It's not always sufficient to simply log or print an error to the console when it occurs in your application. You may want to provide more information about the issue, track several faults that occur simultaneously, or simply deliver a kind, easy-to-read message to the user. A custom error answer can help with that.

With a custom error response object, you can:

  • Track different types of errors.
  • Organize your errors into categories (so you know if it's a JSON issue, a database issue, etc.).
  • Handle the error, log it, and then move on without crashing the app.

Setting Up Our Custom Error Object#

nginx and docker

Let's start by setting up a basic error response object. This will hold our error messages in a dictionary, so we can track multiple types of errors.

Here's how you can do it:

public class ErrResponse
{
public string Message { get; set; }
public Dictionary<string, List<string>> Errors { get; set; }
}
  • Message: This is just a generic message about what went wrong.
  • Errors: This is a dictionary that'll hold all the different errors. Each key will represent an error type (like "JsonError" or "GeneralError"), and the value will be a list of error messages. This way, we can keep things organized.

Deserializing JSON and Handling Errors#

Let's say you're deserializing some JSON data, but there's a chance it could fail. Instead of letting the program crash, we can catch that error, store the details in our custom error response, and continue running. Here's how to do it:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string jsonContent = /* your JSON string here */;
ErrResponse errResponse;
try
{
// Try to deserialize the JSON
errResponse = JsonConvert.DeserializeObject<ErrResponse>(jsonContent);
if (errResponse != null)
{
Console.WriteLine("Deserialization successful.");
Console.WriteLine($"Message: {errResponse.Message}");
if (errResponse.Errors != null)
{
foreach (var error in errResponse.Errors)
{
Console.WriteLine($"Error Key: {error.Key}, Values: {string.Join(", ", error.Value)}");
}
}
}
else
{
Console.WriteLine("Deserialization resulted in a null response.");
}
}
catch (JsonException ex)
{
// If JSON deserialization fails, log it
errResponse = new ErrResponse
{
Message = "There was an issue with the JSON.",
Errors = new Dictionary<string, List<string>>()
};
// Add the error to the "JsonError" category
AddError(errResponse, "JsonError", ex.Message);
AddError(errResponse, "JsonError", ex.StackTrace);
Console.WriteLine($"JSON Deserialization error: {ex.Message}");
}
catch (Exception ex)
{
// Catch any other errors that might happen
errResponse = new ErrResponse
{
Message = "Something unexpected went wrong.",
Errors = new Dictionary<string, List<string>>()
};
// Log the general error
AddError(errResponse, "GeneralError", ex.Message);
AddError(errResponse, "GeneralError", ex.StackTrace);
Console.WriteLine($"Unexpected error: {ex.Message}");
}
// Continue running the app, no matter what
Console.WriteLine("The program keeps on running...");
}
// Utility to add errors to the response
private static void AddError(ErrResponse errResponse, string key, string message)
{
if (string.IsNullOrEmpty(message)) return;
if (errResponse.Errors.ContainsKey(key))
{
errResponse.Errors[key].Add(message);
}
else
{
errResponse.Errors[key] = new List<string> { message };
}
}
}

What's Going On Here?#

nginx and docker
  • Deserialization: We attempt to create our ErrResponse object from the JSON. Fantastic if it does. If not, the error is detected.
  • Catching JSON Errors: If the JSON is incorrect, we detect it and use a JsonError value to add it to our Errors dictionary. The error notice and stack trace are then displayed for simpler debugging.
  • General Error Handling: We detect and record any unexpected events (such as database problems or network failures) under the GeneralError key.
  • Program Doesn't Crash: The software continues to operate after the problem has been handled. Thus, without ruining anything, you can log issues, alert someone, or simply go on.

Why This Is Useful#

  • It Keeps Things Neat: We store errors in an organised manner that makes it simple to see what's wrong, as opposed to simply throwing them around.
  • Multiple Errors? No Problem: We don't have to overwrite or overlook anything when we use a dictionary to track numerous faults at once.
  • No App Crashes: In the event that something breaks, the program continues to operate. You recognise the mistake, correct it, and move on with your life.

Conclusion#

Error management doesn't have to be difficult. You may effortlessly handle failures, record crucial information, and maintain the functionality of your program by utilising a custom error response object in C#. There are ways to deal with issues like a broken JSON string or an unplanned crash without everything exploding.

Therefore, bear in mind to identify the mistake, manage it politely, and continue working on your program the next time something goes wrong.

If you're looking for cutting-edge features for cloud deployment, check out what Oikos by Nife has to offer.