Quantcast
Channel: Planet Python
Viewing all 22411 articles
Browse latest View live

Continuum Analytics Blog: How Machine Learning Will Generate up to $2 Trillion in Value for the Manufacturing Industry


Catalin George Festila: Python 3.7.5 : About PEP 3107.

$
0
0
The PEP 3107 introduces a syntax for adding arbitrary metadata annotations to Python functions. The function annotations refer to syntax parameters with an expression. def my_function(x: expression, y: expression = 5): ... For example: >>> def show(myvar:np.float64): ... print(type(myvar)) ... print(myvar) ... >>> show(1.1) 1.1 >>> def files(filename: str, dot='.') -> list: ...

Catalin George Festila: Python 3.7.5 : About PEP 8.

$
0
0
Today is December 5, 2019, and this is the reason I wrote about PEP 8. The official webpage can be found at this webpage. PEP 8 recommends using 4 spaces to show indentation and tabs should only be used to maintain consistency in the code. The Python Library is conservative and 79 characters are the maximum required line limit as suggested by PEP 8. The main goal is to avoid line wrapping.

Davy Wybiral: Interactive (Touch) Musical Christmas Tree

$
0
0
In this video I should how to build a capacitive touch Christmas tree that allows you to play music just by touching the ornaments. All it takes is a little bit of Python code, a Raspberry Pi, and a Bare Conductive Pi Cap.

Get ready to rock around the Christmas tree!



Andre Roberge: Significant changes for some error messages in Python 3.8

$
0
0
As I work on including more exceptions in Friendly-traceback, I am mostly pleasantly surprised by generally more precise error messages.  For example, in Python 3.7, the following

__debug__ = 1

would yield "SyntaxError: assignment to keyword" which likely would baffle almost everyone looking up the list of Python keywords.   In Python 3.8, that message has been replaced by the more precise: "SyntaxError: cannot assign to __debug__". Much better, in my opinion, even though one may be surprised to learn about this constant.

However, today as I was working on adding another case, I came accross the following:



This change is ... unexpected.  And the "helpful hint", is not so helpful in this case.  However, I can guess as to how it came about.  It will be a challenge to provide a "friendly" explanation that does not lead the users looking for an incorrect solution to their problem.

Edit: Based on my own (limited) experience working on Friendly-traceback, I do realize that trying to provide helpful hints to assist programmers in fixing code that raises exceptions is a very difficult problem.  My task, with Friendly-traceback, is generally made much easier thanks to accurate and usually helpful error messages provided by Python. So, please do not read this post and conclude that I am dismissive of the efforts of the Python core developers in this area. 

Matt Layman: New Project, Who Dis? - Building SaaS #38

$
0
0
In this episode, we started a brand new project! I had some internet troubles so this “stream” is actually a local recording from my computer. We created a new Django project from scratch and set up Heroku to handle deployments. In spite of the streaming trouble, we were able to get a bunch done. We started the project from scratch so we made a repository on GitHub with some .gitignore settings tailored for Python projects.

Janusworx: #100DaysOfCode, Day 016 – Corey Schafer Python Video Marathon

$
0
0

Had decided to play hookey and start up another personal mini project.
But went down the rabbit hole of how to set up arguments.

And everytime I research something Python related, I end up with one of Corey Schafer’s videos.
So I decided to run through his entire Python playlist over the next few days. Will try to do this quickly, skipping over the parts I do know.

22 out of 127 videos done.


Techiediaries - Django: Angular 9/8 Tutorial By Example: REST CRUD APIs & HTTP GET Requests with HttpClient

$
0
0

In this Angular 9 tutorial, we'll learn to build an Angular 9 CRUD example application going through all the required steps from creating/simulating a REST API, scaffolding a new project, setting up the essential APIs, and finally building and deploying your final application to the cloud.

  • We'll learn by example how to send GET requests with URL query strings and parameters and process HTTP responses from REST API servers in your Angular 9/8 application using Httplient for fetching and consuming JSON data, how to do error handling for HTTP errors using the RxJS throwError() and catchError() operators, how to retry failed HTTP requests in poor network connections and cancel pending requests using the RxJS retry() and takeUntil() operators, and finally how to deploy the application to Firebase hosting using the latest Angular 8.3+ features.
  • We'll also see how to use Angular services and RxJS Observables, and learn how to set up Angular Material in our project and style the UI with Material Design components.
  • We'll see how to use the new ng deploy feature in Angular 8.3+ to easily deploy your Angular 9 application from the command-line to Firebase hosting.

Angular 9 is currently in RC version, and comes with various new features and improvements particularly the new Ivy renderer.

This tutorial is now updated to the latest Angular 9 version.

Note: Please note that we are using HttpClient which is an improved version of the HTTP Client API, available starting from Angular version 4.3.0-rc.0. The old HTTP client is not available in Angular 9.

You can also check out how to use HttpClient with Angular 9 to build a news application that fetches JSON data from a third-party REST API in this tutorial.

Throughout this step by step Angular 9 tutorial, we are going to see a practical CRUD example of how to use the HttpClient that's available from the @angular/common/http package, to make HTTP GET requests using the get() method.

We'll cover:

  • How to create a fake and complete working CRUD REST API,
  • How to install Angular CLI v9,
  • How to create an Angular 9 project using Angular CLI,
  • How to set up Angular Material and style your application with Material Design,
  • How to create Angular components, routing and navigation between them,
  • How to create and inject Angular services,
  • How to send HTTP GET requests to servers using HttpClient,
  • How to use the HttpParams class to add URL query strings in your HttpRequest,
  • How to subscribe and unsubscribe from RxJS Observables returned by HttpClient,
  • How to handle HTTP errors using the throwError() and catchError() operators,
  • How to retry failed HTTP requests using the RxJS retry() operator,
  • How to unsubscribe from RxJS Observables returned from HttpClient methods using the takeUntil() operator when requests are concelled,
  • How to build your application for production and deploy it to Firebase hosting using the new ng deploy command available from Angular 8.3+

The steps of this Angular 9 tutorial are as follows:

  • Step 1 — Setting up Angular CLI v9
  • Step 2 — Initializing a New Angular 9 Example Project
  • Step 3 — Setting up a (Fake) JSON REST API
  • Step 4 — Setting up Angular HttpClient v9 in our Example Project
  • Step 5 — Creating Angular 9 Components
  • Step 6 — Adding Angular 9 Routing
  • Step 7 — Styling the UI with Angular Material v9
  • Step 8 — Consuming the JSON REST API with Angular HttpClient v9
  • Step 9 — Adding HTTP Error Handling with RxJS catchError()& HttpClient
  • Step 10 — Retrying Failed HTTP Requests with RxJS retry()& HttpClient
  • Step 11 — Unsubscribing from HttpClient Observables with RxJS takeUntil()
  • Step 12 — Adding URL Query Parameters to the HttpClient get() Method
  • Step 13 — Getting the Full HTTP Response with Angular HttpClient v9
  • Step 14 — Requesting a Typed HTTP Response with Angular HttpClient v9
  • Step 15 — Building and Deploying your Angular 9 Application to Firebase Hosting

Let's get started by introducing Angular HttpClient, its features and why using it.

What is Angular HttpClient?

Front end applications, built using frameworks like Angular communicate with backend servers through REST APIs (which are based on the HTTP protocol) using either the XMLHttpRequest interface or the fetch() API.

Angular HttpClient makes use of the XMLHttpRequest interface that supports both modern and legacy browsers.

The HttpClient is available from the @angular/common/http package and has a simplified API interface and powerful features such as easy testability, typed request and response objects, request and response interceptors, reactive APIs with RxJS Observables, and streamlined error handling.

Why Angular HttpClient?

The HttpClient builtin service provides many advantages to Angular developers:

  • HttpClient makes it easy to send and process HTTP requests and responses,
  • HttpClient has many builtin features for implementing test units,
  • HttpClient makes use of RxJS Observables for handling asynchronous operations instead of Promises which simplify common web development tasks such as
  • - The concelation of HTTP requests,
  • - Listenning for the progression of download and upload operations,
  • - Easy error handling,
  • - Retrying failed HTTP requests, etc.

Now after introducing HttpClient, let's proceed to building our example application starting with the prerequisites needed to successfully complete our Angular 9 tutorial.

Prerequisites

