Developer Blog

Tipps und Tricks für Entwickler und IT-Interessierte

Laravel | Tipps und Tricks | Bootstrap verwenden

Create and Prepare your Laravel Project

Create Laravel App

Installing a fresh Laravel project by running the following steps:

Create a new applaravel new --stack livewire --jet --teams app
In the file .env and change DB Connection to sqliteDB_CONNECTION=sqlite
Create an empty file database/database.sqlite
Start DB Migrationphp artisan migrate
Start Laravelphp artisan serve

Create Page for Bootstrap Demo

Create a file resources/views/using-bootstrap.blade.php with the following content:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel: Using Bootstrap from Local</title>
</head>

<body class="antialiased">
   <main>
      <div class="container py-4">
         <header class="pb-3 mb-4 border-bottom">
            <a href="/" 
               class="d-flex align-items-center text-dark text-decoration-none">
               <title>Bootstrap</title>
               <span class="fs-4">Bootstrap example</span>
            </a>
         </header>

         <div class="p-5 mb-4 bg-light rounded-3">
            <div class="container-fluid py-5">
               <h1 class="display-5 fw-bold">
                  Using Bootstrap in Laravel Projects
               </h1>
               <p class="col-md-8 fs-4">
                  It's very easy to add the Bootstrap Framework 
                  to your Laravel Project.
               </p>
               <button class="btn btn-primary btn-lg" type="button">
                  See how...
               </button>
            </div>
         </div>
      </div>
   </main>
</body>
</html>

Add the link /using-bootstrap to your App by adding this to route/web.php

Route::get('/', function () {
    return view('welcome');
});

Route::get('/using-bootstrap', function () {
    return view('using-bootstrap');
});

If you open http://127.0.0.1:8000/using-bootstrap in the Browser, you the demo page but with no bootstrap styling.

Adding Bootstrap to your Project

You have three possibilities to add Bootstrap into your Larval Project

Methode 1: Adding Bootstrap by a Link to CDN

Using CDN (Content delivery network) is quite easy and simple for beginners. CDN is a network of servers providing the source files for almost every library used in front-end development.

We need the references for bootstrap.min.css and bootstrap.bundle.min.js

You add Bootstrap by inserting the following code snippets in your main Laravel Page.

We will use the file resources/views/using-bootstrap.blade.php

<link            
    href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
    rel="stylesheet"
    integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
    crossorigin="anonymous"
>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
    crossorigin="anonymous">
</script>

The final file looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Boostrap 5</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="alert alert-success mt-5" role="alert">
            Boostrap 5 is working!
        </div>    
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
</body>
</html>

Methode 2: Adding Bootstrap Public Folder

Download Bootstrap 5 file and put the files into the folder app/public/assets/vendor/bootstrap/5.2.0

Add the following code snippets to your Laravel Page:

<link href="{{ asset('assets/vendor/bootstrap/5.2.0/css/bootstrap.min.css') }}" rel="stylesheet">
<script src="{{ asset('assets/vendor/bootstrap/5.2.0/js/bootstrap.min.js') }}"></script>

The final files look like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Boostrap 5</title>
    <link rel="stylesheet" href={{ asset('css/bootstrap.min.css') }}>
</head>
<body>
    <div class="container">
        <div class="alert alert-success mt-5" role="alert">
            Boostrap 5 is working!
        </div>    
    </div>
    <script src="{{ asset('js/bootstrap.min.js') }}"></script>
</body>
</html>

Methode 3: Adding Bootstrap 5 using Laravel Mix

In Laravel, all Frontend Modules are handles with Laravel Mix. This is an elegant wrapper around Webpack, a Package manager for installing and managing node modules.

To use Mix, you need to install NodeJS and NPM.

After this, install all required modules of your starter project

npm install

If you can see node_modules folder, this means npm is working.

Now we need to install bootstrap and the required modules

npm install bootstrap --save-dev 
npm install @popperjs/core --save-dev

You will find the new packages in package.json

    "devDependencies": {
        "@popperjs/core": "^2.11.5",
        "@tailwindcss/forms": "^0.4.0",
        "@tailwindcss/typography": "^0.5.0",
        "alpinejs": "^3.0.6",
        "axios": "^0.25",
        "bootstrap": "^5.1.3",
        "laravel-mix": "^6.0.6",
        "lodash": "^4.17.19",
        "postcss": "^8.1.14",
        "postcss-import": "^14.0.1",
        "tailwindcss": "^3.0.0"
    }

Next, add the following line to resources/css/app.css:

@import "bootstrap";

Add the following line to the file resources/js/bootstrap.js:

window._ = require("lodash");
import "bootstrap";

Run the following command to build the frontend files (css and js)

npm run development

