Running a python app in NixOS

Hi, I’m new to NixOS and growing in confidence with system configuration for my home server and hetzner VPS using Nix packages and docker containers via oci.containers.

I have very little coding experience and haven’t used the more complex options in Nix (other than switching to flake mode) or python before.

This app is ideal for my setup but I can’t figure out how to get it working… I’ve discussed options re: nix-shell and venv with ChatGPT without any success. I would appreciate any advice on how to get it functional.

Does this work?

Create a file called flake.nix and copy this:

{
  inputs.nixpkgs.url = "github:NixOS/nixpkgs";
  outputs = { nixpkgs, ... }: {
    packages.x86_64-linux = with nixpkgs.legacyPackages.x86_64-linux; rec {
      default = shrinkarr;
      shrinkarr = with python3.pkgs; stdenvNoCC.mkDerivation {
        name = "shrinkarr";
        src = fetchFromGitHub {
          owner = "Dan6erbond";
          repo = "shrinkarr";
          rev = "6e41d8eff6feafadcf406a3108b425b75ff911a1";
          hash = "sha256-EFYDoMl0hEa5/GPZ97Dq438De1Mu2XYLLCiBFChpHR8=";
        };
        installPhase = ''
          mkdir -p $out/opt
          cp -farT shrinkarr $out/opt

          mkdir -p $out/bin
          cat <<EOF >$out/bin/shrinkarr
          #!/bin/sh
          cd $out/opt
          exec ${python.withPackages (pypkgs: with pypkgs; [
            python-qbittorrent
            python-dotenv
            humanfriendly
          ])}/bin/python -m shrinkarr.main
          EOF
          chmod +x $out/bin/shrinkarr
        '';
      };
      python-qbittorrent = with python3.pkgs; buildPythonPackage rec {
        pname = "python-qbittorrent";
        version = "0.4.3";
        src = fetchPypi {
          inherit pname version;
          hash = "sha256-TiLPiYkGKLBUpgqkvRFhpowrD61I7wiG+k0yXmnTgoo=";
        };
        propagatedBuildInputs = [ requests ];

        pythonImportsCheck = [
          "qbittorrent"
        ];
      };
    };
  };
}

Then simply run in the same folder nix run. You may need to enable flakes, if you haven’t already.