r/PythonLearning 5d ago

Help Request what do you think ?

i'm learning python for infraestructure this a proyect of a false resgistry of server xd

40 Upvotes

18 comments sorted by

3

u/Interesting-Frame190 5d ago

I think you should listen to reddit and not use a low res screenshot.

To pick at the real code, your data design could use some thinking. Server and Host and somewhat synonymous and represent the same logical idea, but its suggested that you were modeling service (the code running) and host (what the code is running on). In this case, you want to move away from subclassing because the service is not a subclass of host, but its own independent idea. The two still relate with a "has a" style relation that should be modeled. This might look like the "service" object being created with an instance of the host objevt or a method of the host "add_service" that registers the service object. This would multiple services to be registered on one host and mymics the real world nicely.

1

u/Naive-Smoke-5977 5d ago

i see...sorry i'm beginner hahahahah

2

u/tiredITguy42 5d ago

That you shout share code as code not like low resolution screeshot.

2

u/silvertank00 5d ago edited 5d ago
  • you imported pathlib, why are you using os to check if a file existst?
  • use dataclasses, kw_only=true and a @classmethod with forced kwargs with the same args as your json consists to convert your read data into a DTO.
  • raise Exception(...) don't do that. Either be specific, like RuntimeError or inherit from Exception and create your own "IncorrectStateException" or something and raise that. It is much better to handle and react to.

example: ```python from dataclasses import dataclass

@dataclass(kw_only=True) class MyDTO: ip: str hostname: str service: str port: int status: str

@classmethod
def build_from_raw_data(cls, *, ip: str, hostname: str, service: str, port: str, status: str) -> "MyDTO":
    # validation, etc..

    # i.e.
    if not port.isnumeric():
        raise ValueError("incorrect port")

    return cls(
        ip=ip,
        hostname=hostname,
        service=service,
        port=int(port),
        status=status
    )

my_raw_data: dict[str, str] = { "ip":"0.0.0.0", "hostname":"test", "service":"idk", "port":"88", "status":"ok?" }

my_dto_inst = MyDTO.build_from_raw_data(**my_raw_data) print(my_dto_inst) ```

if forced listed kwargs are not your thing or you find it a bit rigid in the perspective of error handling then simply replace it with def build_from_raw_data(cls, **kwargs: dict[str, str]) and you can work up your validation from there

2

u/Naive-Smoke-5977 5d ago edited 5d ago

dammm , i relly idk thath exist , i will use that for correct my piece of sh1t xd , thanks broooo i love youuuuuu :,v that its because i'm beginner sorryyy

2

u/silvertank00 5d ago

It is fine, we all had to start somewhere. I am glad I could help.

Also, if you introduce sensitive data, use this: dataclasses.field

example:

python @dataclass class User: name: str passwd: str = field(repr=False)

this way you are less likely to leak sensitive data.

1

u/Naive-Smoke-5977 3d ago

Es equivalente a lo que va en el ".env" , verdad :v?

2

u/silvertank00 3d ago edited 3d ago

Not really. Your dotenv file(s) are on the filesystem. This method is really useful if you want to read it from there and store it in memory. For instance: if you build a little gui with buttons that would run various things in the background. Lets say dmesg, you see, usually you can't just run it and get a result, you ought to run it via sudo, like this: sudo dmesg. And if your gui program has a button for this, then you have two options:

  • A) ask for credentials every time when you want to run this (better but could be cumbersome)
  • B) store the credentails in your dotenv, read it when your program starts and store it in memory (lets put aside security for a bit lol) and use it when you want to run this subprocess.

If you go with B, then you are handling sensitive credentials and you must do everything in your power to not leak them. With setting the dataclass field's repr argument to False, you cannot leak it with just printing your dataclass instance. (This could really happen in Exceptions or with logging) Additional: if you ask for credentials in CLI, then there is this helpful thing: getpass with this, you can avoid using the normal imput() to ask for passwords, that inherently echoes back the given characters (prints them back to the screen in a readable format)

edit: I might have misunderstood you comment, if you refering to "reading out data from your dotenv and storing it somewhere", then yes, its absolutely good for that. And don't forget: this is a dummy example, in an ideal world you really shouldnt store the sudo password in a plaintext file. But for stuff like API keys, this is still a really great example.

2

u/Naive-Smoke-5977 3d ago

bro , you're my hero

1

u/FeralFanatic 3d ago

Your comment gave me a brain aneurysm. Please type like an adult.

1

u/Naive-Smoke-5977 3d ago

I don't speak you're language , So, my apologies.

1

u/FeralFanatic 3d ago

Nah, you know what I’m on about.

- relly

  • idk
  • sh1t
  • xd
  • brooooo
  • :,v
  • sorryyy

I’ve seen your other comments. You’re capable of not typing like a moronic child.

1

u/Naive-Smoke-5977 3d ago

Ohhh eso entonces supongo que me entiendes , es mi forma de expresarme los de acá en su mayoría seguro no hablan español, que te molesta eso de un desconocido ? Corregiras a un desconocido que está en un lugar anónimo ? Dónde se puede escribir como quiera ? Pensar como quiera ? Y hacer lo que quiera ? . Entonces no pierdas el tiempo tratando de corregirme cuando se perfectamente como escribir y hablar , poner esos emoticones , abreviaciónes y muletillas son parte de mi forma para expresar mejor mi sentimiento. Así que deja de perder el tiempo tratando de corregir a un desconocido en Internet.

1

u/FeralFanatic 3d ago

omg brooo I sowwwy. lik brooo I relly shud fink more sh1t. my bad brooo

1

u/Naive-Smoke-5977 3d ago

Tienes el traductor activado por defecto eh de imaginar , por eso no te das cuenta que este grupo hablan principalmente ingles ?

1

u/FeralFanatic 3d ago

Yes. I have translator enabled by default and that this group mainly speaks English.

1

u/Naive-Smoke-5977 3d ago

Exacto, entonces de que te quejas , por qué te quejas ? Nadie te ah hecho nada tu mismo decidiste leerlo y enojarte , meterte con un desconocido, eso solo me da a entender que si tuviste el tiempo suficiente para tratar de insultarme y/o avergonzarme es por qué no tienes nada más importante que hacer en tu propia vida , piensatelo Broder , nos vemos , que tengas buen día.