You done. See the result here: http://127.0.0.1:8000/using-bootstrap

Using Bootstrap

With the Bootstrap Framework installed, now we can style our Pages. An overview of what you can do could be found in the Documentation or using the Examples.

We will work with the Examples, so download all examples to the folder resources/views/bootstrap

With the Commandline and PowerShell, you could do this: Change to the folder and download the Archive with the examples

❯ Set-Location resources\views
❯ Invoke-WebRequest https://github.com/twbs/bootstrap/releases/download/v5.2.0-beta1/bootstrap-5.2.0-beta1-examples.zip -O bootstrap.zip

Extract the archive, don’t forget the trailing dot ‘.’

❯ Expand-Archive .\bootstrap.zip .

Rename the created folder

❯ Rename-Item .\bootstrap-5.2.0-beta1-examples\ bootstrap
❯ Remove-Item bootstrap.zip

Now, we have all examples in the folder resources/views/bootstrap and we are ready to play with them:

Modify the album example to use with Laravel

Modify the /using-bootstrap (resources/views/using-bootstrap.blade.php) page

Add a sample text and a link to out Album Page

<div class="p-5 mb-4 bg-light rounded-3">
    <div class="container-fluid py-5">
    ... Keep the original content
    </div>

    <div class="container-fluid py-5">
        <p class="col-md-8 fs-4">
            Just start with an <a href="bootstrap/album">example</a>
        </p>
    </div>
</div>

Modify routes/web.php to include a link to /bootstrap/album

Add the following lines to route/web.php

Route::get('/bootstrap/album', function () {
    return view('bootstrap/album');
});

Modify the Album Page

Rename and move the file resources/views/bootstrap/album/index.html to resources/views/bootstrap/album.blade.php.

Please note: We also changed the folder of the file. All examples’ files will be placed directly under the folder resources/views/bootstrap

You can do this for all files with the following PowerShell Script:

Get-ChildItem . index.html -recurse                        | `



Addon: Script to modify all examples files

Remove-Item _web.php

Remove-Item _links.php
Add-Content _links.php "<div class='list-group w-auto'>"

function Add-Link($header, $link) {

Add-Content _links.php ('<a href="' + $link + '" class="list-group-item list-group-item-action d-flex gap-3 py-3" aria-current="true">')
Add-Content _links.php '<img src="https://github.com/twbs.png" alt="twbs" width="32" height="32" class="rounded-circle flex-shrink-0">'
Add-Content _links.php '<div class="d-flex gap-2 w-100 justify-content-between">'
Add-Content _links.php ('<div><h6 class="mb-0">' + $header + '</h6></div>')
Add-Content _links.php '<p class="mb-0 opacity-75">Another examples></p>'
Add-Content _links.php '</div>'
Add-Content _links.php '<small class="opacity-50 text-nowrap">&nbsp;</small>'
Add-Content _links.php '</a>'

}

 $LINK_OLD_JS="../assets/dist/js/bootstrap.bundle.min.js"
$LINK_OLD_CSS="../assets/dist/css/bootstrap.min.css"
 
 $LINK_NEW_JS="{{ asset('js/app.js')   }}"
$LINK_NEW_CSS="{{ asset('css/app.css') }}"


Get-ChildItem . index.html -recurse                        `
|
|
    (Get-Content $_\index.html)         `
    |
    |
    | Set-Content  $_".blade.php"

    Add-Content _web.php "Route::get('/bootstrap/$_', function () { return view('bootstrap/$_'); });"

    Write-Host "Add links to example $_"
    Add-Link $_ "bootstrap/$_"
}

Add-Content _links.php "</div>"

FAQ

Errors and Problems

Build Modules with npm run dev shows up a warning

To see more information about the warning, add the following to the file webpack.mix.js after the first mix.js( ...

mix.webpackConfig({
    stats: {
        children: true,
    },
});

Then, run npm run dev again.

Angular I18N

Angular | Working with I18N

In this post, you will learn how to get started with Angular I18n using ngx-translate, the internationalization (i18n) library for Angular. We will cover the following topics:

  • setup new angular app
  • install required dependencies
  • add bootstrap as ui framework
  • create app with demo page and translation services

This will be the final result (click to show video). Source code for this post is on GitHub.

Setup new Angular app

➜ ng new app
➜ cd app

Add required modules

➜ npm install @ngx-translate/core @ngx-translate/http-loader rxjs --save

Add Bootstrap as UI framework

We need the libraries for Bootstrap and flag icons. Download the required files into your asset/vendor/bootstrap/5.3.1 folder:

Flags Icons need a CSS file with the corresponding images for the flags, so we use the archive from GitHub.

Download and extract the archive into the folder assets/vendor/flag-icons

Current folder structure

This is our current folder structure:

Setup Application

We choose the following structure for the HTML architecture.

  • index.html contains the required css and js files.
    Also, the <app-root> component, which loads our app
  • app.component.html contains the main structure of every page.
    This includes header, navigation, place for main content and footer
  • The main content is inserted via the <router-outlet>

index.html

We will add the corresponding file in the main index.html in our project.

<!doctype html>
<html lang="en" class="h-100">

<head>
  <meta charset="utf-8">
  <title>I18N</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <link rel="stylesheet" href="/assets/vendor/bootstrap.min.css">
  <link rel="stylesheet" href="/assets/vendor/flag-icons.min.css">

  <link rel="stylesheet" href="/assets/vendor/bootstrap/5.1.3/css/bootstrap.min.css">
  <link rel="stylesheet" href="/assets/vendor/flag-icons/css/flag-icons.min.css">

  <link rel="stylesheet" href="/assets/css/default.css">

</head>

<body class="d-flex flex-column h-100">
  <app-root class="h-100"></app-root>

  <script src="assets/vendor/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
</body>

</html>

app.component.html

We borrow the main structure from the bootstrap example ‘Sticky Footer with Navbar‘ with some changes in the navigation bar.

<header>
    <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <img src="assets/img/logo-angular.png" height="40px" width="auto">
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" 
                data-bs-target="#navbarCollapse"
                aria-controls="navbarCollapse" 
                aria-expanded="false"     
                aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarCollapse">
                <ul class="navbar-nav me-auto mb-2 mb-md-0">
                    <li class="nav-item">
                        <a class="nav-link active" aria-current="page" href="#">Home</a>
                    </li>
                </ul>

                <div class="btn-group dropstart">
                    <button class="btn btn-primary dropdown-toggle" type="button" 
                        id="dropdownFlags"
                        data-bs-toggle="dropdown" aria-expanded="false">
                        <span class="flag-icon flag-icon-{{currentlang}}"></span>
                    </button>
                    <ul class="dropdown-menu">
                        <li *ngFor="let lang of languages" [value]="lang" 
                            (click)="useLanguage(lang)">
                            <a class="dropdown-item"
                                [ngClass]="{'active': currentlang == lang}">
                                <span class="flag-icon flag-icon-{{lang}}"></span>
                                &nbsp;
                                {{lang | uppercase}}
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </nav>
</header>
<main class="flex-shrink-0">
    <div class="container">
        <router-outlet></router-outlet>
    </div>
</main>
<footer class="footer mt-auto py-3 bg-dark">
    <div class="container">
        <span class="text-muted">(C) Ralph Göstenmeier</span>
    </div>
</footer>

app.component.ts

import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

import defaultLanguage from '../assets/i18n/de.json';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
})
export class AppComponent {
    title = 'I18N';

    languages = ['us', 'de', 'fr', 'sp'];
    currentlang = 'us';

    constructor(private translate: TranslateService) {
        this.currentlang = 'de';
        translate.setTranslation(this.currentlang, defaultLanguage);
        translate.setDefaultLang(this.currentlang);
    }

    ngOnInit(): void {}

    useLanguage(language: string): void {
        this.currentlang = language;
        this.translate.use(language.toLowerCase());
    }
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClient, HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

import { HomePageComponent } from './pages/home/component';
import { DemoPageComponent } from './pages/demo/component';

@NgModule({
    declarations: [AppComponent, HomePageComponent, DemoPageComponent],
    imports: [
        BrowserModule,
        AppRoutingModule,
        HttpClientModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: HttpLoaderFactory,
                deps: [HttpClient],
            },
        }),
    ],
    providers: [],
    bootstrap: [AppComponent],
})
export class AppModule {}

// required for AOT compilation
export function HttpLoaderFactory(http: HttpClient): TranslateHttpLoader {
    return new TranslateHttpLoader(http);
}

How the app works

The translation is done with the ngx-translate component.

Translation works with different JSON files (for each language a separate file), containing the required translation for each text to be displayed. Each text is addressed with a name within the JSON file.

So, the base structure of each JSON file is the following:

Translation files

assets/i18n/de.json

{
  "i18n-demo-header": "I18N Demo",
  "header": "I18N Funktionalität in Angular"
}

assets/i18n/us.json

{
  "i18n-demo-header": "I18N Example",
  "header": "I18N Functionality in Angular"
}

These translations could be used in a html file by using the translate pipe:

<h1>{{'header' | translate }}</h1>

More information and examples are here.

Changing the language is done with the help of the TranslateService

Inject your app with the TranslateService (in app.component.ts)

constructor(private translate: TranslateService) {
    translate.setDefaultLang('de');
}

Change Language

useLanguage(language: string): void {
    this.translate.use(language.toLowerCase());
}

Integrate in our UI

To easy switching the language, we have to do a few steps

Add a dropdown menu to our navigation bar.

And switching the language is done by calling useLanguage within each menu item:

<div class="btn-group dropstart">
    <button class="btn btn-primary dropdown-toggle" type="button"
        id="dropdownFlags"
        data-bs-toggle="dropdown" aria-expanded="false"><span
        class="flag-icon flag-icon-{{currentlang}}"></span>
    </button>
    <ul class="dropdown-menu">
        <li *ngFor="let lang of languages" [value]="lang"
            (click)="useLanguage(lang)">
            <a class="dropdown-item" 
                [ngClass]="{'active': currentlang == lang}">
                <span class="flag-icon flag-icon-{{lang}}"></span>
                &nbsp;
                {{lang | uppercase}}
            </a>
        </li>
    </ul>
</div>

Setup a list for all menu items:

<ul class="dropdown-menu">
<li *ngFor="let lang of languages" [value]="lang" (click)="useLanguage(lang)">

Rust | Modern Alternatives of Command-Line Tools

Continue Reading

https://github.com/TaKO8Ki/awesome-alternatives-in-rust

Tools

bat

bat is a cat clone with syntax highlighting and Git integration that works on Windows, MacOS and Linux. It provides syntax highlighting for many file extensions by default.

exa

exa is a modern replacement for ls, the default command-line program in Unix/Linux for listing directory contents. exa supports icons with the --icons flag.

just

A command runner and partial replacement for make

Just create a justfile with the desired commands and your set.

When running with PowerShell, add the following at the start of your justfile:

set windows-shell := ["pwsh.exe", "-NoLogo", "-NoProfile", "-Command"]

fd

fd is a fast and user-friendly alternative to find, the built-in command-line program in Unix/Linux for walking a file hierarchy. fd provides opinionated defaults for the most common use cases. To find a specific file by name, you write fd PATTERN instead of find -iname ‘*PATTERN*’fd is also extremely fast and it comes with a ton of options like ignoring hidden directories, files and patterns from .gitignore by default.

procs

procs is a modern replacement for ps, the default command-line program in Unix/Linux for getting information about processes. It provides convenient, human-readable (and colored) output format by default.

sd

sd is an intuitive find & replace command-line tool, it is an alternative to sed, the built-in command-line program in Unix/Linux for parsing and transforming text (). sd has simpler syntax for replacing all occurrences and it uses the convenient regex syntax that you already know from JavaScript and Python. sd is also 2x-11x faster than sed.

sed is a programmable text editor, with search and replace being a common use case. In that light, sd is more like tr, but on steroids. (thanks /u/oleid for the suggestion).

dust

dust is a more intuitive version of du, the built-in command-line program in Unix/Linux for displaying disk usage statistics. By default dust sorts the directories by size.

startship

The minimal, blazing-fast, and infinitely customizable prompt for any shell.

ripgrep

ripgrep is an extremely fast alternative to grep, the built-in command-line program in Unix/Linux for searching files by pattern. ripgrep is a line-oriented search tool that recursively searches your current directory for a regex pattern. By default, ripgrep respects .gitignore and automatically skips hidden files, directories and binary files.

toeki

tokei is a program that displays statistics about your code. It shows the number of files, total lines within those files and code, comments, and blanks grouped by language.

hyperfine

hyperfine is a command-line benchmarking tool. Among many features, it provides statistical analysis across multiple runs, support for arbitrary shell commands, constant feedback about the benchmark progress and current estimates and more.

ytop

ytop is an alternative to top, the built-in command-line program in Unix/Linux for displaying information about processes.

tealdeer

tealdeer is a very fast implementation of tldr, a command-line program for displaying simplified, example based and community-driven man pages.

bandwhich

bandwhich is a CLI utility for displaying current network utilization by process, connection and remote IP or hostname.

grex

grex is a command-line tool and library for generating regular expressions from user-provided test cases.

rmesg

rmesg is a dmesg implementation in Rust (and available as a library for Rust programs to consume kernel message logs.)

zoxide

zoxide is a blazing fast autojumper, intended to completely replace the cd command. It allows you to change directories without typing out the entire path name.

delta

delta is a viewer for git and diff output. It allows you to make extensive changes to the layout and styling of diffs, as well as allowing you to stay arbitrarily close to the default git/diff output.

tp-note

Tp-Note is a template tool that enhances the clipboard with a save and edit as a note file function. After creating a new note file, Tp-Note launches the user’s favorite file editor (for editing) and web browser (for viewing).

nushell

nushell is a new type of shell, written in Rust. Its goal is to create a modern shell alternative that’s still based on the Unix philosophy but adapted to the current era. It supports piping and filtering in a way similar to awk and sed with a column view so that you can combine operations like in SQL. (thanks /u/matu3ba for the suggestion).


Django | How To – Templates konfigurieren

Allgemein / Vorbereitung

Um in einem Django-Projekt mit mehreren Anwendungen die HTML-Templates zu konfigurieren sind mehrere Schritte notwendig.

Ausgangsbasis ist die nachfolgende Verzeichnisstruktur (ein Projekt mit 2 Anwendungen).

Basisprojekt einrichten

➜ pipenv --python 3.10
➜ pipenv shell
➜ pip install django
➜ djangop-admin startproject project
➜ cd project
➜ mkdir apps
➜ mkdir apps\core
➜ django-admin startapp core apps\core
➜ mkdir apps\frontend
➜ django-admin startapp frontend apps\frontend

Dies ergibt die folgende Verzeichnisstruktur:

Hinweis: der Befehl startproject erstellt einen Ordner project, indem er einen weiteren Ordner project erstellt. Der erste Ordner dient dazu, sowohl das Django-Projekt, als auch die erstellten Anwendungen an einer gemeinsame Stelle zu speichern.

Der zweite Ordner project ist das Django-Projekt, in dem sich alle für das Projekt notwendigen Dateien befinden.

Wird in den nachfolgenden Beschreibungen vom dem Ordner project gesprochen, so ist immer der zweite gemeint (project/project)

➜ python manage.py migrate
➜ python manage.py createsuperuser --email admin@localhost --username admin
Password:
Password (again):
Superuser created successfully.

Anwendungen hinzufügen

Im nächsten Schritt werden die beiden erstellten Anwendungen (Core und Frontend) dem Django-Projekt hinzugefügt. Da sie in einem Unterverzeichnis (apps) liegen, muss ihre Konfiguration angepasst werden.

In dere Datei apps.py der jeweiligen Anwendung (apps/core/apps.py und apps/frontend/apps.py) wirr der Name angepasst:

Hinweis: Ohne diese Anpassung würde beim Start des Servers eine Fehlermeldung angezeigt

django.core.exceptions.ImproperlyConfigured: Cannot import 'frontend'. Check that 'apps.frontend.apps.FrontendConfig.name' is correct.

Im Anschluss daran werden die beiden Anwendungen dem Projekt hinzugefügt. Dies erfolgt in der Datei project/settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'apps.core',
    'apps.frontend'
]

Einfache Views erstellen

Ein Template ist die Basis eines Views.

Daher richten wir für jede Anwendung einen einfachen View ein: in apps/core/views.py und apps/frontend/views.py:

from django.shortcuts import render
from django.views import generic

class IndexView(generic.TemplateView):
    """
    IndexView:
    """
    module = 'indexView'
    template_name = 'core/index.html'

URLs für die Anwendungen hinzufügen

Im letzten Vorbereitungsschritt konfigurieren wir die URLs für unsere Anwendungen bzw die beiden eingerichteten Views:

from django.contrib import admin
from django.urls import path

import apps.core.views as core
import apps.frontend.views as frontend

urlpatterns = [
    path('admin/', admin.site.urls),
    path('frontend/', frontend.IndexView.as_view(), name='index'),
    path('core', core.IndexView.as_view(), name='index'),

]

Als Ergebnis sollten wir bei beiden URLs einen Fehler sehen.

Dies was zu erwarten, da wir die notwendigen Templates ja erst jetzt einrichten werden:

Template hinzufügen

Erstellen eines Templates für die Anwendung core: apps/core/templates/core/index.html

Der Verzeichnispfad des Templates setzt sich auch mehreren Teilen zusammen

apps/coreDas Startverzeichnis der Anwendung
templatesDer Default-Name des Verzeichnisses, in dem Django nach Templates sucht
coreDer Namespace als Unterscheidung, wenn es Templates mit gleichem Namen gibt
index.htmlDer Name des Templates

Erstellen Sie die Daten apps/core/templates/core/index.html und öffnen Sie dann den Browser:

http://localhost:8000/core

Zum Vergleich öffen wir die URL für unsere zweite Anwendung: frontend

http://localhost:8000/frontend

Im unteren Teil der Fehlermeldung findet sich aber eine hilfreiche Information:

Als erstes wir uns mitgeteilt, das ein gewünschtes Template in der nachfolgenden Reihenfolge gesucht wird. Es werden als (wir oben bereits erwähnt) mehrere Verzeichnisse durchsucht, um ein passendes Template zu finden.

Template-loader postmortem
Django tried loading these templates, in this order:

Using engine django:

Als erstes werden Verzeichnisse der Django-Installation durchsucht. Hierunter liegen z. B. die Templates für die Administration oder die Anmeldung.

django.template.loaders.app_directories.Loader: 
...\lib\site-packages\django\contrib\admin\templates\frontend\index.html (Source does not exist)

django.template.loaders.app_directories.Loader: 
...\lib\site-packages\django\contrib\auth\templates\frontend\index.html (Source does not exist)

Im Anschluss werden dann die Verzeichnisse unserer Anwendungen durchsucht.

django.template.loaders.app_directories.Loader: ...\project\apps\core\templates\frontend\index.html (Source does not exist)

django.template.loaders.app_directories.Loader: ...\project\apps\frontend\templates\frontend\index.html (Source does not exist)

Um nun ein gewünschtes Template zu finden, werden zwei Informationen benötigt:

  • der Name des Template
  • das Verzeichnis

Name des Templates

Der Name des Templates wird im View angegeben: apps/core/views.py:

class IndexView(generic.TemplateView):
    module = 'indexView'
    template_name = 'core/index.html'

Verzeichnis

Das Verzeichnis selbst wird über die Suchreihenfolge der zu verwendenden Template-Verzeichnisse ermittelt. Das erste Verzeichnis, dass das gewünschte Template beinhaltet, wird verwendet.

Ermitteln des Verzeichnisses

Im Falle unserer Anwendung frontend werden die nachfolgenden Verzeichnisse durchsucht, ob sie das Template core/index.html beinhalten:

UmgebungVerzeichnisTemplate gefunden
DJANGOlib\site-packages\django\contrib\admin\templates
DJANGOlib\site-packages\django\contrib\auth\templates
PROJEKTproject\apps\core\templatescore/index.html
PROJEKTproject\apps\frontend\templates

Template hinzufügen

Erstellen eines Templates für die Anwendung frontend: apps/frontend/templates/frontend/index.html

Weiteres Beispiel: Suchen des passenden Templates

Richten sie einen Neuen View in der Anwendung frontend ein: apps/frontend/views.py

class BaseView(generic.TemplateView):
    module = 'baseView'
    template_name = 'base.html' 

Erstellen Sie eine URL für diesen View in project/urls.py

urlpatterns = [
    path('admin/',      admin.site.urls),
    path('core',        core.IndexView.as_view(),      name='index'),
    path('frontend/',   frontend.IndexView.as_view(),  name='index'),
    path('base/',       frontend.BaseView.as_view(),   name='base'),
]

Öffnen Sie den Browser um diese URL anzuzeigen;

http://localhost:8000/base

Wie zu erwarten war, wird das Template nicht gefunden:

In keinem der bekannten Verzeichnisse gibt es ein Template base.html.

Gemeinsame Templates für alle Anwendungen

Um Templates einzurichten, die von mehreren Anwendungen verwendet werden, empfiehlt es sich, ein Verzeichnis templates auf der gleichen Ebene, wie die Anwendungen, einzurichten

In der Datei project/settings.py wird dieses Verzeichnis dem Django-Projekt hinzugefügt.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        ....

Öffnen Sie den Browser um diese URL anzuzeigen;

http://localhost:8000/base

Das zusätzliche Verzeichnis wird nun auch durchsucht:

Template-loader postmortem
Django tried loading these templates, in this order:

Using engine django:
django.template.loaders.filesystem.Loader: ...\project\templates\base.html (Source does not exist)
django.template.loaders.app_directories.Loader: ...\.venv\lib\site-packages\django\contrib\admin\templates\base.html (Source does not exist)
django.template.loaders.app_directories.Loader: ...\.venv\lib\site-packages\django\contrib\auth\templates\base.html (Source does not exist)
django.template.loaders.app_directories.Loader: ...\project\apps\core\templates\base.html (Source does not exist)
django.template.loaders.app_directories.Loader: ...\project\apps\frontend\templates\base.html (Source does not exist)

Erstellen Sie nun in diesem Verzeichnis (templates) das Template base.html

Öffnen Sie den Browser um diese URL anzuzeigen;

http://localhost:8000/base

SpringBoot - Cookbook

Spring Boot | Cookbook

Introduction

Tipps and Tricks

Change App Port Number

Add line to file src/main/resources/application.properties

server.port=9010

Rest Api

Get JSON Data from a remote Rest Server

final RestTemplate restTemplate = new RestTemplate();
final String response = restTemplate.getForObject("https://httpbin.org/ip", String.class);

System.out.println(response);

Python | Virtuelle Umgebung mit pipenv

Pipenv: Python-Entwicklungsworkflow für Menschen

Pipenv ist ein Tool, das darauf abzielt, das Beste aller Verpackungswelten (Bündel, Composer, NPM, Cargo, Garn usw.) in die Python-Welt zu bringen. Windows ist in unserer Welt ein erstklassiger Bürger.

Es erstellt und verwaltet automatisch eine virtuelle Umgebung für Ihre Projekte und fügt Pakete zu Ihrer Pipfile hinzu/entfernt sie, während Sie Pakete installieren/deinstallieren. Es generiert auch das immer wichtige Pipfile.lock, das verwendet wird, um deterministische Builds zu erstellen.

Die Probleme, die Pipenv zu lösen versucht, sind vielschichtig:

  • Sie müssen pip und virtualenv nicht mehr separat verwenden. Sie arbeiten zusammen.
  • Die Verwaltung einer Requirements.txt-Datei kann problematisch sein, daher verwendet Pipenv Pipfile und Pipfile.lock, um abstrakte Abhängigkeitsdeklarationen von der zuletzt getesteten Kombination zu trennen.
  • Hashes werden immer und überall verwendet. Sicherheit. Sicherheitslücken automatisch aufdecken.
  • Empfehlen Sie dringend die Verwendung der neuesten Versionen von Abhängigkeiten, um Sicherheitsrisiken durch veraltete Komponenten zu minimieren.
  • Geben Sie Einblick in Ihr Abhängigkeitsdiagramm (z. B. pipenv graph).
  • Optimieren Sie den Entwicklungsworkflow durch Laden von .env-Dateien.

Installation

Installieren Sie pipenv über das Kommando pip

pip install pipenv

Beispiele

Virtuelle Umgebungmit Python 3.9 erstellen

E:\> pipenv --python 3.9

E:\> type .\Pipfile
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]

[dev-packages]

[requires]
python_version = "3.9"

Verzeichnisse der virtuellen Umgebung anzeigen

E:\> pipenv --where
E:\
E:\> pipenv --venv
C:\Users\workshop.virtualenvs\pipenv-python39-FzfGexFj
E:\> get-command python

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Application     python.exe                                         3.9.6150.… C:\Users\workshop\.virtualenvs\pipenv-python39-FzfGexFj\Scripts\python.exe

Die virtuelle Umgebung wird im Verzeichnis des Benutzer erstellt, im Unterordner .virtualenv.

Sollte ihr Projekt die Anforderung haben, das die virtuelle Umgebung im Projektordner erstellt wird, dann gibt es hierfür zwei Möglichkeiten:

  • Erstellen Sie im Projektordner einen Unterordner .venv
  • Verwenden Sie die Umgebungsvariable PIPENV_VENV_IN_PROJECT.
 E:\> $ENV:PIPENV_VENV_IN_PROJECT=1 && pipenv --python 3.9
Creating a virtualenv for this project...
Pipfile: E:\Pipfile
Using D:/Python/3.9.6/python.exe (3.9.6) to create virtualenv...
[=== ] Creating virtual environment...created virtual environment CPython3.9.6.final.0-64 in 262969ms
  creator CPython3Windows(dest=E:\.venv, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\rg\AppData\Local\pypa\virtualenv)
    added seed packages: pip==21.1.3, setuptools==57.1.0, wheel==0.36.2
  activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

Successfully created virtual environment!

Um für alle zu Erstellenden virtuellen Umgebungen das Verzeichnis anzupassen, kann die Umgebungsvariable WORKON_HOME verwendet werden.

Wechseln in die virtuelle Umgebung

E:\> pipenv shell
Launching subshell in virtual environment...
PowerShell 7.2.0-preview.6
Copyright (c) Microsoft Corporation.

Virtuelle Umgebung verlassen

Verlassen Sie die virtuelle Umgebung einfach, indem sie die neu gestartete Subshell beenden

E:\> exit

Prüfen, ob man in einer virtuellen Umgebung arbeitet

Prüfen Sie, welches Python Version verwendet wird

E:\> Get-Command python

CommandType     Name                Version    Source
-----------     ----                -------    ------
Application     python.exe          3.9.6150.… E:\.venv\Scripts\python.exe

Prüfen sie, welche PIP Version verwendet wird:

E:\> pip -V
pip 21.1.3 from E:\.venv\lib\site-packages\pip (python 3.9)

Prüfen Sie die Umgebungsvariable PIPENV_ACTIVE

E:\>$ENV:PIPENV_ACTIVE
1

Löschen einer virtuellen Umgebung im aktuellen Verzeichnis

E:\> pipenv --rm
Removing virtualenv (C:\Users\workshop\.virtualenvs\pipenv-python39-FzfGexFj)...

Installieren eines Paketes

E:\> pipenv install fastapi
Installing fastapi...
Adding fastapi to Pipfile's [packages]...
Installation Succeeded
Pipfile.lock (16c839) out of date, updating to (4f56a0)...
Locking [dev-packages] dependencies...
Locking [packages] dependencies...
           Building requirements...
Resolving dependencies...
Success!
Updated Pipfile.lock (4f56a0)!
Installing dependencies from Pipfile.lock (4f56a0)...
  ================================ 0/0 - 00:00:00
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.

Der neue Inhalt der Konfigurationsdatei Pipfile:

E:\> type Pipfile
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]
fastapi = "*"

[dev-packages]

[requires]
python_version = "3.9"

Install all dependencies for a project (including dev)

E:\> pipenv install --dev
Pipfile.lock not found, creating...
Locking [dev-packages] dependencies...
Locking [packages] dependencies...
Updated Pipfile.lock (16c839)!
Installing dependencies from Pipfile.lock (16c839)...
  ================================ 0/0 - 00:00:00
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.

Erstellen einer Lockdatei Pipenv.lock mit den aktuell installierten Releases

E:\> pipenv lock --pre
Locking [dev-packages] dependencies...
Locking [packages] dependencies...
Updated Pipfile.lock (16c839)!

Show a graph of your installed dependencies:

E:\> pipenv graph
fastapi==0.68.0
  - pydantic [required: >=1.6.2,<2.0.0,!=1.8.1,!=1.8,!=1.7.3,!=1.7.2,!=1.7.1,!=1.7, installed: 1.8.2]
    - typing-extensions [required: >=3.7.4.3, installed: 3.10.0.0]
  - starlette [required: ==0.14.2, installed: 0.14.2]

Oder mit dem Ausgabeformat JSON

 E:\> pipenv graph --json-tree

Überprüfen der installierten Abhängigkeiten auf Sicherheitslücken

E:\> pipenv check
Checking PEP 508 requirements...
Passed!
Checking installed package safety...
All good!

Ausführen eines Kommandos in der virtuellen Umgebung

E:\> pipenv run pip -V
pip 21.1.3 from C:\Users\rg.virtualenvs\app-pipenv-tgP0nh4t\lib\site-packages\pip (python 3.9)

Ausführen eines Pip-Kommandos

E:\> pipenv run pip freeze
fastapi==0.68.0
pydantic==1.8.2
starlette==0.14.2
typing-extensions==3.10.0.0

Kommandozeile

Optionen

--where            Output project home information.
--venv             Output virtualenv information.
--py               Output Python interpreter information.
--envs             Output Environment Variable options.
--rm               Remove the virtualenv.
--bare             Minimal output.
--completion       Output completion (to be executed by the shell).

--man              Display manpage.
--support          Output diagnostic information for use in GitHub issues.

--site-packages / --no-site-packages
                   Enable site-packages for the virtualenv.
                   env var: PIPENV_SITE_PACKAGES]

--python TEXT      Specify which version of Python virtualenv should use.

--three / --two    Use Python 3/2 when creating virtualenv.
--clear            Clears caches (pipenv, pip, and pip-tools).
                   env var: PIPENV_CLEAR]

-v, --verbose      Verbose mode.
--pypi-mirror TEXT Specify a PyPI mirror.
--version          Show the version and exit.
-h, --help         Show this message and exit.

Rust | Cookbook

Fehler und deren Behebung

Problem

cargo build
error: no default toolchain configured

Lösung

Ermitteln, welche Toolchains installiert sind

rustup toolchain list

Toolchain installieren

rustup install stable
rustup default  stable

FastAPI | Cookbook

Einleitung

Anforderungen

CORS

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)

Starlette

Templates

Template erstellen

...

    
...

Template verwenden



    ...
    <main>....</main>




Links

CSS

<link href="{{ url_for('static', path='/css/bootstrap.min.css') }}"
      rel="stylesheet"
>

JavaScript

<script src="{{ url_for('static', path='/js/jquery.min.js') }}"></script>

Laravel | Erstellen einer Beispielanwendung unter WSL

Voraussetzung

Voraussetzung für die Verwendung von Laravel ist eine lauffähige Entwicklungsumgebung.

Der Aufbau einer solchen Umgebung wird hier beschrieben.

Installation über WSL

WSL starten

WSL ist das Windows Subsystem for Linux 2 (WSL2)

> wsl
/mnt/d/Websites
$

Installation einer Beispielanwendung

curl -s https://laravel.build/example-app | bash

Individuelle Anpassung

Beim Aufruf kann die zu verwendende Dienste mit angegeben werden. Mögliche Werte sind:

mysql, pgsql, mariadb, redis, memcached, meilisearch, selenium, and mailhog

Die Standardwerte sind:

mysql, redis, meilisearch, mailhog und selenium
curl -s "https://laravel.build/example-app?with=mysql,redis" | bash

Installation mit Standardwerten

curl -s https://laravel.build/example-app | bash

Und die letzten Schritte

Starten der Anwendung

$ cd example-app
$ ./vendor/bin/sail up

Zugriff auf die Anwendung über http://localhost