Design a site like this with WordPress.com
Get started
Featured

Serve React From Django in 10 mins

In this tutorial we will go through integration of django and react in just 10 min

There aren’t many tutorials clearly identifying changes required in django app to run with a react app. Most tutorials seem complex and steps mentioned are often are not necessary. We will look at steps to integrate django rest service with a react web application and all this will be served from the django project. We will also demonstrate hot deployment of react changes when working in django when we are developing and there are constant changes that we would want to make to the UI pages and look at result of those changes. You wont believe, it hardly takes 10 mins.

I am making a few assumptions here.

  1. Django is installed
  2. DjangoRestFramework is installed
  3. Basic understanding of Django
  4. npm and npx are installed
  5. PyCharm IDE – Not mandatory but recommended

The above installations are fairly simple and extremely easy. We wont go into details of those installations as you would find bunch of those on google search

The code for this project is present @ https://github.com/letsblogcontent/Python/tree/master/DjangoReactProject

Steps

Step 1Create Project

Lets begin by creating a django project. As you can see below, I have created a new django project “DjangoReactProject

If you open the directory, you should find below files/directories created by django

Step 2Create App

Next up we are going to create a new Django app, lets call this as service as we are going to serve rest calls from this service.

Step 3Register the app & Create url mapping

I have opened my project in pycharm but you may as well edit the files in any editor.
The current project structure should look like

Next is to register the service app to the project, this is done by adding the app config in the settings.py file of the project.

Now that we have registered our app to the project. Lets add a function in the views.py file of our app. This function is what we will respond from the service app for our project. If you see below In the views.py file, I have added a new function which responds with a dummy json string having name and city attributes.

Next, Create a urls.py file in the our service app and create a mapping between a default http request with the function we have created just now.

Step 4 – Test the url

Now lets run our project to see if we receive response for our mapped url. Run the command “python manage.py runserver” and you should see below console output.

Now navigate to the url http://localhost:8000/api” to see below ouput on your browser.

Step 5 – Create a React App with npx

Lets create a react app inside our project folder with npx. This should take a few mins. This will download all the packages required for react. Once this is complete, You should see directory structure like below

Steps 6 – Add Component and Update App.js

Lets create a new directory named “components” under src in our react app just created and create a new file “MyComponent.js” and add below content .

This is a very basic code in React and most of you must already understand what is going on here.

We have created a new React component and initialized state of the component with name and city. In the render function, we are passing an html with the content of the state inside a div element. We have overriden the component “componentDidMount” in which we are making an http request to the url we created in Django and setting it into the state of the component

import React from 'react';
import ReactDOM from 'react-dom';

class MyComponent extends React.Component {
    constructor(){
       super();

        this.state = {
            name: null,
            city: null
        };
    }

    componentDidMount(){
        fetch('/api/')
         .then(response => response.json()
         .then(data => {
                            this.setState({ name : data.name });
                            this.setState({ city: data.city });
                        }
               ));
    }

    render() {
       return (
       <div>
       <div> {this.state.name} </div>
       <div> {this.state.city}  </div>
       </div>
       );
    }
}

export default MyComponent;

Now lets add this component to App.js file in the react application under the src folder. React must have pre-populated some content. Remove all of that and copy below code to the App.js file

import React from 'react';
import logo from './logo.svg';
import './App.css';
import MyComponent from './components/MyComponent.js'

function App() {

  return (
    <div className="App">
      <h1>React App - Served from Django</h1>
      <MyComponent/>
    </div>
  );
}

export default App;

Step 7 Run the react build

Navigate to the react app folder and create react build by running npm run build. A build directory will be created after successful execution of the build with all the files required for the react app. The starting point of the application being index.html

Step 8 – Configure Django to serve react build

We now just need to point Django to the build directory of react so that it starts serving from there.
In our DjangoReactProject directory present in the root of our project, navigate to settings.py

Find Templates in the settings.py file and add the build directory of our react application as show in the screenshot in the DIRS. We are telling python where to find templates in the react application

In the same file add a new variable “STATICFILES_DIRS” if not present already and add variable which points to the static content of the react app as below

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'webapp/build/static')]

In the urls.py file of the DjangoReactProject include below path in the urlpattern and import TemplateView to render index.html from our react app

from django.views.generic import TemplateView
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('service.urls')),
    path('', TemplateView.as_view(template_name='index.html'))
]

Now run our django server and it should start serving our react application and call the rest service /api to render the response

 C:\DjangoReactProject>python manage.py runserver

This should deploy our django app with react @ http://localhost:8000/. Navigate to the url to see below page.

Step 9 – Hot Deployment