Before getting started you need a few prerequisites:

  • Basic knowledge of TypeScript. Particularly the familiarity with Object Oriented concepts such as TypeScript classes and decorators.
  • A local development machine with Node 10+, together with NPM 6+ installed. Node is required by the Angular CLI like the most frontend tools nowadays. You can simply go to the downloads page of the official website and download the binaries for your operating system. You can also refer to your specific system instructions for how to install Node using a package manager. The recommended way though is using NVM— Node Version Manager — a POSIX-compliant bash script to manage multiple active Node.js versions.

Note: If you don't want to install a local environment for Angular development but still want to try the code in this tutorial, you can use Stackblitz, an online IDE for frontend development that you can use to create an Angular project compatible with Angular CLI.

If you have the previous prerequisites, you are ready for the next steps of our Angular 9 tutorial that will teach you by example how to use Angular HttpClient to send HTTP GET requests for fetching JSON data and the various RxJS operators such as catchError(), tap(), retry(), and takeUntil() for implementing advanced features such as error handling, retrying failed HTTP requests and cancelling pending requests.

In the first step(s) of our tutorial, we'll see how to install Angular CLI 9 and create an example project from scratch.

Step 1 — Setting up Angular CLI v9

In this step, we'll install the latest Angular CLI 9 version (at the time of writing this tutorial).

Note: These instructions are also valid for Angular 8.

Angular CLI

Angular CLI is the official tool for initializing and working with Angular projects. To install it, open a new command-line interface and run the following command:

$ npm install -g @angular/cli@next 

At the time of writing this tutorial, angular/cli v9.0.0-rc.2 will be installed on your system.

Please note that until Angular 9 is officialy released, you need to use the @next tag to install the latest pre-release version.

If you run the ng version command, you should get a similar output:

Angular CLI: 9.0.0-rc.2
Node: 10.16.3
OS: win32 ia32
Angular:
...

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.900.0-rc.2
@angular-devkit/core         9.0.0-rc.2
@angular-devkit/schematics   9.0.0-rc.2
@schematics/angular          9.0.0-rc.2
@schematics/update           0.900.0-rc.2
rxjs                         6.5.3

In the next step, we'll learn how to intialize a new example project from the command-line.

Step 2 — Initializing a New Angular 9 Example Project

In this step, we'll proceed to create our example project. Head back to your command-line interface and run the following commands:

$ cd ~
$ ng new angular-httpclient-example

The CLI will ask you a couple of questions — If Would you like to add Angular routing? Type y for Yes and Which stylesheet format would you like to use? Choose CSS.

This will instruct the CLI to automatically set up routing in our project so we'll only need to add the routes for our components to implement navigation in our application.

If you run the ng version command inside your project's folder, you should get a similar output:

Angular CLI: 9.0.0-rc.2
Node: 10.16.3
OS: win32 ia32
Angular: <error>
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.900.0-rc.2 (cli-only)
@angular-devkit/build-angular   <error>
@angular-devkit/core            9.0.0-rc.2 (cli-only)
@angular-devkit/schematics      9.0.0-rc.2 (cli-only)
@schematics/angular             9.0.0-rc.2 (cli-only)
@schematics/update              0.900.0-rc.2 (cli-only)
rxjs                            6.5.3 (cli-only)
typescript                      3.6

Next, navigate to you project’s folder and run the local development server using the following commands:

$ cd angular-httpclient-example
$ ng serve    

A local development server will start listening on the http://localhost:4200/ address. Angular CLI Ng Serve

Open your web browser and navigate to the http://localhost:4200/ address to see your app up and running. This is a screenshot at this point:

Angular 9 Project

You should now leave the development server running and start a new command-line interface for running the CLI commands of the next steps.

In the next step, we'll learn how to create a fake JSON REST API that we'll be consuming in our Angular example application.

Step 3 — Setting up a (Fake) JSON REST API

Before we proceed to develop our Angular application, we'll need to prepare a JSON REST API that we can consume using HttpClient.

We can also consume or fetch JSON data from third-party REST API servers but in this example, we choose to create a fake REST API. Check out this tutorial for a real REST API example. As far as Angular concerned, there is no difference between consuming fake or real REST APIs.

As said, you can either use an external API service, create a real REST API server or create a fake API using json-server. In this example we'll use the last approach.

So head over to a new command-line interface and start by installing json-server from npm in your project:

$ cd ~/angular-httpclient-example
$ npm install --save json-server 

Next, create a server folder in the root folder of your Angular project:

$ mkdir server
$ cd server

In the server folder, create a database.json file and add the following JSON object:

{"products":[]}

This JSON file will act as a database for your REST API server. You can simply add some data to be served by your REST API or use Faker.js for automatically generating massive amounts of realistic fake data.

Go back to your command-line, navigate back from the server folder, and install Faker.js from npm using the following command:

$ cd ..
$ npm install faker --save

At the time of creating this example, faker v4.1.0 will be installed.

Now, create a generate.js file and add the following code:

varfaker=require('faker');vardatabase={products:[]};for(vari=1;i<=300;i++){database.products.push({id:i,name:faker.commerce.productName(),description:faker.lorem.sentences(),price:faker.commerce.price(),imageUrl:"https://source.unsplash.com/1600x900/?product",quantity:faker.random.number()});}console.log(JSON.stringify(database));

We first imported faker, next we defined an object with one empty array for products. Next, we entered a for loop to create 300 fake entries using faker methods like faker.commerce.productName() for generating product names. Check all the available methods. Finally we converted the database object to a string and log it to standard output.

Next, add the generate and server scripts to the package.json file:

"scripts":{"ng":"ng","start":"ng serve","build":"ng build","test":"ng test","lint":"ng lint","e2e":"ng e2e","generate":"node ./server/generate.js > ./server/database.json","server":"json-server --watch ./server/database.json"},

Next, head back to your command-line interface and run the generate script using the following command:

$ npm run generate

Finally, run the REST API server by executing the following command:

$ npm run server

You can now send HTTP requests to the server just like any typical REST API server. Your server will be available from the http://localhost:3000/ address.

REST API Server

These are the API endpoints we'll be able to use via our JSON REST API server:

  • GET /products for getting the products,
  • GET /products/<id> for getting a single product by id,
  • POST /products for creating a new product,
  • PUT /products/<id> for updating a product by id,
  • PATCH /products/<id> for partially updating a product by id,
  • DELETE /products/<id> for deleting a product by id.

You can use _page and _limit parameters to get paginated data. In the Link header you'll get first, prev, next and last links.

For example:

GET /products?_page=1 for getting the first page of data, GET /products?_page=1&_limit=5 for getting the first five products of the first page of data.

Note: You can use other features such as filters, sorting and ordering. For more information, check out the docs.

Leave the JSON REST API server running and open a new command-line interface for typing the commands of the next steps.

As a summary of what we have done — We installed Angular CLI and initialized a new project based on the latest Angular 9 version. Then, we created a REST API using json-server based on a JSON file. In the next step of our Angular 9 tutorial, we'll learn how to set up HttpClient in our Angular 9 project.

Step 4 — Setting up Angular 9 HttpClient in our Example Project

In this step, we'll proceed to set up the HttpClient module in our example.

HttpClient lives in a separate Angular module, so we'll need to import it in our main application module before we can use it.

Open your example project with a code editor or IDE. I'll be using Visual Studio Code.

Next, open the src/app/app.module.ts file, import HttpClientModule and add it to the imports array of the module as follows:

import{BrowserModule}from'@angular/platform-browser';import{NgModule}from'@angular/core';import{AppRoutingModule}from'./app-routing.module';import{AppComponent}from'./app.component';import{HttpClientModule}from'@angular/common/http';@NgModule({declarations:[AppComponent,],imports:[BrowserModule,AppRoutingModule,HttpClientModule],providers:[],bootstrap:[AppComponent]})exportclassAppModule{}

That's all, we are now ready to use the HttpClient service in our project but before that we need to create a couple of components — The home and about components. This is what we'll learn to do in the next step.

Step 5 — Creating Angular 9 Components

In this step, we'll proceed to create the Angular components that control our application UI.

Head back to a new command-line interface and run the following command:

$ cd ~/angular-httpclient-example
$ ng generate component home

This is the output of the command:

CREATE src/app/home/home.component.html (19 bytes)
CREATE src/app/home/home.component.spec.ts (614 bytes)
CREATE src/app/home/home.component.ts (261 bytes)
CREATE src/app/home/home.component.css (0 bytes)
UPDATE src/app/app.module.ts (467 bytes)

