Skip to content

Python3 - Struktur eines Projektes

Python3
  • Ich hatte mich gestern mal versucht ein wenig einzulesen, wie man ein Python Projekt strukturiert. Dabei habe ich wieder viele interessante Dingen gelernt.

    Eine Sache davon ist das hier

    requirements.txt erzeugen

    (restic_ui-RwXjz-0W) frank@frank-MS-7C37:~/restic_ui$ pipenv lock -r > requirements.txt
    

    Inhalt aktuell

    cffi==1.15.0
    cryptography==36.0.1
    pycparser==2.21
    pyqt5-qt5==5.15.2
    pyqt5-sip==12.9.0
    pyqt5==5.15.6
    

    Meine aktuelle Struktur sieht so aus

    frank@frank-MS-7C37:~/Restic_UI_Produktiv/restic-ui-public$ tree
    .
    ├── icons
    │   ├── add.svg
    │   ├── delete.svg
    │   ├── document-save.svg
    │   ├── edit.svg
    │   ├── exit.svg
    │   ├── folder-open.svg
    │   ├── help-info.svg
    │   ├── media-playback-start.svg
    │   ├── reload.svg
    │   ├── Restic_Logo.png
    │   ├── Restic_UI_main_screen.png
    │   └── settings.svg
    ├── LICENSE
    ├── log.txt
    ├── Pipfile
    ├── Pipfile.lock
    ├── README.md
    ├── requirements.txt
    ├── setup.py
    └── src
        ├── create.py
        ├── crypt.py
        ├── functions.py
        ├── __init__.py
        ├── __pycache__
        │   ├── crypt.cpython-38.pyc
        │   ├── functions.cpython-38.pyc
        │   ├── settings.cpython-38.pyc
        │   └── waitingspinnerwidget.cpython-38.pyc
        ├── restic_ui.py
        ├── settings.py
        └── waitingspinnerwidget.py
    
    3 directories, 30 files
    

    Die Ansicht bekommt man mit

    apt install tree
    

    Quellen

  • 0 Stimmen
    5 Beiträge
    128 Aufrufe
    FrankMF

    Hab ChatGPT nochmal nach der Installation auf einem Production Server befragt.

    ChatGPT

    Certainly! Here's a short example of the steps you can follow to deploy a Flask application on a production server using Nginx and Gunicorn:

    Prepare your server:

    Set up a server (e.g., using a cloud provider like AWS, DigitalOcean, or a dedicated server) and ensure it has a clean, up-to-date installation of a Linux distribution (e.g., Ubuntu or CentOS).

    Install required software:

    Install necessary software packages on your server. You'll need Python, pip (Python package manager), Nginx, and Gunicorn. You can use your distribution's package manager (e.g., apt for Ubuntu or yum for CentOS) to install these dependencies.

    Deploy your Flask application:

    Copy your Flask application code and any required dependencies to your server.

    Set up a virtual environment (optional but recommended):

    Create a virtual environment for your Flask application to isolate its dependencies. You can use venv or virtualenv for this purpose.

    Install Flask and any required Python packages within your virtual environment:

    pip install flask

    Test your Flask application:

    Ensure your Flask application runs correctly within your server's virtual environment.

    Configure Gunicorn:

    Create a Gunicorn configuration file (e.g., gunicorn_config.py) to specify the settings for running your Flask application. Here's a simple example: workers = 4 # Number of Gunicorn worker processes bind = '0.0.0.0:8000' # The address and port Gunicorn should listen on

    Start Gunicorn:

    Start Gunicorn with your Flask application: gunicorn -c gunicorn_config.py your_app:app

    Configure Nginx:

    Create an Nginx server block (often located in /etc/nginx/sites-available) to define how Nginx should handle incoming requests. Here's a simplified example: server { listen 80; server_name your_domain.com www.your_domain.com; location / { proxy_pass http://127.0.0.1:8000; # Pass requests to Gunicorn proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }

    Enable the Nginx server block and restart Nginx:

    sudo ln -s /etc/nginx/sites-available/your_config /etc/nginx/sites-enabled/ sudo nginx -t # Test Nginx configuration sudo systemctl restart nginx

    Configure your DNS:

    Point your domain name to your server's IP address.

    Secure your server (optional but recommended):

    Set up SSL/TLS certificates for your domain to enable HTTPS. You can use Let's Encrypt for free SSL certificates.

    Monitor your application:

    Set up monitoring tools and logs to keep track of your application's performance and troubleshoot any issues.

    These are the basic steps to deploy a Flask application on a production server with Nginx and Gunicorn. Please note that this is a simplified example, and there are many additional considerations, such as database configuration, security, and optimization, depending on your specific application and requirements. It's also important to keep your server and software up to date and follow security best practices to ensure the stability and security of your production environment.

    Das werde ich doch mal ausprobieren 😎

  • Python3 - HTML Text ausgeben

    Python3
    1
    0 Stimmen
    1 Beiträge
    120 Aufrufe
    Niemand hat geantwortet
  • Python3 - subprocess.run

    Python3
    2
    0 Stimmen
    2 Beiträge
    176 Aufrufe
    FrankMF

    Ich möchte das Thema noch mal ausgraben. Bin beim Recherchieren über diese Links gestolpert, die mein Interesse geweckt haben.

    Link Preview Image Python Pipes to Avoid Shells — OpenStack Security Advisories 0.0.1.dev266 documentation

    favicon

    (security.openstack.org)

    B603: subprocess_without_shell_equals_true — Bandit documentation

    favicon

    (bandit.readthedocs.io)

    Da ich aktuell nur eine Desktop Anwendung entwickle, ist das Thema Sicherheit nicht ganz so wichtig, weil wer hackt sich schon selber!? Aber, da man ja nie weiß, wie so ein Tool evt. mal benutzt wird, sollte man von Anfang an auf ein paar Dinge achten.

    Ok, schauen wir uns das mal genauer an.

    Link 1 - shell=True

    Ich kopiere mal das Beispiel aus dem Link.

    def count_lines(website): return subprocess.check_output('curl %s | wc -l' % website, shell=True)

    Ok, das Problem ist

    shell=True

    Ein Beispiel aus meinem Projekt

    result = subprocess.run(['restic', '-r', backup_data[row].repository, 'stats'], input=pass_word.pw[0], capture_output=True, text=True)

    Gesetzt wird der in meinem Beispiel nicht. Besuchen wir mal die Webseite vom subprocess.run

    https://docs.python.org/3/library/subprocess.html?highlight=subprocess run#subprocess.run

    Wenn ich das jetzt richtig verstehe,

    subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)

    dann ist standardmäßig

    shell=False

    gesetzt. Damit ist das in meinem Projekt kein Problem.

    Link 2 - B603: subprocess_without_shell_equals_true

    Ein Tool auf gitlab.com wirft Security Warnings aus, dabei war diese. Schauen wir mal, was uns das sagen möchte.

    Python possesses many mechanisms to invoke an external executable. However, doing so may present a security issue if appropriate care is not taken to sanitize any user provided or variable input.

    Ok, es geht also um die Prüfung von Eingaben bzw. Variablen. Der Merksatz "Keine Benutzereingabe wird ungeprüft übernommen!" ist doch mit das Wichtigste, wenn man irgendwas programmiert. Nochmal mein Beispiel von oben.

    result = subprocess.run(['restic', '-r', backup_data[row].repository, 'stats'], input=pass_word.pw[0], capture_output=True, text=True)

    Ich übergebe dem Prozess einige Eingaben / Variablen.

    backup_data[row].repository pass_word.pw[0]

    Lesen wir wieder ein wenig in der Dokumentation von subprocess.run

    args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

    Das Wichtigste in Kürze Providing a sequence of arguments is generally preferred

    Der Aufruf von subprocess.run erwartet als erste Übergabe args

    subprocess.run(args, *, ....

    Mein Beispiel

    result = subprocess.run(['restic', '-r', backup_data[row].repository, 'stats'], ....

    Das zwischen den eckigen Klammern ist args. Laut der Anleitung ist es empfohlen, das als ein Argument zu übergeben, also so. Somit ist dafür gesorgt, das das Modul die Argumente selbst ein wenig "überwacht".

    as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names).

    Somit hätten man schon mal was für sie "Sicherheit" getan.

    args = ['restic', '-r', backup_data[row].repository, 'stats'] result = subprocess.run(args, ....

    Man sollte trotzdem auf diese beiden Variablen

    * backup_data[row].repository * pass_word.pw[0]

    ein Auge behalten. Ich denke, das habe ich in meinem Projekt eingehalten, indem ich Pfadangabe mit den Systemwerkzeugen auswählbar mache, keine Texteingaben! Passwörter und andere Bezeichnung werden mit regex auf korrekte Eingaben geprüft usw.

    Fazit

    Wieder viel gelernt und ich denke, es passt so weit alles. Bei der ganzen Spielerei, dann noch entdeckt, das ich im Code dieses Argument drin hatte.

    check=False

    Das ist aber Standard, somit kann das weg. Habe das im kompletten Projekt dann entfernt und mir fällt gerade auf, da der Code immer gleich ist, muss das jetzt eigentlich alles in eine Funktion 😉 Mal auf die ToDo-Liste drauf schreiben.

  • Python3 - String-Operatoren

    Python3
    1
    0 Stimmen
    1 Beiträge
    134 Aufrufe
    Niemand hat geantwortet
  • Python3 - virtuelle Entwicklungsumgebung

    Angeheftet Python3
    3
    0 Stimmen
    3 Beiträge
    301 Aufrufe
    FrankMF

    Nach Systemwechsel erneut Probleme. Hier noch mal aufgelistet.

    Aufpassen, das kein venv Ordner vorhanden ist! Neu anlegen!

    python3 -m venv venv

    Dann meckert mein Linux Mint Cinnamon

    The virtual environment was not created successfully because ensurepip is not available. On Debian/Ubuntu systems, you need to install the python3-venv package using the following command. apt install python3.8-venv You may need to use sudo with that command. After installing the python3-venv package, recreate your virtual environment. Failing command: ['/home/frank/Restic_UI_Produktiv/restic-ui-public/venv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']

    Ok, das ist einfach 😉

    apt install python3.8-venv python3 -m venv venv

    Danach aktivieren

    source venv/bin/activate Installation von PyQt5 (venv) frank@frank-MS-7C37:~/Restic_UI_Produktiv/restic-ui-public$ pip3 install PyQt5 Collecting PyQt5 Downloading PyQt5-5.15.4-cp36.cp37.cp38.cp39-abi3-manylinux2014_x86_64.whl (8.3 MB) |████████████████████████████████| 8.3 MB 1.7 MB/s Collecting PyQt5-Qt5>=5.15 Downloading PyQt5_Qt5-5.15.2-py3-none-manylinux2014_x86_64.whl (59.9 MB) |████████████████████████████████| 59.9 MB 18.3 MB/s Collecting PyQt5-sip<13,>=12.8 Downloading PyQt5_sip-12.9.0-cp38-cp38-manylinux1_x86_64.whl (332 kB) |████████████████████████████████| 332 kB 46.1 MB/s Installing collected packages: PyQt5-Qt5, PyQt5-sip, PyQt5 Successfully installed PyQt5-5.15.4 PyQt5-Qt5-5.15.2 PyQt5-sip-12.9.0

    Danach meckert er über ein fehlendes Modul requests

    (venv) frank@frank-MS-7C37:~/Restic_UI_Produktiv/restic-ui-public$ python3 restic_ui.py Traceback (most recent call last): File "restic_ui.py", line 41, in <module> from functions import ( File "/home/frank/Restic_UI_Produktiv/restic-ui-public/functions.py", line 19, in <module> import requests as req ModuleNotFoundError: No module named 'requests' Installation requests (venv) frank@frank-MS-7C37:~/Restic_UI_Produktiv/restic-ui-public$ pip3 install requests Collecting requests Downloading requests-2.25.1-py2.py3-none-any.whl (61 kB) |████████████████████████████████| 61 kB 802 kB/s Collecting chardet<5,>=3.0.2 Downloading chardet-4.0.0-py2.py3-none-any.whl (178 kB) |████████████████████████████████| 178 kB 2.7 MB/s Collecting certifi>=2017.4.17 Downloading certifi-2021.5.30-py2.py3-none-any.whl (145 kB) |████████████████████████████████| 145 kB 14.0 MB/s Collecting idna<3,>=2.5 Downloading idna-2.10-py2.py3-none-any.whl (58 kB) |████████████████████████████████| 58 kB 9.4 MB/s Collecting urllib3<1.27,>=1.21.1 Downloading urllib3-1.26.6-py2.py3-none-any.whl (138 kB) |████████████████████████████████| 138 kB 11.5 MB/s Installing collected packages: chardet, certifi, idna, urllib3, requests Successfully installed certifi-2021.5.30 chardet-4.0.0 idna-2.10 requests-2.25.1 urllib3-1.26.6

    Und schwupps, geht mein Tool wieder 🙂

    4968ce42-7c66-4c8a-a2ad-424b9a529d87-grafik.png

  • Python3 - Globale Variablen

    Python3
    1
    0 Stimmen
    1 Beiträge
    128 Aufrufe
    Niemand hat geantwortet
  • Python3 - RegEx für ein LineEdit

    Python3
    2
    0 Stimmen
    2 Beiträge
    153 Aufrufe
    FrankMF

    Gut, Menschen die mich kennen, wissen das IPv6 nicht so mein Spezialgebiet ist. Es hilft aber nichts, auch damit muss man sich beschäftigen 🙂

    Es war etwas schwierig was Passendes zu finden, aber ich denke das hier ist ganz gut. Ob es alle Möglichkeiten bei IPv6 beinhaltet, weiß ich nicht zu 100%.

    Hier eine Seite, wo ich was Passendes gefunden habe.
    https://ihateregex.io/expr/ipv6/

    Code # regex für IPv6 reg_ex = QRegExp('^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$') input_validator = QRegExpValidator(reg_ex, self.lineedit2_ipv6) self.lineedit2_ipv6.setValidator(input_validator)

    Ein paar Test von mir ergaben, das es so aussieht als wenn es funktioniert 🙂

  • Python und GUI

    Verschoben Python3
    1
    0 Stimmen
    1 Beiträge
    155 Aufrufe
    Niemand hat geantwortet