So the above is fine structure to deploy our react application once all of our react code is ready, but during development it is going to be very difficult to always having to build our react app for small changes in our react app. So to overcome this, we have to make a small change in the react app so that when we are developing all the requests are redirected to django app.

So when we are developing we will run the inbuild react server to server our react application, which will redirect calls to django server when required.

To configure this we just need to add proxy configure in the package.json file of the react app.

Here we have given the address of server

"proxy": "http://127.0.0.1:8000",

Once this is done, lets run the react server by running command “npm run start”. This will start the react application @ http://localhost:3000/ and you should see the below page. Any changes to react will be hot deployed for development.

At this point any changes in the Django or the react app are hot deployed and we can make changes to quickly see the results.

Ohh. We have still not reached Step 10, that was really easy. Let us know if you have any queries or like the page if you have like this tutorial, post any feedback if you have. Thank you!

Advertisement
Featured

P4 – Django Rest – Class Based Views

In the previous tutorial we have seen how to create rest api and add GET, POST request using independent functions. Now we will see how to create class based views. So with a class based views we can have more separation of concerns of different parts of our application wrapped within a class serving different http requests.

Step 1

It is very simple and aimed at reducing and creating reusable code. Lets create model having seller information as below in the models.py file.

products/models.py

Step 2

Now create a serializer class for the Seller class in the serializer.py file as below

serializer.py

Step 3

Now in the views.py file we define a new class “SellerView” which extends it self from the APIView class. The APIView class is a wrapper class which provided additional standard handling of the various http requests thus abstracting us from the finer details and we can write our functionality faster and in an efficient way. Notice that we have created two methods, one for GET request and one for POST request. The framework will automatically invoke respective methods based on the HttpRequest.

Ignore the additional imports for generics and mixins, we will need them later, we can ignore them for now.

Also note that we have used the format variable and set it None, it means that the function can handle multiple formats. Res t of the code is pretty standard that we have seen in earlier tutorials

Step 4

Now we need to map url pattern to this new Seller class view. See below screenshot where we have added the seller url pattern, we need to pass the as_view return unlike functions itself that we passed earlier with function based views and its done.

Step 5

Its time to test. Lets open the ARC and add one new seller to the rest service and then retrieve it back.

Add new seller to the service
Retrieve the seller back

GIT Project link – https://github.com/letsblogcontent/SampleRestProject

Spring Config Server – (search paths)

in the previous post sprig config server we have seen how to start a spring config server with a sample application config.

Let us see some more variations that spring allows us with spring config server.

The spring config server allows for using placeholders {application} and {profile} .

With this flexibility we can configure one repository per application against one repository for all the applications as we did in the previous post, let us see how. We will change what we did in earlier post so I will make changes to the same project to demonstrate the feature.

Let us first create two repositories for two applications “my-app-1” and “my-app-2”

Below I have created and initialized the first repo

add two files into this directory as application.yml and application-dev.yml

application.yml

app:
 name: my-app-1

application-dev.yml

app:
 name: my-app-1-dev

commit this file into the git repo with “git add .” and “git commit”

Now, similarity create another repo in the same root directory with name “my-app-2”, in my case it was “C:\Users\<user>\git”

So we have two repositories for the two apps now, one with name “my-app-1” and another with “my-app-2”. Now lets add this config to the server application config.

Navigate to the configuration of the config-server and update the git url to use application placeholder like below.

spring:
  application:
    name: my-config-server
  cloud:
    config:
      server:
        git:
          uri: file://c://Users/<user>/git/{application}

Now lets start the config server and see the application in action
browse the url – http://localhost:8001/my-app-1/dev to view dev profile and http://localhost:8001/my-app-1/master to view the master or the default profile. Similarly you can use http://localhost:8001/my-app-2/dev or http://localhost:8001/my-app-2/master for the “my-app-2” config.

With the placeholder “{profile}” we can also create various other combinations. For e.g. we can create directories within the application repo for each of different profile instead of the suffix used in our example or in case of single repository for all the applications, we can use profile for dev and test or any folder of your choice within the repository.

You can also use the placeholder {application} or {profile} in searchpath config which basically is instruction to the spring config server on the whereabouts of your app config.

I have created two directories under the single repository configuration from my previous post and instead of having the config with the app name into the root directory, now I have created 2 directories for each app within the same root directory like below

I will have to also update the config-server application configuration to instruct on this new application locations.

spring:
  application:
    name: my-config-server
  cloud:
    config:
      server:
        git:
          uri: file://c://Users/<user>/git/app-config
          searchPaths: '{application}'


server:
  port: 8001