The CLI created four files for the component and added it to the declarations array in the src/app/app.module.ts file.

Next, let's create the about component using the following command:

$ ng generate component about

Next, open the src/app/about/about.component.html and add the following code:

<pstyle="padding: 13px;">
An Angular 9 example application that demonstrates how to use HttpClient to consume REST APIs
</p>

We'll update the home component in the following steps.

In the next step of our Angular 9 tutorial, we'll add these components to the router.

Step 6 — Adding Angular 9 Routing

In this step, we'll proceed to add routing to our example.

Head back to the src/app/app-routing.module.ts file, that was automatically created by Angular CLI for routing configuration, and import the components then add the routes as follows:

import{NgModule}from'@angular/core';import{Routes,RouterModule}from'@angular/router';import{HomeComponent}from'./home/home.component';import{AboutComponent}from'./about/about.component';constroutes:Routes=[{path:'',redirectTo:'home',pathMatch:'full'},{path:'home',component:HomeComponent},{path:'about',component:AboutComponent},];@NgModule({imports:[RouterModule.forRoot(routes)],exports:[RouterModule]})exportclassAppRoutingModule{}

We first imported the home and about components, next we added three routes including a route for redirecting the empty path to the home component, so when the user visits the app, they will be redirected to the home page.

In the next step of our example, we'll set up Angular Material in our project for styling our UI.

Step 7 — Styling the UI with Angular Material v9

In this step of our Angular 9 tutorial, we'll proceed to add Angular Material to our project and style our application UI.

Angular Material provides Material Design components that allow developers to create professional UIs. Setting up Angular Material in our project is much easier now with the new ng add command of the Angular CLI v7+.

Head back to your command-line interface, and run the following command from the root of your project:

$ ng add @angular/material

You'll be asked for choosing a theme, choose Indigo/Pink.

For the other options — Set up HammerJS for gesture recognition? and Set up browser animations for Angular Material? Simply press Enter in your keyboard to choose the default answers.

Next, open the src/styles.css file and add a theme:

@import"~@angular/material/prebuilt-themes/indigo-pink.css";

Each Angular Material component has a separate module that you need to import before you can use the component. Open the src/app/app.module.ts file and add the following imports:

import{MatToolbarModule,MatIconModule,MatCardModule,MatButtonModule,MatProgressSpinnerModule}from'@angular/material';

We imported the following modules:

  • MatToolbar that provides a container for headers, titles, or actions.
  • MatCard that provides a content container for text, photos, and actions in the context of a single subject.
  • MatButton that provides a native <button> or <a> element enhanced with Material Design styling and ink ripples.
  • MatProgressSpinner that provides a circular indicator of progress and activity.

Next, you need to include these modules in the imports array:

@NgModule({declarations:[AppComponent,HomeComponent,AboutComponent],imports:[BrowserModule,AppRoutingModule,HttpClientModule,BrowserAnimationsModule,MatToolbarModule,MatIconModule,MatButtonModule,MatCardModule,MatProgressSpinnerModule],providers:[],bootstrap:[AppComponent]})exportclassAppModule{}

Next, open the src/app/app.component.html file and update it as follows:

<mat-toolbarcolor="primary"><h1>
    ngStore 
  </h1><buttonmat-buttonrouterLink="/">Home</button><buttonmat-buttonrouterLink="/about">About</button></mat-toolbar><router-outlet></router-outlet>

We created the shell of our application containing a top bar with two navigation buttons to the home and about components.

As a summary of what we did until this point of our tutorial — We have setup HttpClient and Angular Material v9 in our project, created the home and about components and configured routing, and finaly added the shell of our application containing a topbar with navigation.

In the next step of our tutorial, we'll learn how to fetch the JSON data from our REST API server using HttpClient v9.

Step 8 — Consuming the JSON REST API with Angular HttpClient 9

In this step, we'll proceed to consume JSON data from our REST API server in our example application.

We'll need to create an Angular service for encapsulating the code that deals with consuming data from the REST API server.

A service is a singleton that can be injected by other services and components using the Angular dependency injection.

In software engineering, dependency injection is a technique whereby one object supplies the dependencies of another object. Source

Now, let’s generate an Angular service that interfaces with the JSON REST API. Head back to your command-line interface and run the following command:

$ ng generate service data

Next, open the src/app/data.service.ts file, import and inject HttpClient as follows:

import{Injectable}from'@angular/core';import{HttpClient}from'@angular/common/http';@Injectable({providedIn:'root'})exportclassDataService{privateREST_API_SERVER="http://localhost:3000";constructor(privatehttpClient:HttpClient){}}

We imported and injected the HttpClient service as a private httpClient instance. We also defined the REST_API_SERVER variable that holds the address of our REST API server.

Next, add a sendGetRequest() method that sends a GET request to the REST API endpoint to retrieve JSON data:

import{Injectable}from'@angular/core';import{HttpClient}from'@angular/common/http';@Injectable({providedIn:'root'})exportclassDataService{privateREST_API_SERVER="http://localhost:3000";constructor(privatehttpClient:HttpClient){}publicsendGetRequest(){returnthis.httpClient.get(this.REST_API_SERVER);}}

The method simply invokes the get() method of HttpClient to send GET requests to the REST API server.

Next, we now need to use this service in our home component. Open the src/app/home/home.component.ts file, import and inject the data service as follows:

import{Component,OnInit}from'@angular/core';import{DataService}from'../data.service';@Component({selector:'app-home',templateUrl:'./home.component.html',styleUrls:['./home.component.css']})exportclassHomeComponentimplementsOnInit{products=[];constructor(privatedataService:DataService){}ngOnInit(){this.dataService.sendGetRequest().subscribe((data:any[])=>{console.log(data);this.products=data;})}}

We imported and injected DataService as a private dataService instance via the component constructor.

Next, we defined a products variable and called the sendGetRequest() method of the service for fetching data from the JSON REST API server.

Since the sendGetRequest() method returns the return value of the HttpClient.get() method which is an RxJS Observable, we subscribed to the returned Observable to actually send the HTTP GET request and process the HTTP response.

When data is received, we added it in the products array.

Next, open the src/app/home/home.component.html file and update it as follows:

<divstyle="padding: 13px;"><mat-spinner*ngIf="products.length === 0"></mat-spinner><mat-card*ngFor="let product of products"style="margin-top:10px;"><mat-card-header><mat-card-title>{{product.name}}</mat-card-title><mat-card-subtitle>{{product.price}} $/ {{product.quantity}}
            </mat-card-subtitle></mat-card-header><mat-card-content><p>
                {{product.description}}
            </p><imgstyle="height:100%; width: 100%;"src="{{ product.imageUrl }}"/></mat-card-content><mat-card-actions><buttonmat-button> Buy product</button></mat-card-actions></mat-card></div>

We used the <mat-spinner> component for showing a loading spinner when the length of the products array equals zero i.e before no data is received from the REST API server.

Next, we iterated over the products array and used a Material card to display the name, price, quantity, description and image of each product.

This is a screenshot of the home page after JSON data is fetched:

Angular 9 Example

Next, we'll see how to add error handling to our service.

Step 9 — Adding HTTP Error Handling with RxJS catchError()& HttpClient

In this step, we'll proceed to add error handling in our example application.

The Angular's HttpClient methods can be easily used with the catchError() operator from RxJS, since they return Observables, via the pipe() method for catching and handling errors. We simply need to define a method to handle errors within your service.

There are two types of errors in front-end applications:

  • Client-side errors such as network issues and JavaScript syntax and type errors. These errors return ErrorEvent objects.
  • Server-side errors such as code errors in the server and database access errors. These errors return HTTP Error Responses.

As such, we simply need to check if an error is an instance of ErrorEvent to get the type of the error so we can handle it appropriately.

Now, let's see this by example. Open the src/app/data.service.ts file and update it accordingly:

