PYTHON: mudanças entre as edições

De Wiki Clusterlab.com.br
Ir para navegação Ir para pesquisar
 
(10 revisões intermediárias pelo mesmo usuário não estão sendo mostradas)
Linha 10: Linha 10:


==Reference==
==Reference==
*[https://docs.python.org/3.7/reference/index.html 3.7]
*[https://docs.python.org/3.11/reference/index.html 3.11]
 
==CODE==
==CODE==
===FastApi Controller===
<syntaxhighlight lang=python line=1>
import json
from dataclasses import dataclass
from types import SimpleNamespace
from typing import Optional
from src.model.resource import ResourceModel, ResourceModelList
from fastapi import FastAPI, HTTPException
from src.model.provider import ProviderModel
from src.repository.resource import ResourceRepository
from src.service.resource import ResourceService
import inspect
@dataclass(init=True)
class ResourceController:
    app: FastAPI
    def make_cal(self, obj, all_arguments, method):
        try:
            signature_values = inspect.signature(method).parameters.values()
            all_argument_values = {
                parameter.name: all_arguments[parameter.name] for parameter
                in signature_values}
            return obj(**all_argument_values)
        except Exception as e:
            raise HTTPException(
                status_code=500,
                detail="deu ruim.",
                headers={"X-Error": e.__str__()}
            )
    def __post_init__(self):
        app = self.app
        @app.get("/api/resources", tags=["resource"])
        async def get_api_resources(
                name: Optional[str] | None = None,
                before: Optional[str] | None = None,
                after: Optional[str] | None = None
        ) :
            """
                    Action:
                  - Will return a list of resources.
                    Parameters:
                    - **name**: The name of the resource.
                    - **before**: An EPOCH number to match resources collected before specified dateTime.
                    - **after**: An EPOCH number to match resources collected after specified dateTime.
                    """
            resource_service = ResourceService()
            return self.make_cal(
                resource_service.get_resources,
                locals(),
                get_api_resources
            )
app = FastAPI()
resource_controller = ResourceController(app=app)
</syntaxhighlight>
===Model Class===
===Model Class===
<syntaxhighlight lang=python line=1>
<syntaxhighlight lang=python line=1>
Linha 23: Linha 86:
     name: Optional[str] = None
     name: Optional[str] = None
     address: Optional[str] = None
     address: Optional[str] = None
    def __init__(self, **kwargs):
        self.__dict__.update(**kwargs)
        self.kwargs = kwargs


     def __add__(self, other):
     def __add__(self, other):
Linha 31: Linha 98:
             else:
             else:
                 data.update({attr: other.__getattribute__(attr)})
                 data.update({attr: other.__getattribute__(attr)})
         return User(**data)
         return __class__(**data)


     def __repr__(self):
     def __repr__(self):
         data = {}
         data = {}
         for attr in self.get_attributes():
         for attr in self.get_attributes():
             data.update({attr: self.__getattribute__(attr)})
             if attr == "kwargs":
                continue
            else:
                data.update({attr: self.__getattribute__(attr)})
         return data
         return data


     def __str__(self):
     def __str__(self):
Linha 93: Linha 164:
</syntaxhighlight>
</syntaxhighlight>


==setup.py==
==Packaging Python Projects==
===setup.py===
* https://packaging.python.org/en/latest/tutorials/packaging-projects/
<syntaxhighlight lang=python>
<syntaxhighlight lang=python>
"""Python Setup"""
"""Python Setup"""
Linha 147: Linha 220:


=WEB server=
=WEB server=
==Simple HTTP==
*python2.7 -m SimpleHTTPServer 8383
*python2.7 -m SimpleHTTPServer 8383
*python3 -m http.server 8383
*python3 -m http.server 8383
==HTTPS Python3.12==
[[ OpenSSL#Simple_key_and_cert | Generate key and cert here.]]
<syntaxhighlight lang=python>
import http
from http.server import HTTPServer, BaseHTTPRequestHandler
import ssl
def run():
        server_address = ('127.0.0.1', 5000)
        httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler)
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        context.load_cert_chain(certfile="cert.pem", keyfile="key.pem")
        httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
        httpd.serve_forever()
if __name__ == "__main__":
    run()
</syntaxhighlight>
=Codificação de terminal=
=Codificação de terminal=
<syntaxhighlight lang=bash>
<syntaxhighlight lang=bash>

Edição atual tal como às 18h05min de 22 de novembro de 2024

Python

DATA

PIP

venv/pip.conf

[global]
index-url=https://username:password|PAT@pkgs.somewhere.com/something/xxxxxxxxxx/

Reference

CODE

FastApi Controller

import json
from dataclasses import dataclass
from types import SimpleNamespace
from typing import Optional
from src.model.resource import ResourceModel, ResourceModelList
from fastapi import FastAPI, HTTPException
from src.model.provider import ProviderModel
from src.repository.resource import ResourceRepository
from src.service.resource import ResourceService
import inspect

@dataclass(init=True)
class ResourceController:
    app: FastAPI


    def make_cal(self, obj, all_arguments, method):
        try:
            signature_values = inspect.signature(method).parameters.values()

            all_argument_values = {
                parameter.name: all_arguments[parameter.name] for parameter
                in signature_values}
            return obj(**all_argument_values)

        except Exception as e:
            raise HTTPException(
                status_code=500,
                detail="deu ruim.",
                headers={"X-Error": e.__str__()}
            )
    def __post_init__(self):
        app = self.app

        @app.get("/api/resources", tags=["resource"])
        async def get_api_resources(
                name: Optional[str] | None = None,
                before: Optional[str] | None = None,
                after: Optional[str] | None = None
        ) :
            """
                    Action:
                   - Will return a list of resources.

                    Parameters:

                    - **name**: The name of the resource.
                    - **before**: An EPOCH number to match resources collected before specified dateTime.
                    - **after**: An EPOCH number to match resources collected after specified dateTime.
                    """
            resource_service = ResourceService()
            return self.make_cal(
                resource_service.get_resources,
                locals(),
                get_api_resources
            )
app = FastAPI()
resource_controller = ResourceController(app=app)

Model Class

import json
from dataclasses import dataclass
from types import SimpleNamespace
from typing import Optional

@dataclass(init=True)
class User:
    name: Optional[str] = None
    address: Optional[str] = None

    def __init__(self, **kwargs):
        self.__dict__.update(**kwargs)
        self.kwargs = kwargs

    def __add__(self, other):
        data = {}
        for attr in self.get_attributes():
            if other.__getattribute__(attr) is None:
                data.update({attr: self.__getattribute__(attr)})
            else:
                data.update({attr: other.__getattribute__(attr)})
        return __class__(**data)

    def __repr__(self):
        data = {}
        for attr in self.get_attributes():
            if attr == "kwargs":
                continue
            else:
                data.update({attr: self.__getattribute__(attr)})
        return data


    def __str__(self):
        return json.dumps(self.__repr__())

    def __len__(self):
        count = 0
        for attr in self.get_attributes():
            if self.__getattribute__(attr) is not None:
                count = count + 1
        return count

    def to_dict(self):
        return self.__repr__()

    def get_attributes(self):
        return [attr for attr in dir(self) if not callable(getattr(self, attr)) and not attr.startswith("__")]

    def get_methods(self):
        return [attr for attr in dir(self) if callable(getattr(self, attr)) and not attr.startswith("__")]

    def to_simple_namespace(self):
        return json.loads(self.__str__(), object_hook=lambda d: SimpleNamespace(**d))

    def to_str(self):
        return self.__str__()

    def gen_gettersetters(self):
        for attr in self.get_attributes():
            attr_type = str(type(getattr(self, attr))).split("'")[1]
            print(f"""
    def set_{attr}(self, {attr}: {attr_type}):
        self.{attr} = {attr}
    def get_{attr}(self) -> {attr_type}:
        return self.{attr}""")


if __name__ == "__main__":
    ale1 = User(name="Ale")
    ale2 = User(address="street somewhere")
    print(ale1)
    print(ale2)
    ale = ale1 + ale2
    print(ale)
    print(len(ale1))
    print(len(ale2))
    print(len(ale))

SimpleNamespaces

sn = json.loads(json_data, object_hook=lambda d: SimpleNamespace(**d))
sn = SimpleNamespace(hetero_list=['aa', SimpleNamespace(y='ll')])
json.loads(json.dumps(sn, default=lambda s: vars(s)))

Packaging Python Projects

setup.py

"""Python Setup"""

from setuptools import setup, find_packages


VERSION = '0.0.10'


with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()


setup(
    name="my-app",
    version=VERSION,
    description="Template my-app",
    long_description=long_description,
    author = "Alexandre D'Amato",
    author_email = "devops@clusterlab.com.br",
    license='MIT',
    install_requires=[
        'requests==2.31.0'
        ],
    extras_require={},
    classifiers=[],
    packages=find_packages(exclude=['docs', 'tests']),
    python_requires=">=3.10",
    entry_points={
          'console_scripts': [
             'my-app=myapp.__main__:main',
          ],
       },
)

Frameworks

Mirroring a repository

Making a mirror of the docker-py package and using it on another machine without internet access.

virtualenv -p $(which python3) pypi-mirror
source pypi-mirror/bin/activate
mkdir data
pip install python-pypi-mirror
pypi-mirror download -d data docker-py
pypi-mirror create -d data/ -m simple

WEB server

Simple HTTP

  • python2.7 -m SimpleHTTPServer 8383
  • python3 -m http.server 8383

HTTPS Python3.12

Generate key and cert here.

import http
from http.server import HTTPServer, BaseHTTPRequestHandler
import ssl

def run():
        server_address = ('127.0.0.1', 5000)
        httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler)

        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        context.load_cert_chain(certfile="cert.pem", keyfile="key.pem")

        httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
        httpd.serve_forever()


if __name__ == "__main__":
    run()

Codificação de terminal

export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"

Ansible em WSL

apt install python-txwinrm python3-winrm -y
pip install "pywinrm>=0.2.2"

Articles

Tools