Now restart the server and browse urls – http://localhost:8001/my-app-1/master&#8221; or http://localhost:8001/my-app-2/master&#8221; or their dev profiles. You should be able to see the change consistent with the expectations. Spring config server will now pull the configuration from the application directories.

Spring Config Server

Spring config server is one of the very important module of spring cloud to basically externalize application configuration. In a microservice architecture, spring config server provides a central place where all the microservices can look for the application configuration. It has support for multiple applications and environments.

We will look into a sample spring server application supported by git as storage for the application config. Although we can use a different form of storage but then it will require some additional changes.

Navigate to spring https://start.spring.io/ and add config server to dependencies, provide the artifact details as per the screenshot below or choose one of your own and click on generate


This will download a zip to you local filesystem. Unzip the directory and import/open the project into your favorite IDE. I am using Intellij.

The imported project will look like below.

Take a look at the pom.xml, it will have dependency for spring cloud config server apart from the spring boot starter dependency. Also it will import spring cloud dependencies using the maven import pom.

<dependency>
 <groupId>org.springframework.cloud</groupId>
 <artifactId>spring-cloud-config-server</artifactId>
</dependency>

delete the application.properties file and create application.yml instead. Set the application name and set the server port to 8001 as below

spring:
  application:
    name: my-config-server

server:
  port: 8001


let us create a git repository on our local and then migrate it on to the github.

create a directory app-config and navigate into the directory on command line and fire command “git init”

create a file inside the app-config directory. lets say myapp.yml and add a property like below

app:
 name: my-first-app

Now add this file to the git repo using git add and then git commit as below

let us add reference to this repo in our spring boot application. To do this, just open the application.yml file use the spring.cloud.config.git.url to the repository we created like below

spring:
  application:
    name: my-config-server
  cloud:
    config:
      server:
        git:
          uri: file://c://Users/Amey/git/app-config

Now to initialize our spring boot application as config server, we have to add the annotation @EnableConfigServer to our main class like below

@SpringBootApplication
@EnableConfigServer
public class MyConfigServerApplication {
	public static void main(String[] args) {
		SpringApplication.run(MyConfigServerApplication.class, args);
	}

}

Now we are ready to run the spring config server application. Right click on the class and run the application.

Now on the browser, navigate to the url http://localhost:8001/my-first-app/master&#8221; to see spring config server responding as below


Here the spring has assumed the default profile as master or assumed that the branch is the default profile.

Now lets add another file to the git repo with name “my-first-app-dev.yml” and add the following property to the config

app:
 name: my-first-app-dev