import{Injectable}from'@angular/core';import{HttpClient,HttpErrorResponse}from"@angular/common/http";import{throwError}from'rxjs';import{retry,catchError}from'rxjs/operators';@Injectable({providedIn:'root'})exportclassDataService{privateREST_API_SERVER="http://localhost:3000/products";constructor(privatehttpClient:HttpClient){}handleError(error:HttpErrorResponse){leterrorMessage='Unknown error!';if(error.errorinstanceofErrorEvent){// Client-side errorserrorMessage=`Error:${error.error.message}`;}else{// Server-side errorserrorMessage=`ErrorCode:${error.status}\nMessage:${error.message}`;}window.alert(errorMessage);returnthrowError(errorMessage);}publicsendGetRequest(){returnthis.httpClient.get(this.REST_API_SERVER).pipe(catchError(this.handleError));}}

As you can see, this needs to be done for each service in your application which is fine for our example since it only contains one service but once your application starts growing with many services which may all throw errors you need to use better solutions instead of using the handleError method per each service which is error-prone. One solution is to handle errors globally in your Angular application using HttpClient interceptors.

This is a screenshot of an error on the console if the server is unreachable:

Angular HttpClient Error Example

In the next step, we'll see how to improve our data service by automatically retry sending the failed HTTP requests.

Step 10 — Retrying Failed HTTP Requests with RxJS retry()& HttpClient

In this step of our Angular 9 tutorial, we'll see how to use the retry() operator of RxJS with HttpClient to automatically resubscribing to the returned Observable which results in resending the failed HTTP requests.

In many cases, errors are temporary and due to poor network conditions so simply trying again will make them go away automatically. For example, in mobile devices network interruptions are frequent so if the user tries again, they may get a successful response. Instead of letting users manually retry, let's see how to do that automatically in our example application.

The RxJS library provides several retry operators. Among them is the retry() operator which allows you to automatically re-subscribe to an RxJS Observable a specified number of times. Re-subscribing to the Observable returned from an HttpClient method has the effect of resending the HTTP request to the server so users don't need to repeat the operation or reload the application.

You can use the RxJS retry() operator by piping it (using the pipe() method) onto the Observable returned from the HttpClient method before the error handler.

Go to the src/app/data.service.ts file and import the retry() operator:

import{retry,catchError}from'rxjs/operators';

Next update the sendGetRequest() method as follows:

publicsendGetRequest(){returnthis.httpClient.get(this.REST_API_SERVER).pipe(retry(3),catchError(this.handleError));}

This will retry sending the failed HTTP request three times.

In the next step, we'll see how to unsubscribe from RxJS Observables in our example home component.

Step 11 — Unsubscribing from HttpClient Observables with RxJS takeUntil()

In this step of our Angular 9 tutorial, we'll learn about why we need and how to unsubscribe from Observables in our code using the takeUntil() operator.

First of all, do you need to unsubscribe from the Observables returned by the HttpClient methods?

Generally, you need to manually unsubscribe from any subscribed RxJS Observables in your Angular components to avoid memory leaks but in the case of HttpClient, this is automatically handled by Angular by unsubscribing when the HTTP response is received. However, there are some cases when you need to manually unsubscribe for example to cancel pending requests when users are about to leave the component.

We can simply call the unsubscribe() method from the Subscription object returned by the subscribe() method in the ngOnDestroy() life-cycle method of the component to unsubscribe from the Observable.

There is also a better way to unsubscribe from or complete Observables by using the takeUntil() operator.

The takeUntil() operator emits the values emitted by the source Observable until a notifier Observable emits a value.

Let's see how to use this operator to complete Observables when the component is destroyed.

Check out How to cancel/unsubscribe all pending HTTP requests angular 4+.

Open the src/app/home/home.component.ts file and update it as follows:

import{Component,OnInit,OnDestroy}from'@angular/core';import{DataService}from'../data.service';import{takeUntil}from'rxjs/operators';import{Subject}from'rxjs';@Component({selector:'app-home',templateUrl:'./home.component.html',styleUrls:['./home.component.css']})exportclassHomeComponentimplementsOnInit,OnDestroy{products=[];destroy$:Subject<boolean>=newSubject<boolean>();constructor(privatedataService:DataService){}ngOnInit(){this.dataService.sendGetRequest().pipe(takeUntil(this.destroy$)).subscribe((data:any[])=>{console.log(data);this.products=data;})}ngOnDestroy(){this.destroy$.next(true);// Unsubscribe from the subjectthis.destroy$.unsubscribe();}}

We first imported the OnDestroy interface, Subject and the takeUntil() operator. Next, we implemented the OnDestroy interface and added the ngOnDestroy() lifecycle hook to the component.

Next, we created an instance of Subject which can emit boolean values (the type of the value doesn't really matter in this example) that will be used as the notifier of the takeUntil() operator.

Next, in the ngOnInit() lifecycle hook, we called the sendGetRequest() of our data service and called the pipe() method of the returned Observable to pipe the takeUnitl() operator and finaly subscribed to the combined Observable. In the body of the subscribe() method, we added the logic to put the fetched data of the HTTP response in the products array.

The takeUntil() operator allows a notified Observable to emit values until a value is emitted from a notifier Observable.

When Angular destroys a component it calls the ngOnDestroy() lifecycle method which, in our case, calls the next() method to emit a value so RxJS completes all subscribed Observables.

That's it. In this step, we have added the logic to cancel any pending HTTP request by unsubscribing from the returned Observable in case the user descides to navigate away from the component before the HTTP response is received.

In the next step of our Angular 9 tutorial, we'll see how to use URL query parameters with the get() method of HttpClient.

Step 12 — Adding URL Query Parameters to the HttpClient get() Method

In this step, we'll start adding the logic for implementing pagination in our example application. We'll see how to use URL query parameters via fromString and HttpParams to provide the appropriate values for the the _page and _limit parameters of the /products endpoint of our JSON REST API server for getting paginated data.

Open the src/app/data.service.ts file and start by adding the following the import for HttpParams:

import{HttpClient,HttpErrorResponse,HttpParams}from"@angular/common/http";

Next, update the sendGetRequest() method as follows:

publicsendGetRequest(){// Add safe, URL encoded_page parameter constoptions={params:newHttpParams({fromString:"_page=1&_limit=20"})};returnthis.httpClient.get(this.REST_API_SERVER,options).pipe(retry(3),catchError(this.handleError));}

We used HttpParams and fromString to create HTTP query parameters from the _page=1&_limit=20 string. This tells to returns the first page of 20 products.

Now the sendGetRequest() will be used to retrieve the first page of data. The received HTTP response will contain a Link header with information about the first, previous, next and last links of data pages.

In the Link header you’ll get first, prev, next and last links. In the next step, we'll see how to extract these pagination links by parsing full HTTP responses.

Step 13 — Getting the Full HTTP Response with Angular HttpClient 9

In this ste, we'll proceed by implementing the logic for retrieving pagination information from the Link header contained in the HTTP response received from the JSON REST API server.

By default, HttpClient does only provide the response body but in our case we need to parse the Link header for pagination links so we need to tell HttpClient that we want the full HttpResponse using the observe option.

The Link header in HTTP allows the server to point an interested client to another resource containing metadata about the requested resource.Wikipedia

Go to the src/app/data.service.ts file and import the RxJS tap() operator:

import{retry,catchError,tap}from'rxjs/operators';

Next, define the following string variables:

publicfirst:string="";publicprev:string="";publicnext:string="";publiclast:string="";

Next, define the parseLinkHeader() method which parses the Link header and populate the previous variables accordingly:

parseLinkHeader(header){if(header.length==0){return;}letparts=header.split(',');varlinks={};parts.forEach(p=>{letsection=p.split(';');varurl=section[0].replace(/<(.*)>/,'$1').trim();varname=section[1].replace(/rel="(.*)"/,'$1').trim();links[name]=url;});this.first=links["first"];this.last=links["last"];this.prev=links["prev"];this.next=links["next"];}

Next, update the sendGetRequest() as follows:

publicsendGetRequest(){// Add safe, URL encoded _page and _limit parameters returnthis.httpClient.get(this.REST_API_SERVER,{params:newHttpParams({fromString:"_page=1&_limit=20"}),observe:"response"}).pipe(retry(3),catchError(this.handleError),tap(res=>{console.log(res.headers.get('Link'));this.parseLinkHeader(res.headers.get('Link'));}));}

We added the observe option with the response value in the options parameter of the get() method so we can have the full HTTP response with headers. Next, we use the RxJS tap() operator for parsing the Link header before returning the final Observable.

Since the sendGetRequest() is now returning an Observable with a full HTTP response, we need to update the home component so open the src/app/home/home.component.ts file and import HttpResponse as follows:

import{HttpResponse}from'@angular/common/http';

Next, update the subscribe() method as follows:

ngOnInit(){this.dataService.sendGetRequest().pipe(takeUntil(this.destroy$)).subscribe((res:HttpResponse<any>)=>{console.log(res);this.products=res.body;})}

We can now access the data from the body object of the received HTTP response.

Next, go back to the src/app/data.service.ts file and add the following method:

publicsendGetRequestToUrl(url:string){returnthis.httpClient.get(url,{observe:"response"}).pipe(retry(3),catchError(this.handleError),tap(res=>{console.log(res.headers.get('Link'));this.parseLinkHeader(res.headers.get('Link'));}));}

This method is similar to sendGetRequest() except that it takes the URL to which we need to send an HTTP GET request.

Go back to the src/app/home/home.component.ts file and add define the following methods:

publicfirstPage(){this.products=[];this.dataService.sendGetRequestToUrl(this.dataService.first).pipe(takeUntil(this.destroy$)).subscribe((res:HttpResponse<any>)=>{console.log(res);this.products=res.body;})}publicpreviousPage(){if(this.dataService.prev!==undefined&&this.dataService.prev!==''){this.products=[];this.dataService.sendGetRequestToUrl(this.dataService.prev).pipe(takeUntil(this.destroy$)).subscribe((res:HttpResponse<any>)=>{console.log(res);this.products=res.body;})}}publicnextPage(){if(this.dataService.next!==undefined&&this.dataService.next!==''){this.products=[];this.dataService.sendGetRequestToUrl(this.dataService.next).pipe(takeUntil(this.destroy$)).subscribe((res:HttpResponse<any>)=>{console.log(res);this.products=res.body;})}}publiclastPage(){this.products=[];this.dataService.sendGetRequestToUrl(this.dataService.last).pipe(takeUntil(this.destroy$)).subscribe((res:HttpResponse<any>)=>{console.log(res);this.products=res.body;})}

Finally, add open the src/app/home/home.component.html file and update the template as follows:

<divstyle="padding: 13px;"><mat-spinner*ngIf="products.length === 0"></mat-spinner><mat-card*ngFor="let product of products"style="margin-top:10px;"><mat-card-header><mat-card-title>#{{product.id}} {{product.name}}</mat-card-title><mat-card-subtitle>{{product.price}} $/ {{product.quantity}}
            </mat-card-subtitle></mat-card-header><mat-card-content><p>
                {{product.description}}
            </p><imgstyle="height:100%; width: 100%;"src="{{ product.imageUrl }}"/></mat-card-content><mat-card-actions><buttonmat-button> Buy product</button></mat-card-actions></mat-card></div><div><button(click)="firstPage()"mat-button> First</button><button(click)="previousPage()"mat-button> Previous</button><button(click)="nextPage()"mat-button> Next</button><button(click)="lastPage()"mat-button> Last</button></div>

This is a screenshot of our application:

Step 14 — Requesting a Typed HTTP Response with Angular HttpClient 9

In this step, we'll see how to use typed HTTP responses in our example application.

Angular HttpClient allows you to specify the type of the response object in the request object, which make consuming the response easier and straightforward. This also enables type assertion during the compile time.

Let's start by defining a custom type using a TypeScript interface with the required properties.

Head back to your command-line interface and run the following command from the root of your project:

$ ng generate interface  product

Next, open the src/app/product.ts file and update it as follows:

exportinterfaceProduct{id:number;name:string;description:string;price:number;quantity:number;imageUrl:string;}

Next, specify the Product interface as the HttpClient.get() call's type parameter in the data service. Go back to the src/app/data.service.ts file and import the Product interface:

import{Product}from'./product';

Next:

publicsendGetRequest(){returnthis.httpClient.get<Product[]>(this.REST_API_SERVER,{params:newHttpParams({fromString:"_page=1&_limit=20"}),observe:"response"}).pipe(retry(3),catchError(this.handleError),tap(res=>{console.log(res.headers.get('Link'));this.parseLinkHeader(res.headers.get('Link'));}));}publicsendGetRequestToUrl(url:string){returnthis.httpClient.get<Product[]>(url,{observe:"response"}).pipe(retry(3),catchError(this.handleError),tap(res=>{console.log(res.headers.get('Link'));this.parseLinkHeader(res.headers.get('Link'));}));}

Next, open the src/app/home/home.component.ts file and import the Product interface:

import{Product}from'../product';

Next change the type of the products array as follows:

exportclassHomeComponentimplementsOnInit,OnDestroy{products:Product[]=[];

Next chnage the type of the HTTP response in the sendGetRequest() call:

ngOnInit(){this.dataService.sendGetRequest().pipe(takeUntil(this.destroy$)).subscribe((res:HttpResponse<Product[]>)=>{console.log(res);this.products=res.body;})}

You also need to do the same for the other firstPage(), previousPage(), nextPage() and lastPage() methods.

Step 15 — Building and Deploying your Angular 9 Application to Firebase Hosting

In this step, we'll see how to build and deploy our example application to Firebase hosting using the ng deploy command available in Angular 8.3+.

We'll only see how to deploy the frontend application without the fake JSON server.

Angular CLI 8.3+ introduced a new ng deploy command that makes it more easier than before to deploy your Angular application using the deploy CLI builder assocaited with your project. There are many third-party builders that implement deployment capabilities for different platforms. You can add any of them to your project by running the ng add command.

After adding a deployment package it will automatically update your workspace configuration (i.e the angular.json file) with a deploy section for the selected project. You can then use the ng deploy command to deploy that project.

Let's now see that by example by deploying our project to Firebase hosting.

Head back to your command-line interface, make sure you are inside the root folder of your Angular project and run the following command:

$ ng add @angular/fire

This will add the Firebase deployment capability to your project.

The command will also update the package.json of our project by adding this section:

"deploy":{"builder":"@angular/fire:deploy","options":{}}

The CLI will prompt you to Paste authorization code here: and will open your default web browser and ask you to give Firebase CLI permissions to administer your Firebase account:

After you signin with the Google account associated with your Firebase account, you'll be given the authorization code:

Next, you'll be prompted: Please select a project: (Use arrow keys or type to search). You should have created a Firebase project before.

The CLI will create the firebase.json and .firebaserc files and update the angular.json file accordingly.

Next, deploy your application to Firebase, using the following command:

$ ng deploy

The command will produce an optimized build of your application (equivalent to the ng deploy --prod command), it will upload the production assets to Firebase hosting.

Conclusion

Throughout this Angular 9 tutorial, we've built a complete working Angular application example using the latest version.

As a recap, we've particularly seen by example how to set up HttpClient and send HTTP GET requests with parameters using the HttpClient.get() method, how to handle HTTP errors using the RxJS throwError() and catchError() operators, unsubscribe from RxJS Observables for the cancelled HTTP requests using the takeUntil() operator and retry failed requests with the retry() operator and finally how to deploy our application to Firebase hosting using the latest ng deploy feature available from Angular 8.3+.


Techiediaries - Django: Angular 9 CRUD Tutorial: Consume a Python/Django CRUD REST API

$
0
0

Angular 9 is in pre-release! Read about its new features in this article and how to update to the latest Angular version in this article.

You can also get our Angular 8 book for free or pay what you can.

This tutorial is designed for developers that want to use Angular 9 to build front-end apps for their back-end REST APIs. You can either use Python & Django as the backend or use JSON-Server to mock the API if you don't want to deal with Python. We'll be showing both ways in this tutorial.

Check out the other parts of this tutorial:

This tutorial deals with REST APIs and routing but you can also start with basic concepts by following this tutorial (part 1 and part 2) instead which you'll build a simple calculator.

If you would like to consume a third-party REST API instead of building your own API, make to check out this tutorial.

You will see by example how to build a CRUD REST API with Python.

The new features of Angular 9 include better performance and smaller bundles thanks to Ivy.

Throughout this tutorial, designed for beginners, you'll learn Angular by example by building a full-stack CRUD — Create, Read, Update and Delete — web application using the latest version of the most popular framework and platform for building mobile and desktop client side applications (also called SPAs or Single Page Applications), created and used internally by Google.

In the back-end we'll use Python with Django, the most popular pythonic web framework designed for perfectionists with deadlines.

In nutshell, you'll learn to generate apps, components and services and add routing.

You'll also learn to use various features such as HttpClient for sending AJAX requests and HTTP calls and subscribing to RxJS 6 Observables etc.

By the end of this tutorial, you'll learn by building a real world example application:

  • How to install the latest version of the CLI,
  • How to use the CLI to generate a new Angular 9 project,
  • How to build a simple CRM application,
  • What's a component and component-based architecture
  • How to use RxJS 6 Observables and operators (map() and filter() etc.)
  • How to create components,
  • How to add component routing and navigation,
  • How to use HttpClient to consume a REST API etc.

Prerequisites

You will need to have the following prerequisites in order to follow this tutorial:

  • A Python development environment. We use a Ubuntu system with Python 3.7 and pip installed but you can follow these instructions in a different system as long as you have Python 3 and pip installed. Also the commands shown here are bash commands which are available in Linux-based systems and macOS but if you use Windows CMD or Powershell , make sure to use the equivalent commands or install bash for Windows.
  • Node.js and npm installed on your system. They are required by Angular CLI.
  • Familiarity with TypeScript.

If you have these requirements, you are good to go!

Getting & Running the Python REST API Server

We'll be using a Python REST API that we have created in this tutorial. Go ahead and clone the project's code from GitHub using the following command:

$ git clone https://github.com/techiediaries/python-django-crm-rest-api.git 

Next, create and activate a virtual environment:

$ python3 -m venv .env
$ source .env/bin/activate

Next, navigate to your CRM project and install the requirements using pip:

$ cd python-django-crm-rest-api
$ pip install -r requirements.txt

Finally, you can run the development server using the following command:

$ python manage.py runserver

Your REST API will be available from the http://localhost:8000/ address with CORS enabled.

Mocking the Same REST API with json-server

If you don't want to use a real Python & Django REST API server, you can also use json-server to quickly mock the REST API.

First, let's install json-server in our system using the following command:

$ npm install -g json-server

Next, create a folder for your server and create a JSON file (data.json) with the following content:

{"users":[{"id":1,"first_name":"Robert","last_name":"Schwartz","email":"admin@email.com"}],"accounts":[{"id":1,"name":"","email":"","phone":"","industry":"","website":"","description":"","createdBy":1,"createdAt":"","isActive":true}],"contacts":[{"id":1,"first_name":"","last_name":"","account":1,"status":1,"source":1,"email":"","phone":"","address":"","description":"","createdBy":1,"createdAt":"","isActive":true}],"activities":[{"id":1,"description":"","createdAt":"","contact":1,"status":1}],"contactsources":[{"id":1,"source":""}],"contactstatuses":[{"id":1,"status":""}],"activitystatuses":[{"id":1,"status":""}]}

We added empty entries for JSON data. Feel free to add your own data or use a tool like Faker.js to automatically generate fake data.

Next, you need to start the JSON server using:

$ json-server --watch data.json  

Your REST API server will be running at http://localhost:3000.

We'll have the following resources exposed:

  • http://localhost:3000/users
  • http://localhost:3000/accounts
  • http://localhost:3000/contacts
  • http://localhost:3000/activities
  • http://localhost:3000/contactsources
  • http://localhost:3000/contactstatuses
  • http://localhost:3000/activitystatuses

This is nearly the same REST API exposed by our real Python REST API server.

The example Angular application we'll be building is the front-end for the CRM RESTful API that will allow you to create accounts, contacts and activities. It's a perfect example for a CRUD (Create, Read, Update and Delete) application built as an SPA (Single Page Application). The example application is work on progress so we'll be building it through a series of tutorials and will be updated to contain advanced features such as RxJS and JWT authentication.

Installing the Angular CLI 9

Make sure you have Node.js installed, next run the following command in your terminal to install Angular CLI 9:

$ npm install @angular/cli@next --global

At the time of this writing @angular/cliv9.0.0-rc will be installed.

Before the final release of Angular 9, you will need to use the @next tag to install the pre-release version.

You can check the installed version by running the following command:

$ ng version

Now, you're ready to create a project using Angular CLI 9. Simply run the following command in your terminal:

ng new ngsimplecrm

The CLI will automatically generate a bunch of files common to most Angular projects and install the required dependencies for your project.

The CLI will prompt you if Would you like to add Angular routing? (y/N), type y. And Which stylesheet format would you like to use? Choose CSS and type Enter.

Next, you can serve your application locally using the following commands:

$ cd ./ngsimplecrm
$ ng serve

The command will compile our project and finally will display the ** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ ** ℹ 「wdm」: Compiled successfully. message.

This means, your application is running at http://localhost:4200.

What's a Component?

A component is a TypeScript class with an HTML template and an optional set of CSS styles that control a part of the screen.

Components are the most important concept in Angular. An Angular application is basically a tree of components with a root component (the famous AppComponent). The root component is the one contained in the bootstrap array in the main NgModule module defined in the app.module.ts file.

One important aspect of components is re-usability. A component can be re-used throughout the application and even in other applications. Common and repeatable code that performs a certain task can be encapsulated into a re-usable component that can be called whenever we need the functionality it provides.

Each bootstrapped component is the base of its own tree of components. Inserting a bootstrapped component usually triggers a cascade of component creations that fill out that tree. source

What's a Component-Based Architecture?

An Angular application is made of several components forming a tree structure with parent and child components.

A component is an independent block of a big system (web application) that communicates with the other building blocks (components) of the system using inputs and outputs. A component has an associated view, data and behavior and may have parent and child components.

Components allow maximum re-usability, easy testing, maintenance and separation of concerns.

Let's now see this practically. Head over to your Angular project folder and open the src/app folder. You will find the following files:

  • app.component.css: the CSS file for the component
  • app.component.html: the HTML view for the component
  • app.component.spec.ts: the unit tests or spec file for the component
  • app.component.ts: the component code (data and behavior)
  • app.module.ts: the application main module

Except for the last file which contains the declaration of the application main (root) Module, all these files are used to create a component. It's the AppComponent: The root component of our application. All other components we are going to create next will be direct or un-direct children of the root component.

Demystifying the App Component

Go ahead and open the src/app/app.component.ts file and let's understand the code behind the root component of the application.

First, this is the code:

import{Component}from'@angular/core';@Component({selector:'app-root',templateUrl:'./app.component.html',styleUrls:['./app.component.css']})exportclassAppComponent{title='app';}

We first import the Component decorator from @angular/core then we use it to decorate the TypeScript class AppComponent. The Component decorator takes an object with many parameters such as:

  • selector: specifies the tag that can be used to call this component in HTML templates just like the standard HTML tags
  • templateUrl: indicates the path of the HTML template that will be used to display this component (you can also use the template parameter to include the template inline as a string)
  • styleUrls: specifies an array of URLs for CSS style-sheets for the component

The export keyword is used to export the component so that it can be imported from other components and modules in the application.

The title variable is a member variable that holds the string 'app'. There is nothing special about this variable and it's not a part of the canonical definition of an Angular component.

Now let's see the corresponding template for this component. If you open src/app/app.component.html this is what you'll find:

<divstyle="text-align:center"><h1>
Welcome to !
</h1><imgwidth="300"alt="Angular Logo"src="data:image/svg+xml;...."></div><h2>Here are some links to help you start: </h2><ul><li><h2><atarget="_blank"rel="noopener"href="https://angular.io/tutorial">Tour of Heroes</a></h2></li><li><h2><atarget="_blank"rel="noopener"href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2></li><li><h2><atarget="_blank"rel="noopener"href="https://blog.angular.io/">Angular blog</a></h2></li></ul>

The template is a normal HTML file (almost all HTML tags are valid to be used inside Angular templates except for some tags such as <script>, <html> and <body>) with the exception that it can contain template variables (in this case the title variable) or expressions (``) that can be used to insert values in the DOM dynamically. This is called interpolation or data binding. You can find more information about templates from the docs.

You can also use other components directly inside Angular templates (via the selector property) just like normal HTML.

Note: If you are familiar with the MVC (Model View Controller) pattern, the component class plays the role of the Controller and the HTML template plays the role of the View.

Components by Example

After getting the theory behind Angular components, let's now create the components for our simple CRM application.

Our REST API, built either with Django or JSON-Server, exposes these endpoints:

  • /accounts: create or read a paginated list of accounts
  • /accounts/<id>: read, update or delete an account

  • /contacts: create or read a paginated list of contacts

  • /contacts/<id>: read, update or delete a contact

  • /activities: create or read a paginated list of activities

  • /activities/<id>: read, update or delete an activity

  • /contactstatuses: create or read a paginated list of contact statuses

  • /activitystatuses: create or read a paginated list of activity statuses

  • /contactsources: create or read a paginated list of contact sources

Before adding routing to our application, we first need to create the application components - so based on the exposed REST API architecture we can initially divide our application into these components:

  • AccountListComponent: this component displays and controls a tabular list of accounts
  • AccountCreateComponent: this component displays and controls a form for creating or updating accounts

  • ContactListComponent: displays a table of contacts

  • ContactCreateComponent: displays a form to create or update a contact

  • ActivityListComponent: displays a table of activities

  • ActivityCreateComponent: displays a form to create or update an activity

Let's use the Angular CLI to create the components. Open a new terminal and run the following commands:

$ ng generate component AccountList
$ ng generate component AccountCreate

$ ng generate component ContactList
$ ng generate component ContactCreate

$ ng generate component ActivityList
$ ng generate component ActivityCreate

This is the output of the first command:

CREATE src/app/account-list/account-list.component.css (0 bytes)
CREATE src/app/account-list/account-list.component.html (31 bytes)
CREATE src/app/account-list/account-list.component.spec.ts (664 bytes)
CREATE src/app/account-list/account-list.component.ts (292 bytes)
UPDATE src/app/app.module.ts (418 bytes)

You can see that the command generates all the files to define a component and also updates src/app/app.module.ts to include the component.

If you open src/app/app.module.ts after running all commands, you can see that all components are automatically added to the AppModule declarations array:

import{BrowserModule}from'@angular/platform-browser';import{NgModule}from'@angular/core';import{AppComponent}from'./app.component';import{AccountListComponent}from'./account-list/account-list.component';import{AccountCreateComponent}from'./account-create/account-create.component';import{ContactListComponent}from'./contact-list/contact-list.component';import{ContactCreateComponent}from'./contact-create/contact-create.component';@NgModule({declarations:[AppComponent,AccountListComponent,AccountCreateComponent,ContactListComponent,ContactCreateComponent,ActivityListComponent,ActivityCreateComponent],imports:[BrowserModule],providers:[],bootstrap:[AppComponent]})exportclassAppModule{}

Note: If you are creating components manually, you need to make sure to include them manually so they can be recognized as part of the module.

Setting up HttpClient

Now that we've created the various components, let's set up HttpClient in our Angular 9 project to consume the RESTful API back-end.

You simply need to add HttpClientModule to the imports array of the main application module:

// [...]import{HttpClientModule}from'@angular/common/http';@NgModule({declarations:[// [...]],imports:[// [...]HttpClientModule],providers:[],bootstrap:[AppComponent]})exportclassAppModule{}

We can now use HttpClient in our application.

Create Services

A service is a global class that can be injected in any component. It's used to encapsulate code that can be common between multiple components in one place instead of repeating it throughout various components.

Now, let's create the services that encapsulates all the code needed for interacting with the REST API. Using Angular CLI 8 run the following commands:

$ ng generate service services/contact
$ ng generate service services/activity
$ ng generate service services/account

Note: Since we have multiple services, we can put them in a services folder or whatever you want to call it.

Injecting HttpClient in the Services

Open the src/app/services/contact.service.ts file then import and inject HttpClient:

import{Injectable}from'@angular/core';import{HttpClient}from'@angular/common/http';@Injectable({providedIn:'root'})exportclassContactService{constructor(privatehttpClient:HttpClient){}}

Note: You will need to do the same for the other services.

Angular provides a way to register services/providers directly in the @Injectable() decorator by using the new providedIn attribute. This attribute accepts any module of your application or 'root' for the main app module. Now you don't have to include your service in the providers array of your module.

Conclusion

Throughout this tutorial for beginners, we've seen, by building a simple real world CRUD example, how to use different Angular 9 concepts to create simple full-stack CRUD application.

In the next tutorial we'll be learning how to add routing to our example application.

Mike C. Fletcher: RunSnakeRun for Python3 Out

$
0
0

So I finally pushed out the Python3/wxPython Pheonix compatible release of RunSnakeRun. The Python3 version has to run Python2 in order to load Python2 pstats dumps, and Meliae doesn't AFAIK support Python3 yet, so I expect I'll just drop support for it eventually. The code is now living on GitHub rather than Launchpad.

Stack Abuse: Serving Files with Python's SimpleHTTPServer Module

$
0
0

Introduction

Servers are computer software or hardware that processes requests and deliver data to a client over a network. Various types of servers exist, with the most common ones being web servers, database servers, application servers, and transaction servers.

Widely used web servers such as Apache, Monkey, and Jigsaw are quite time-consuming to set up when testing out simple projects and a developer's focus is shifted from producing application logic to setting up a server.

Python's SimpleHTTPServer module is a useful and straightforward tool that developers can use for a number of use-cases, with the main one being that it is a quick way to serve files from a directory.

It eliminates the laborious process associated with installing and implementing the available cross-platform web servers.

Note: While SimpleHTTPServer is a great way to easily serve files from a directory, it shouldn't be used in a production environment. According to the official Python docs, it "only implements basic security checks."

What is an HTTP Server

HTTP stands for HyperText Transfer Protocol. Let us think of a protocol as a spoken language like English. English has a set of rules and vocabulary. Thus, if we both understand the rules and vocabulary defining the English Language, then we can communicate in the language effectively.

Just like human beings, electronic devices too communicate with each other. They, therefore, need a 'set of rules and vocabulary' to actively pass and receive information from each other.

A protocol is a standard set of rules that facilitates successful communication between electronic devices. These sets of mutually accepted and implemented rules include the commands used to initiate the sending and reception of data, the data types to be transmitted between devices, how to detect errors in data, how successful data transfers are confirmed, and much more.

For example, when you perform a simple search using a browser, there were two essential systems involved - the HTTP Client and HTTP Server.

The client, commonly referred to as the browser, can be an elaborate program such as Google Chrome, or Firefox, but it can also be as simple as a CLI application. The client sends your request to the server, which the processes the HTTP requests and provides a response to the client. In the case of browsers, the response is typically an HTML page.

Python's SimpleHTTPServer Module

When you need a quick web server running, setting up a production-level server is a massive overkill.

Python's SimpleHTTPServer module is a labor-saving tool that you can leverage for turning any directory in your system into an uncomplicated web server. It comes packaged with a simple HTTP server that delivers standard GET and HEAD request handlers.

With a built-in HTTP server, you are not required to install or configure anything to have your web server up and running.

Note: The Python SimpleHTTPServer module was merged into the http.server module in Python 3. Throughout this article we'll be using the Python 3 version, but if you're using Python 2 you can swap out http.server for SimpleHTTPServer and it should work in most cases.

Command Line Usage

The simplest way to start up a web server that serves the directory in which the command is ran is to simply navigate to your project's directory using the terminal and run:

Python 2

$ python -m SimpleHTTPServer 8000

Python 3

$ python3 -m http.server 8000

By running this command, you'll be able to access the files in your directory through your browser at localhost:8000:

alt

As you can see, the server provides a simple directory UI in which you can access any of the files. This is the simplest way to directly serve files locally over HTTP.

Default Python Usage

For one reason or another, running this server via the command line might not suit our use-case. At times like this we can instead use the server directly in our code using the SimpleHTTPRequestHandler object. But first, we need to set it up with a socket server.

Beneath the HTTP protocol are UDP (User Datagram Protocol) or TCP (Transmission Control Protocol), which are transport protocols that handle the transportation of data from one network location to another. Since we're running an HTTP server, our application will use the TCP protocol, through a TCP Socket Address which contains an IP address and a port number. This can be set up with Python's socketserver.TCPServer, which we've implemented below:

import http.server
import socketserver

PORT = 8000

handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), handler) as httpd:
    print("Server started at localhost:" + str(PORT))
    httpd.serve_forever()

Note: The code will fail with the error AttributeError: __exit__ for Python versions < 3.6. This is because in previous versions socketserver.TCPServer does not support use with context managers (the with keyword). In these cases you need to call server_close() to stop the server.

By default, the SimpleHTTPRequestHandler serves files from the current directory and related subdirectories. As the name suggests, it is a simple HTTP request handler. Being the simple server that it is, it only allows you to retrieve data and not post it to the server. And because of this, it only implements the HTTP GET and HEAD methods via do_GET() and do_HEAD().

The parameters passed to the TCPServer represent the IP address and port number. By leaving the IP address empty, the server listens to all available IP addresses, while we've set the port to 8000. This means that it would then be accessible on localhost:8000.

Finally, httpd.server_forever() starts the server, listens, and responds to incoming requests from the a client.

The server can be started by simply executing the file:

$ python3 simple-server.py

And just like with the command line usage, we can now access the directory through our web browser:

alt

Customizing Paths

Another approach we can take is to make a custom class that extends SimpleHTTPRequestHandler and handles our requests with some custom functionality. To do this, we implement our own do_GET() function.

But before we get to that, let's say we have an HTML file that we want to serve, mywebpage.html:

<!DOCTYPE html>
<html>
<head>
  <title>Using Python's SimpleHTTPServer Module</title>
  <style>
    #rectangle {
      height: 50px;
      width: 100px;
      background-color: #00f28f;
    }
  </style>
</head>
<body>
  <h2>Rectangle served by SimpleHTTPServer</h2>
  <div id="rectangle"></div>
</body>
</html>

In order to serve this HTML from a path that isn't /mywebpage.html, we can use our custom handler to serve it on any path we want. In this example we'll just serve it on the root path, /:

import http.server
import socketserver

class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.path = 'mywebpage.html'
        return http.server.SimpleHTTPRequestHandler.do_GET(self)

# Create an object of the above class
handler_object = MyHttpRequestHandler

PORT = 8000
my_server = socketserver.TCPServer(("", PORT), handler_object)

# Star the server
my_server.serve_forever()

Again, running this script will allow us to access it through the browser:

alt

Though, there are a lot more customizations we can do with the response via the self reference, which we'll see in the next section.

Returning Dynamic HTML

A common usage of web servers is to serve dynamically generated HTML. Although this is only as very simple server, it can perform this task as well. In addition to sending dynamic HTML, we can also set different status codes, headers, etc. In the following example we set some headers and return dynamic HTML that is generated using the query parameter name:

import http.server
import socketserver
from urllib.parse import urlparse
from urllib.parse import parse_qs

class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # Sending an '200 OK' response
        self.send_response(200)

        # Setting the header
        self.send_header("Content-type", "text/html")

        # Whenever using 'send_header', you also have to call 'end_headers'
        self.end_headers()

        # Extract query param
        name = 'World'
        query_components = parse_qs(urlparse(self.path).query)
        if 'name' in query_components:
            name = query_components["name"][0]

        # Some custom HTML code, possibly generated by another function
        html = f"<html><head></head><body><h1>Hello {name}!</h1></body></html>"

        # Writing the HTML contents with UTF-8
        self.wfile.write(bytes(html, "utf8"))

        return

# Create an object of the above class
handler_object = MyHttpRequestHandler

PORT = 8000
my_server = socketserver.TCPServer(("", PORT), handler_object)

# Star the server
my_server.serve_forever()

And running this code with the URL http://localhost:8000?name=Billy will yield:

alt

Any value you set for the name query parameter will then show up on the screen! You can even omit the name query parameter and see what happens.

As you can see, creating a custom request handler allows us to manipulate the responses as much as we'd like by changing the implementation of the do_GET method and we don't have such control over our responses with the default implementation.

The same can be done with the HTTP HEAD method (via the do_HEAD() function), but since it is very similar to that of GET method we'll leave that as an exercise to the reader.

Conclusion

Python provides us with the SimpleHTTPServer module (or http.server in Python 3) that can be used to quickly and easily serve files from a local directory via HTTP. This can be used for many development or other internal tasks, but is not meant for production.

This is a great solution for local use since web servers such as Apache, Monkey, and Jigsaw are much more difficult to get set up and are often overkill for development activities.

Talk Python to Me: #241 Opal: Full stack health care apps

$
0
0
Open source has permeated much of the software industry. What about health care? This highly regulated and important industry might seem to be the domain of huge specialized software companies.

Ned Batchelder: Sleepy snake

$
0
0

My son Ben has created a mascot for coverage.py. It adorns the new coverage.py Twitter feed. I give you Sleepy Snake:

Sleepy Snake snugly tucked into a C-shaped bed

I love this drawing! I’ve always been charmed by cartoonists’ ability to capture an essence in a seemingly simple drawing. Objects are reduced to stereotypes, but with some whimsy thrown in. Ben has always had this gift: to create just the right stroke to perfectly express an attitude or feeling.

Here Sleepy is snug in his bed, covered by a blanket. Even in his custom bed, he’s too long to fit, but he’s comfortable. The pillow isn’t shaped like a real pillow, but it’s exactly our cartoon Platonic ideal of a pillow.

When I first thought of getting a mascot, I wanted it to be a snake in bed, because of the literal meaning of “coverage.” But I threw the question out to Twitter to see what came up:

I got a lot of good ideas, including blanket/quilt/duvet, and a nice quick sketch of a snake holding an umbrella.

Ben liked the idea of the umbrella, so when he started sketching ideas, he started with snakes with umbrellas:

Two different ideas for snakes holding umbrellas

But I really wanted to see bed ideas, so he drew a snake in bed. He said snakes are usually curved, so the bed should be curved. His cartoonist’s instinct was at work:

Quick sketch of a snake in bed

I said, “Hmm, flip it around, and it will look like a C for coverage.” Now he was starting to warm to the idea:

Four more quick sketches of snake in a bed

Then he switched to digital media to produce a “real” drawing of the idea:

More detailed drawing of Sleepy Snake in bed

Now all the elements were there, and it was clear that this was a winner. I suggested making the sleeping cap a little more separate from the body, Ben added detail and colors, and Sleepy was done:

Sleepy Snake snugly tucked into a C-shaped bed

I can see using this picture with a slogan underneath: “Coverage.py: rest easy.”

I’ve long used Ben’s work where I can, in my presentations. The illustrations are always a fun aspect of what otherwise might be a visually monotonous slide deck:

Ben will be graduating soon, and setting out as a freelancer. I couldn’t be more proud of his talent. He has an Instagram and a portfolio site.

Catalin George Festila: Python 3.7.5 : Using the django with javascript.

$
0
0
The Django framework can work great with javascript. I start this project a few days ago. You can start a simple Django project, see my old tutorials. I used a template for main page in my template folder named chart.html. The chart.min.js is set on base.html. The links work from the Django framework to HTML5 templates with javascript. The full project can be found on my GitHub project. See the

Codementor: Trigger Local Python App Remotely

$
0
0
Trigger an app from your phone on another machine and receive the output on your phone within seconds!

TechBeamers Python: Generate a Python Random Number

$
0
0

Here is a quick guide on Python’s random number. You can always refer to it whenever you need to generate a random number in your programs. Python has a built-in random module for this purpose. It exposes several methods such as randrange(), randint(), random(), seed(), uniform(), etc. You can call any of these functions to generate a Python random number. Usually, a random number is an integer, but you can generate float random also. However, you first need to understand the context as a programmer and then pick the right function to use. A Python Random Number Tutorial for Beginners

The post Generate a Python Random Number appeared first on Learn Programming and Software Testing.

A. Jesse Jiryu Davis: PyGotham 2019 Speaker Coaching Recap

$
0
0
I’m one of the organizers for PyGotham, the yearly Python programming conference in New York City. This year thirteen PyGotham speakers received training from opera singer and speaking coach Melissa Collom, paid for by the conference and free for the speakers. Eight of the speakers were new to the conference scene; Melissa helped them focus on delivering value to their audience, structuring their talks clearly, and speaking with conviction. All the speakers who responded to a survey said they felt more confident and they were more likely to propose conference talks again.

Janusworx: #100DaysOfCode, Days 017 & 018 – Corey Schafer Python Video Marathon

$
0
0

Chugging through.
The weekend’s been busy with health stuff.
But did watch a few videos.

39 of 127, done.

Catalin George Festila: Python 3.7.5 : Starting with kaggle platform.

$
0
0
Kaggle is the world's largest community of data scientists and the platform is the fastest way to get started on a new data science project. A good choice to use Kaggle is this feature: Kaggle provides free access to NVidia K80 GPUs in kernels. The tutorial for today is about kaggle and is new for me because I hear about this opportunity last year. This platform that hosts data science and

Janusworx: Moving Python Planet Feed, Test Post.

Viewing all 22411 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>