You are reading the article How Does The Null Function Work In C++ With Examples? updated in October 2023 on the website Benhvienthammyvienaau.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested November 2023 How Does The Null Function Work In C++ With Examples?
Introduction to C++ nullThe null function is used to assign value to the variable; this can be treated as the default value for the variable defined in many programming languages. Null functions can be used to assign value to a pointer that is not pointing to any address and contain any garbage value, so the null function will assign them a special value called ‘NULL’, which means they are now null pointer. In this topic, we are going to learn about C++ null.
Start Your Free Software Development Course
Syntax
This is very simple to assign a null value to the variable in C++; we just need to do this at the time of initialization only. This variable then turns to be treated as the Null pointer. Below see the syntax to understand this better and used while programming see below;
int main () { int *your_ptr_name = NULL; }In the above syntax, we are using the NULL value here to assign to a pointer. First, we have to define the pointer, and then we can initialize it with NULL. Sample practice syntax for more understanding see below;
int main () { int *myptr = NULL; } How does the null function work in C++?As of now, we know that we use Null functions to assign some special value to the pointer variable. By the use of this, we can give them a logical value when they are not pointing to any address in the memory. That’s why it is also known as a special value to the pointer. Also, we know that pointer holds the memory address, so if we want them to point to some other value, in that case, we can use NULL here. But we have to use this while initiation of the pointer. Now we will see one example and understand its working how it actually works; for more detail, see below;
Example:
using namespace std; int main () { int *myptr1 = NULL; int *myptr2= NULL; int *myptr3 = NULL; if(!myptr1) { cout << “demo value for myptr ” << myptr1 ; } return 0; }
In this example, we create three different pointers, and all of them point to the NULL here. So as we can see, we have initialized the value for the variable at the time of declaring the variables. After this, we are making one check here to check and print the value of the pointer. If the statement coming out to be right, then the print statement will be executed; otherwise, it will return. If we see it will assign a default value of ‘0’ to the pointer. So a null can be an integer value as well when it is not pointing to the memory address. In the if statement above, as you can see pointer is pointing to null, but here it got converted into Boolean false, and if the value for any of the pointers is not null, then it will convert into Boolean true.
So in this way, we can test our pointers as well. Null functions are nothing but a way to assign value to the pointer variable in c++. We can also do dereferencing of our null pointers in c++, but this will lead to unusual behavior of the program. this is because dereferencing means go back to the previous state where it is pointing to before initiation, but if we try to do this in our code, a null pointer still points nowhere because it has no memory address attached with it.
Points to be remembered while working with the NULL functions in c++ see below;
2) If the pointer does not point to any memory address in C++, it does not point to null; we will use NULL functions to assign them value.
3) If we assign a value to a pointer using null functions, then they will convert to Boolean true or false depending on the value they are holding. This is because the null pointer can be integer also.
Examples of C++ nullGiven below are the examples of C++ null:
Example #1In this example, we will see how to initialize the null value to the pointer using the NULL function in C++; this is nothing but the special value we can assign at the time of initialization. There is no particular syntax to do this.
Code:
using namespace std; int main () { cout<<“Demo for null functions in c++”; cout<<“n”; int *myptr1 = NULL; int *myptr2= NULL; int *myptr3 = NULL; cout << “value of the first variabel is::: ” << myptr1 ; cout<<“n”; cout << “value of the second variabel is::: ” << myptr2 ; cout<<“n”; cout << “value of the third variabel is::: ” << myptr3 ; return 0; }
Output:
Example #2In this example, we are going to see how to make a conditional statement while using a NULL pointer in your program and how they change the value while checking them. After the statement, we are assigning them a new value to the point.
Code:
using namespace std; int main () { int var1 =20; int var2 =30; int var3 =40; cout<<“Demo for null functions in c++”; cout<<“n”; int *myptr1 = NULL; int *myptr2= NULL; int *myptr3 = NULL; cout<<“Value before null functions :::”; cout<<“n”; cout << “value of the first variable is before ::: ” << myptr1 ; cout<<“n”; cout << “value of the second variable is before :::” << myptr2 ; cout<<“n”; cout << “value of the third variable is before :::” << myptr3 ; if(!myptr1){ myptr1 = &var1; cout << “value after initialization is ::” ; cout<<“n”; cout << “value of the first variable is after ::: ” << myptr1 ; cout<<“n”; } if(!myptr2){ myptr2 = &var2; cout << “value after initialization is ::” ; cout<<“n”; cout << “value of the second variable is after ::: ” << myptr2 ; cout<<“n”; } if(!myptr3){ myptr3 = &var3; cout << “value after initialization is ::” ; cout<<“n”; cout << “value of the third variable is after ::: ” << 3 ; cout<<“n”; } return 0; }
Output:
ConclusionHence we can use null functions to assign value to the variable; null values are important when our pointer is not pointing to any memory address to avoid the unusual behavior while programming, so null functions or null assigning to a pointer is used to assign a default value when they are not pointing anywhere in the memory address.
Recommended ArticlesThis is a guide to C++ null. Here we discuss how the null function works in C++ and Examples along with the codes and outputs. You may also have a look at the following articles to learn more –
You're reading How Does The Null Function Work In C++ With Examples?
How Polyfit Function Work In Numpy With Examples?
Introduction to NumPy polyfit
In python, Numpy polyfit() is a method that fits the data within a polynomial function. That is, it least squares the function polynomial fit. For example, a polynomial p(X) of deg degree fits the coordinate points (X, Y). This function returns a coefficient vector p that lessens the squared error in the deg, deg-1,…0 order. However, a RankWarning is issued by polyfit when the fit of the least-squares is poorly conditioned. This means that, as a result of numerical error, the best fit is not properly defined. The outcome can be enhanced by replacing x with x-mean(x) or minimizing the polynomial degree.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax and parameters of NumPy polyfitBelow is the syntax of the polyfit method in numpy.
numpy.polyfit( x , y , deg , rcond = None , full = False, w = None, cov = False)Parameters:
x: This parameter is array-like which is of the shape of (M,) size.
y: This parameter is array-like which is of the shape of (M,) or (M, K) size.
– Represents the M sample y-coordinate value of (x[i], y[i]).
Deg: int value which is the fitting polynomial degree.
rcond: float value which is considered as optional.
-This parameter represents the relative condition value of the fit.
– Singular numbers that are less than this relative condition to the highest singular value can be avoided.
-len(x)*ep is the default value of rcond.
-Here, ep is the relative precision of the type float.
-In most cases, 2e-16 is the value.
full: A boolean value which is optional
-This is considered as a switch that is responsible for the nature of value returned.
-If the value is false, it returns the coefficients.
– If the value is true, it returns the diagnostic data from the singular value decomposition.
w: This parameter is array-like which is of the shape of (M,) size.
-This parameter weights to put to the sample point’s y-coordinates.
-In the case of Gaussian uncertainties, 1/sigma has to be used instead of 1/sigma**2
cov: A boolean value which is optional
-This parameter returns the estimate as well as the estimated covariance matrix.
-If the value of full is true, this parameter won’t return.
Return value:
p: This parameter is an ndarray which is of shape ( deg + 1, ) or ( deg + 1,K)
-This is the polynomial coefficient which has the highest power mentioned first.
– If the value of y is 2-dimensional, the kth dataset coefficient will be set as p[:,k].
Moreover, the list [residuals, rank, singular_values, rcond] will be returned only if the value of full is true. Here, residuals are the residual of the least square fit; Rank is the scaled vandermonde coefficient matrix rank, singular value, and the value of rcond.
V: This value is a ndarray which is of shape M, M) or (M, M, K).
– This value will be returned only if the value of full is false and the value of cov is true.
How polyfit function work in NumPy?Now, let us see how to fit the polynomial data with the help of a polyfit function from the numpy standard library, which is available in Python.
Assume that some data is available in the polynomial. This is to use the function polyfit() for fitting the data available in the polynomial.
A polynomial with a degree of 1 is the simplest known polynomial.
It is mentioned using the equation y=m*x+c
Similar to that, the degree 2 quadratic equation is denoted by the equation
Y = ax**2 + bx + cIn this case, the polyfit method will find all the m, c coefficients for degree 1. This will calculate the a, b, and c coefficients for degree 2.
Below is a sample code for a simple line.
Code:
import matplotlib.pyplot as mp import numpy as np x = np.linspace( -10 , 10 , 5 ) y = 2*x + 5 mp.plot( x , y , 'o' )If the function polyfit() is also added, code changes as shown below.
import matplotlib.pyplot as mp import numpy as np x = np.linspace( -10 , 10 , 5 ) y = 2*x + 5 coeff = np.polyfit(x,y,2) xn = np.linspace(-20,20,100) yn = np.poly1d(coeff) mp.plot( xn,yn(xn),x,y,'o')Note:
In some cases, fitting polynomial coefficients is intrinsically badly conditioned. For example, it is during the cases when the polynomial degree is higher or the interval of sample points is poorly centered. Moreover, the quality of the fit has to be always checked in the cases mentioned above. If the polynomial fits are not that satisfactory, a good alternative will be splined.
Examples of NumPy polyfit Example #1Python program to fit a polynomial function
Code:
import numpy as np import matplotlib.pyplot as mp np.random.seed(12) x = np.linspace( 0, 1, 25 ) y = np.cos(x) + 0.3*np.random.rand(25) p = np.poly1d( np.polyfit(x, y, 4) ) t = np.linspace(0, 1, 250) mp.plot(x, y, 'o', t, p(t), '-') mp.show()Output:
In this program, first, import the libraries matplotlib and numpy. Set the values of x, y, p, and t. Then, using the values of this x, y, p, and t, plot the polynomial by fitting it.
Example #2Python program to fit a polynomial function of a simple line
Code:
import numpy as np import matplotlib.pyplot as mp np.random.seed(12) x=np.linspace(-20,20,10) y=2*x+5 coeff = np.polyfit(x,y,2) xn = np.linspace(-20,20,100) yn = np.poly1d(coeff) mp.plot( xn,yn(xn),x,y,'o')Output:
In this program, also, first, import the libraries matplotlib and numpy. Set the values of x and y. Then, calculate the polynomial and set new values of x and y. Once this is done, fit the polynomial using the function polyfit().
ConclusionNumpy polyfit() is a method available in python that fits the data within a polynomial function. Here, it least squares the function polynomial fit. That is, a polynomial p(X) of deg degree is fit to the coordinate points (X, Y). In this article, different aspects such as syntax, working, and examples of polyfit() function are explained in detail.
Recommended ArticlesThis is a guide to NumPy polyfit. Here we discuss How polyfit functions work in NumPy and Examples with the codes and outputs. You may also have a look at the following articles to learn more –
How Does Export Work In Docker? (Examples)
Introduction to Docker Export
Docker export is a command that is used to export the container’s file system as an archive, i.e., tar, that can be imported as required as a Docker image using the Docker import command. It includes all the files and folders created in that container. However, it does not export the data of volumes mounted on that container. It is very useful to create a single layer or flat Docker image to improve performance or to share the Docker image with others without the need for the Docker registry. It is like creating a template, as we create a template of VMs to speed up the process.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax:
docker export [OPTIONS] container
Options:
-o, –output – It is a string type and is used to write the output to a file instead of STDOUT.
Command:
docker export --help
Explanation:
We use ‘–help’ to know about the ‘docker export’ as shown above. We can see that this command has only one option, ‘-o’, for redirecting the output to a file.
How Does Export Work in Docker?
It takes at least one argument, that is, a container name or container ID. When we run this command, it saves the container’s file system as an archive. It creates a flat Docker image that makes the Docker image slightly smaller in size. However, it lost its history and metadata, which means we cannot perform any rollback to a previous layer if we import a Docker image using any exported tar file.
Below is a snapshot of a folder structure of an exported container:
Command:
tree -L 1 alpine-export
Output:
Explanation: We export a Docker container in a tar file and extracted the tar file in a folder ‘alpine-export’. The above example is the tree structure of that folder.
Example to Implement Docker ExportBelow are the examples:
Scenario 1: Update any File of the Docker ImageWe have built an nginx Docker Image, and a container is running using this Docker image; however, when we browse the web application, we realize that something is missing on the homepage. We need to update the homepage and create a new Docker image but building the image from scratch using Dockerfile is going to take more time, so we are going to make the changes in the chúng tôi file when the container is running, and we export the container and then import it as a Docker image. So let’s get started:
1. Below is the snippet of Dockerfile and chúng tôi files:
index.html
Code:
Dockerfile
CMD [“nginx”, “-g”, “daemon off;”]
2. Build the docker image named ‘my-nginx’ using the below command:
docker build -t my-nginx
Note: if Dockerfile is not in the current working directory, then use the full path of the Dockerfile.
Output:
3. Run a container using the above Docker image as below:
docker run -d -p 80:80 my-nginx
Output:
4. Now, let’s assume that we got a requirement to change the background color of the heading ‘Example of Docker Export’ to blue, so we will update the chúng tôi file in the running container and export it as an archive using the below command:
Command:
sudo docker exec -it 44 sh
Output:
5. Export the running container after making the changes using the below command and import it as a Docker image named ‘my-nginx:v2’;
Command:
docker run -d -p 8081:80 my-nginx:v2
Output:
Explanation: Run a new container using the imported Docker file to verify the changes are successfully applied as expected. When we browse the default page, we can see that the background color of the heading has been changed to blue in the below image.
Scenario 2: Create a Single Layer Docker ImageWhen we create a Docker image, it has multiple layers, as each instruction in a Dockerfile creates a layer while building the image. If we want to create a single-layer Docker image to enhance the performance of the container, we export the container and import it as a Docker image as shown in the below steps:
1. Check the layers of any Docker image using the below Command:
Syntax:
Command:
docker image history my-nginx
Output:
2. Now, again, run a container using this image and export it as an archive:
Command:
Output:
3. Import the exported archive file or tar file with the command and message below and check the history of the newly imported Docker image:
Command:
docker image history my-nginx:v3
Output:
Explanation:
In the above snapshot, only one layer shows after importing the exported archive. It helps to improve the performance. However, it is not recommended by Docker as Docker encourages building a multilayer Docker image to use the cache function of the image-building process.
Advantages of Docker Export
Speed: Docker export is faster than rebuilding the Docker image if any minor changes are required.
Image Sharing: As we know, if we want to share the Docker image, we need to push it to a registry; however, we can use Docker export to export it as an archive, and we can share it with others like we share files.
Performance: When we import the exported library using Docker import, it creates a single-layer Docker image that improves the performance of the container.
ConclusionDocker export is a command-line tool to export any container as an archive. The archive contains a regular Linux filesystem with all the container data except data of mounted volumes. Docker export and docker import both commands primarily work together.
Recommended ArticlesWe hope that this EDUCBA information on “Docker Export” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
Examples On How Does Laravel Distinct Work?
Introduction to Laravel Distinct
Web development, programming languages, Software testing & others
$hCat = Hotels::select( DB::raw('DISTINCT(hoteltype_id)'), What is Laravel Distinct? How does Laravel Distinct Work?One has to be careful while working with Laravel DISTINCT because it may not always provide you with the exact return. A turn around for that would be using the GROUPBY option, which essentially groups all the relevant search results and returns the same. One of the drawbacks of using the DISTINCT query is that if we are to request for multiple rows containing similar data that has to be merged together for the final output, the resultant will not be what we would expect it to be. Hence, under these circumstances, as mentioned previously we would be using the GROUPBY query.
For Example:
The table structure looks like this:
And I would want to have an output similar to this:
The Laravel Query Builder that has to be used for such an event would be:
However, for searches where multiple merges do not take place, the DISTINCT query works perfectly fine.
Hence, the important thing to remember here is the difference between GROUPBY and DISTINCT queries. Both return values, albeit, differently. The SELECT DISCTINCT query is used to return values which are different from each other.
The SELECT GROUP BY query is used to find values that are the same across multiple rows. Also, the GROUP BY query is used in conjunction with other functions like (COUNT, MAX, MIN, SUM, AVG), whereas, the DISTINCT QUERY is used as a standalone function.
Examples of Laravel DistinctA few examples using the Laravel DISTINCT query to ease the understanding:
1. Want to run a query which is going to return a value with No Duplicates.
The SQL query is going to be: SELECT DISTINCT column_name FROM table_name; The LARAVEL ELOQUENT query would beThe LARAVEL ELOQUENT query would be
3. A trickier example would be to display value ignoring any null values. The SQL query would be
SELCT DISTINCT meta_value FROM 'wp_postmeta'The LARAVEL ELOQUENT query would be.
SELECT Products.* FROM ------ Get all the distinct product_id’s of ordered products. ------ (i.e. only show each product once, regardless of how many ------ times it has been ordered. (SELCT DISTINCT product_id FROM orders) AS purchased_products ----- join back onto product table to show the full details of only ----- those products that have been ordered. INNER JOIN products ON purchased_products.product_id = products.products_idWhat this does is identifies the values that need to be queried and returns them as asked. Please note that in this case an additional functionality like INNER JOIN.
5. A simpler example related to the DISTINCT query would be:
The similar SQL query to this would be:
SELECT DISTINCT user_id FROM picks WHERE weeknum = 1Laravel unveiled a painless method of coding and simplified the logic. Hence particular to the DISTINCT query the bare syntax would ideally look like:
It does not confirm to the above kernel.
The correct syntax would be:
A couple of other variations would be:
Laravel 5 unveiled an addition of the UNIQUE query. This has a similar functionality to DISTINCT. Furthermore, it accepts the $Key argument which is optional. This restricts the items which are to be returned.
An example would be:
public function unique( $key = null, $strict = false );Over the years the PHP LARAVEL framework has become one of the most trusted tools for web development. The reasons are plenty.
It integrates with the mail services.
The integration with the tool makes building web applications faster and smoother.
Automation testing is one of the quickest in Laravel.
It is for these reasons, that the market is replete, with web applications based on the LARAVEL platform.
ConclusionThe DISTINCT query in the ELOQUENT LARAVEL framework is an important function. However, owing to a few shortcomings, this query limits its uses. LARAVEL though has quite a few other queries which does an equally commendable job, of returning distinct values. This does not demean the DISTINCT query by any means. It is an essential cog in the wheel.
Recommended ArticlesWe hope that this EDUCBA information on “Laravel Distinct” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
Access Modifiers (Specifiers) In C# With Program Examples
What is Access Modifier (Specifier) in C#?
Access Modifiers or Access Specifiers in C# are the keywords used to define the visibility of a class property or method. It is used when you don’t want other programs to see the properties or methods of a class. Access modifiers restrict access so that other programs cannot see the properties or methods of a class.
There are 6 types of access modifiers in C#:
Private
Public
Protected
Internal
Protected Internal
Private Protected
In this tutorial, you will learn-
We will learn about the main access modifiers in C# with program examples as explained below.
Private Access Modifiers in C#When Private access modifier is attached to either a property or a method, it means that those members cannot be accessed from any external program.
Example of Private Access ModifierLet’s take an example and see what happens when we use the private access modifier.
Let’s modify the current code in our chúng tôi file. In the SetTutorial method, let’s change the public keyword to private.
Now let’s switchover to our chúng tôi file. You will notice that there is a red squiggly line under the SetTutorial method.
Since we have now declared the SetTutorial method as private in our Tutorial class, Visual Studio has detected this. It has told the user by highlighting it that now this method will not work from the chúng tôi file.
C# Public Access ModifiersWhen Public access modifier is attached to either a property or a method, it means that those members can be accessed from any external program. We have already seen this in our earlier examples.
Example of Public Access ModifierSince we have defined our methods as public in the Tutorial class, they can be accessed from the chúng tôi file.
Protected Access Modifiers in C#When Protected access modifier is attached to either a property or a method, it means that those members can be accessed only by classes inherited from the current class. This will be explained in more detail in the Inheritance class.
C# Internal Access ModifiersWhen an Internal access modifier is attached to either a property or a method, those members can be accessed only by an internal program but not by an external program.
C# ConstructorC# Constructors are used to initializing the values of class fields when their corresponding objects are created. A constructor is a method which has the same name as that of the class. If a constructor is defined in a class, then it will provide the first method which is called when an object is created. Suppose if we had a class called Employee. The constructor method would also be named as Employee().
The following key things need to be noted about constructor methods
The C# default access modifier for the constructor needs to be made as public.
There should be no return type for the constructor method.
Example of C# ConstructorLet’s now see how we can incorporate the user of constructors in our code. We will use constructors to initialize the TutorialID and TutorialName fields to some default values when the object is created.
Step 1) The first step is to create the constructor for our Tutorial class. In this step, we add the below code to the chúng tôi file.
Code Explanation:-
We first add a new method which has the same name as that of the class. Because it is the same name as the class, C# treats this as a constructor method. So now whenever the calling method creates an object of this class, this method will be called by default.
In the Tutorial constructor, we are setting the value of TutorialID to 0 and TutorialName to “Default”. So whenever an object is created, these fields will always have these default values.
Now let’s switchover to our chúng tôi file and just remove the line, which calls the SetTutorial method. This is because we want just to see how the constructor works.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoApplication { class Tutorial { public int TutorialID; public string TutorialName; public Tutorial() { TutorialID=0; TutorialName="Default"; } public void SetTutorial(int pID,string pName) { TutorialID=pID; TutorialName=pName; } public String GetTutorial() { return TutorialName; } static void Main(string[] args) { Tutorial pTutor=new Tutorial(); Console.WriteLine(pTutor.GetTutorial()); Console.ReadKey(); } } }Code Explanation:-
The first step is to create an object for the Tutorial class. This is done via the ‘new’ keyword.
We use the GetTutorial method of the Tutorial class to get the TutorialName. This is then displayed to the console via the Console.WriteLine method.
If the above code is entered properly and the program is executed, the following output will be displayed.
Output:
From the output, we can see that the constructor was indeed called and that the value of the TutorialName was set to “Default”.
Note: Here the value “default” is fetched from the constructor.
Summary
C# Access Modifiers or Access Specifiers are used to define the visibility of a class property or method.
When Private access modifier is attached to either a property or a method, it means that those members cannot be accessed from any external program.
When Public access modifier is attached to either a property or a method, it means that those members can be accessed from any external program.
When Protected access modifier is attached to either a property or a method, it means that those members can be accessed only by classes inherited from the current class.
When an Internal access modifier is attached to either a property or a method, those members can be accessed only by an internal program but not by an external program.
C# Constructors are used to initializing the values of class fields when their corresponding objects are created.
How Does Redirect Function Works In Flask
Introduction to Flask redirect
Flask redirect is defined as a function or utility in Flask which allows developers to redirect users to a specified URL and assign a specified status code. When this function is called, a response object is returned, and the redirection happens to the target location with the status code. When a website is visited, server receives a request and after processing responds to the request with a three-digit code known as the HTTP code. In a programming world this status code that is returned as a response is known as Errors. Errors and redirect function goes hand in hand.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax of Flask redirect1. Importing the redirect and abort function.
from flask import redirect, abort2. Instantiating of Flask redirect.
Here,
3. Using abort function to exit from the code loop, in conjunction to redirect.
Here the code refers to a set of codes that will generate some error, as applicable, and stop any further execution of the application.
How does redirect Function Works in Flask?Redirect function is one of the big three route resolutions in Flask. We know that any Flask function will have the concept of serving contents through multiple URLs. Routes are the URL where the content is served, and views refers to the content in them. Also, another piece is that the route decorator enables users to list the endpoint along with added functionality of methods that one would expect would happen in the endpoint. Now assume there are multiple users, and we need to create a dynamic URL by their username. For this we can use the concept of dynamic routes. With the dynamic routes and the variable rules, the dynamic URL is created and can be accessed. Now that the route piece is clear, we would need to understand the view responses. The view responses in a Flask application happens in three common ways namely, page template, response and redirecting. We will park the first 2 for some other article, but here we will talk in depth about the redirecting.
In this function we send in a string which corresponds to the path where the user will be redirected to. This string can be either a relative path, an absolute path or even an external URL. The function searches for the corresponding match to the string passed as an argument and correspondingly renders the required template and puts it in front of the user.
Another variation of the redirect function, and the most widely used one, as it is one of the best practices in terms of programming is to route by names rather than by sending in the path of the redirect URL. For this we use a built-in function known as url_for( ) discussed in detail in another article. Onto this we send the name of the view function is passed, the url_for( ) function is responsible for converting the name of the view function to the corresponding URL pattern. One added benefit we would achieve out of this is to prevent any broken links between pages.
Now as a part of redirection, there are status code which can be easily used for communication to the server.
Below is the list of status and what they refer to:
Status Code Messaging Significance
300 The code refers to the message that indicates requests has more than one response.
301 This is to indicate that the resource is moved permanently.
302 This the by default message, denoting that the resource is found.
303 This is to inform that the response doesn’t redirects to something new, but another page.
304 This is o inform that retransmission of the resources is not required.
305 This is a depreciated code, typically instructing the server to connect to proxy.
306 This code is no longer used now.
307 In contrast to the 301, here the resource has been moved temporarily.
Now let us look at one flask application with a redirect capability.
Examples of Flask redirectGiven below are the examples of Flask redirect:
Example #1Sample code for redirect functionality.
Syntax:
from flask import Flask, redirect, url_for appFlask = Flask(__name__) @appFlask.route("/home") def home(): return redirect(url_for('LoginPage')) @appFlask.route("/LoginPage") def LoginPage(): return "You are redirected to Login Page" if __name__ == "__main__": appFlask.run(debug=True)Output:
Example #2Using abort function to portray unauthorized login.
from flask import Flask, redirect, url_for, abort appFlask = Flask(__name__) def home(user): if user == 'admin': return redirect(url_for('LoginPageAdmin')) else: abort(401) @appFlask.route("/LoginPageAdmin") def LoginPageAdmin(): return "You are redirected to Login Page" if __name__ == "__main__": appFlask.run(debug=True)Output:
For admin login:
For another user login:
Here we see that when the URL has an argument named as admin, we are redirected to the corresponding URL for admin. In case of any other user, we get an unauthorized access pertaining to the fact that the user is unauthorized for redirect.
ConclusionTo conclude, in this article we have looked at the simple way of working for redirect function and also how abort function goes hand in hand with the redirect function. Usage of this functionality is left to readers to try out these concepts in Flask applications. Also, the list of error codes here will come in handy for our readers to use for correct functionality.
Recommended ArticlesThis is a guide to Flask redirect. Here we discuss the introduction, how does redirect function works in flask? and examples respectively. You may also have a look at the following articles to learn more –
Update the detailed information about How Does The Null Function Work In C++ With Examples? on the Benhvienthammyvienaau.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!