lets go back to the browser and now instead of master lets use dev as the profile in the url and check what the server responds with ( http://localhost:8001/my-first-app/dev“) .

Now our spring config server has done the magic trick. It has returned us the dev profile for our application. if you see the app.name is now my-first-app-dev and also we did not restart the server. Spring has picked up the change and responded with new profile we just added.

In the next blog, we will see various other configurations that we can use with spring config server.

Configure your Git Bash with Github (Windows)

Step 1 Open your git bash terminal (Intall from here https://git-scm.com/downloads)

Step 2 Generate a key pair using ssh-key gen
ssh-keygen

Step 3 Add the generated private key to you ssh agent with “ssh-add”

Step 4 Login to your github account and navigate to settings

Step 4 On the settings page click on “SSH and GPG Keys” and click on “New SSH key”
Step 5 Add the contents of “.pub” file generated in our 2nd step in “key ” text area and provide a name in the “Title text” and click on “Add SSH key”

Step 6 Your setup is done. Now create a repository and try cloning it with git clone from your git bash terminal,

LocalDate class in java

Java 8 has introduced various classes to work with date and time objects. Lets see today LocalDate class in java 8 and how can we use it in our day to day coding.

Lets look at few of the useful methods provided and understand how it works

System.out.println("My Current TimeZone >> " + ZoneOffset.systemDefault());
System.out.println("Is same as zone >>"+LocalDate.now(Clock.system(ZoneOffset.of("+05:30"))));
		
		
System.out.println(LocalDate.now());
System.out.println(LocalDate.now(Clock.systemUTC()));
System.out.println(LocalDate.now(Clock.system(ZoneOffset.of("+10"))));
System.out.println(LocalDate.now(Clock.system(ZoneOffset.of("+0530"))));

line 1, will print my current timezone

line 2, will print my current timezone converted into UTC offset.

line 3, “LocalDate.now” will print my current date in my timezone.

line 4, will print current date in UTC

line 5, will print current date in time zone offset at +10 from UTC

line 6, will print current date in time zone offset at +05:30 from UTC

Lets look at the output

My Current TimeZone >> Asia/Calcutta
Is same as  >>+05:30
2021-08-06
2021-08-06
2021-08-07
2021-08-06

If you see, the date in time zone +10 is different than in UTC timezone or with offset +5:30. It is also possible to provide negative value of offset as well to the ZoneOffset method.

The “now” methods returns an object of type LocalDate. There are various other utility methods to find month, day of month, day of week, year etc.

Lets look at one useful method

System.out.println(LocalDate.now().get(ChronoField.DAY_OF_MONTH));
System.out.println(LocalDate.now().get(ChronoField.YEAR_OF_ERA));

So if you see above, one of the method accepts a class called TemporalField. ChronoField enum has various temporal fields that can be passed to this method. Output of the above is as below

6
2021

So day of month is 6 and year is 2021. If you pass any temporal field which the LocalDate does support then it will throw “UnsupportedTemporalTypeException”

So for a date object which does not have time, if you ask for temporalfield “ChronoField.AMPM_OF_DAY” then it will throw ” UnsupportedTemporalTypeException”

There are various other utility methods to add days, months, minutes to the current LocalDate object.

Lets look at how can you convert a simple string into a LocalDate object.

LocalDate.from(DateTimeFormatter.ofPattern("yyyy-MM-dd").parse("2021-01-01"));

Here I have used “DateTimeFormatter” to the utility class as formatter and passed the expected date string to the parse method of DateTimeFormatter. This will try to convert the string to the format and return us the LocalDate Object. It will throw Parsing exception if you do not provide correct string to the parse method.

I hope this will help you in some or other way. Thank you !

How to install Maven on Windows Machine

  • Download zip file and unzip it from below location

https://maven.apache.org/download.cgi

  • Add JAVA_HOME and MAVEN_HOME in environment variable.

For java installation follow below links

Install Java
Install java with exe
  • Add maven path in environment variable

Choose options based on your need .Most of types in secure environment like company you only have access to variable linked to your account only.

  • Verify Maven
  • Open Command prompt and type “mvn -version

How to setup your Java Environment from JDK Zip file?

Please follow below steps

1 Download JDK Zip file

2 Unzip File on any location on your hard disk

3 Configure environment variable

Type Environment Variable in search bar

Choose options based on your need .Most of types in secure environment like company you only have access to variable linked to your account only.

Follow below steps in sequence

4 Verify JDK version

Open Command Prompt

Type Below Command

java -version

This will look like below one

How to setup your Java Environment from installer(exe)?

Please follow below steps

1 Download JDK from below URL

https://www.oracle.com/in/java/technologies/javase-downloads.html

2 Download it as EXE file

3 Install JDK on your local machine by following steps mentioned in installer

4 Verify JDK version

Open Command Prompt

Type Below Command

java -version

This will look like below one

What is Apache beam?

Apache beam is open source and unified programming language that will help to process stream based and batch based data.

Lets understand each and every word

Unified programming language : This means you can code once and run on different runner ,Runners means like spark cluster or flink cluster

Stream Based data: The data which is continuously flowing ,simple example is cars running on road ..if you want to count them there is not fixed window for it they are runing on road day and night.

This data consist of data like sensor data ,IOT device data,continious feed from solace,MQ,Kafka

Batch Based data: This is finite data and it could be grouped by number or timeline easily. E.g. number of cars going in 1 hour. This kind of data can be generate by any system on daily basis and sent in batches for example trading data for entire day.

Different Runners Supported by Apache Beam

  1. Spark Runner
  2. Flink Runner
  3. Samza
  4. Nemo Runner
  5. Google data flow
  6. hazzle cast runner

You can code with beam in different languages

Below are languages supported in beam

  1. Java
  2. Python
  3. Go

You need to download SDK for each language to code in apache beam, We will be going to see java SDK for our tutorials

Python – Variable

In python variable get declared when you assign value to variable first time

x=10;  #x will be integer
y='abcd' #y will be string
print(x)
print(y)

This will declare x as integer and y as string and you can also check data types as coded in below sample.

Find Type of Variable

you can use “type” keyword to find type of variable

Below is sample code and output

In Python variable names are case sensitive

x=10;  #x will be integer
y='abcd' #y will be string
X= 'Ten'

print( 'Value of small x=' ,x)
print('Value  of y=',y)
print('Value  of X=', X)

print( 'Type of small x=' ,type(x))
print('Type of y=',type(y))
print('Type of X=', type(X))

Output of this code will be as below

Value of small x= 10
 Value  of y= abcd
 Value  of X= Ten 
 Type of small x= <class 'int'>
 Type of y= <class 'str'>
 Type of X= <class 'str'>