Trending March 2024 # How Json Works In Redshift With Examples? # Suggested April 2024 # Top 6 Popular

You are reading the article How Json Works In Redshift With Examples? updated in March 2024 on the website Moimoishop.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 April 2024 How Json Works In Redshift With Examples?

Definition on Redshift JSON

Redshift JSON has limited support while working with the JSON documents in redshift, basically, there are three types of options available in redshift to load the data into table. First option is we can convert the JSON file into relational model before loading data into the redshift, to load the data using this options we need to create the relational target database. Second option is load all the JSON documents in redshift table and query those documents using JSON functions, there are multiple JSON function available in redshift to query the data of JSON documents.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax

Below is the syntax of JSON in redshift are as follows.

2) Select json_function (name_of_json_column,) group by, order by

Parameter description syntax of redshift JSON.

1) JSON function – This is the function which was we have using with JSON data to retrieve from JSON column. There are multiple JSON function available in redshift to query the JSON data. We can retrieve the JSON column data using JSON function in redshift.

2) Select – Select command is used with JSON function to retrieve data from table by using the clauses and conditional operator.

3) Name of column – This is the name of JSON data column which was we have using with JSON function to retrieve data from table.

4) Value of json column – This is nothing but the column value which was we have using to segregate the JSON document data in redshift. We can segregate the data from table column as per value which was we have used in our query.

5) Where condition – We can retrieve JSON document from column by using where condition in redshift.

6) Order by condition – We can retrieve JSON document from column by using order by condition in redshift.

7) Group by condition – We can retrieve JSON document from column by using group by condition in redshift.

How JSON works in Redshift?

There are multiple options available to load the JSON documents in redshift. After loading the data we can retrieve the JSON data by using following JSON functions.

6) Json extract array element text (JSON_EXTRACT_ARRAY_ELEMENT_TEXT) function.

If we want to store the small number of key-value pairs then JSON document is best suited for the same. Using JSON format we can save the storage space of storing the data.

We can store multiple key value pair in a single column by using JSON format, we cannot stored multiple key-value pair in other format.

To use the JSON function on integer datatype values or the data which was not in JSON format. We can apply JSON function only on JSON type of document.

Below example shows that we can apply JSON function only on JSON type of columns.

Code:

Select json_extract_path_text (stud_name, 'A') as key2 from redshift_json where stud_id = 101;

In above example, we have applied JSON function on stud_name column and trying to retrieve key-value pair as “A”, But it will showing error as invalid JSON object which was we have used in our query.

Also, it will showing the parsing error of query.

We cannot use the integer datatype column with JSON function in redshift, we need to use only JSON type of data.

Below example shows that we cannot use the integer datatype of column with JSON function in redshift.

Select json_extract_path_text (stud_id) from redshift_json where stud_id = 101;

In above example, we have used column name as stud_id with JSON function, stud_id datatype as integer. So it will issues the error like integer does not exist, which was not found any matching function or arguments.

We can use copy command to load the data from JSON file to redshift table. We can also use the JSON files which was stores in the S3 bucket.

We can also copy JSON file fields automatically by using option as auto or we need to specify the path of JSON file.

Examples

Below is the example of JSON in redshift are as follows.

1) Querying JSON fields using IS_VALID_JSON function

The below example shows querying JSON fields using IS_VALID_JSON function are as follows. This function is validates the JSON string.

In below example, we have used JSON column to validate the JSON data from function. We have not found any invalid JSON data in JSON column.

Code:

Select stud_id, json, is_valid_json (json) from redshift_json order by stud_id;

2) Querying JSON fields using is_valid_json_array function

Below example shows querying JSON fields using is_valid_json_array function are as follows. This function validates the JSON array string.

In below example, we have used JSON column to validate the JSON array value from function. We have not found any JSON array in JSON column.

Code:

3) Querying JSON fields using json_extract_path_text function

Below example shows querying JSON fields using json_extract_path_text function are as follows. This function is extracting the value from the text.

In below example, we have used json column to extract path text data from function.

Code:

Select stud_id, json, json_extract_path_text (json, 'key2') as json_key from redshift_json order by stud_id;

4) Querying JSON fields using json_parse function

Below example shows querying JSON fields using json_parse function are as follows. This function is used to parse the JSON value.

In below example, we have used json column to parse the data from function.

Code:

Select stud_id, json, json_parse (json) as json_key from redshift_json order by stud_id;

Conclusion

We can use multiple JSON function to query data from table columns. Redshift JSON is very useful and important to store the value in key-value pairs. Using JSON we can store multiple column value within a single column. We can also minimize the storage usage using JSON in redshift.

Recommended Articles

This is a guide to Redshift JSON. Here we discuss the definition, syntax, How JSON works in Redshift? examples with code implementation respectively. You may also have a look at the following articles to learn more –

You're reading How Json Works In Redshift With Examples?

How Json Works In Postgresql?

Definition of PostgreSQL JSON

JSON is an abbreviation of JavaScript Object Notation. JSON stores value in key-value pair; it is an open standard format. We generally prefer JSON for sending/receiving or exchanging data between servers and in web applications. The data within JSON is in text format, which is easily human-readable. PostgreSQL version 9.2 introduced support for the native JSON data type. PostgreSQL provides various methods and operators to work with JSON data.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax:

column_name json  How JSON Works in PostgreSQL?

We need to make sure the given data is in a valid JSON format before adding it to the table.

If JSON data is incorrect, then it will throw an error.

PostgreSQL provides the two native operators to work with JSON data.

How to Insert JSON Data?

To understand the insertion of JSON data, let us create a ‘student’ table with the following structure.

The student table consists of two columns:

stud_id: The column is the primary key column that uniquely identifies the student.

stud_data: The column which stores the student’s information in the form of JSON.

Let’s create the table by using the CREATE TABLE statement:

CREATE TABLE student ( stud_id serial NOT NULL PRIMARY KEY, stud_data json NOT NULL );

Now we will insert the data into the stud_data column, which is of type JSON. Before adding JSON data to the table, we need to ensure the given data is invalid in JSON format. Now insert the JSON data with the help of the following INSERT statement, which will add a new row into the ‘student’ table.

INSERT INTO student (stud_data) VALUES ( '{ "name": "Oliver Jake", "information": { "mobile_number": "9999999999", "branch": "Computer", "rank":12 } }' );

After executing the above statement, illustrate the student table’s content using the following snapshot and SQL statement.

select * from student;

Output:

We can insert multiple rows in the table using the following INSERT statement:

INSERT INTO student (stud_data) VALUES ( '{ "name": "Jack Connor", "information": { "mobile_number": "9999999910", "branch": "Computer", "rank":1 } }' ), ( '{ "name": "Harry Callum", "information": { "mobile_number": "9999999911", "branch": "Civil", "rank":2 } }' ), ( '{ "name": "Jacob John", "information": { "mobile_number": "9999999912", "branch": "Electrical", "rank":6 } }' ); select * from student;

We can fetch the data from the student table by using the following snapshot and SQL statements.

Output:

Examples of PostgreSQL JSON

We have created a student table in the above section; let’s use the same for understanding the following examples.

Example #1 – Get all students in the form of JSON key SELECT FROM student;

Output:

Example #2 – Get all students in the form of JSON text SELECT FROM student;

Output:

Example #3 – Get specific JSON node using operators SELECT FROM student ORDER BY rank;

Output:

Example #4 – Use JSON operator in WHERE clause

In order to filter rows from the result set, we can use the JSON operators in the WHERE clause. Consider the following example, which gives us the record whose branch is Computer by using the following statement.

SELECT FROM student WHERE

Output:

Example #5 – PostgreSQL JSON functions

PostgreSQL provides us with some functions to handle JSON data.

json_each function

By using the json_each() function, we can expand the outermost JSON object into a set of key-value pairs as follows:

SELECT json_each (stud_data) FROM student;

We can use the json_each_text() function to get a set of key-value pairs as text.

json_object_keys function

We can use the json_object_keys() function to get a set of keys in the outermost JSON object as follows:

SELECT FROM student;

json_typeof function

With the help of the function json_typeof(), we can get the type of the outermost JSON value as a string. The type of JSON value can be a boolean, number null, string, object, and array.

We can get the data type of the information using the following statement:

SELECT FROM student;

Output:

We can get the data type rank field of the nested information JSON object using the following statement:

SELECT FROM student;

Output:

Advantages of using JSON in PostgreSQL

Advantages of using JSON in PostgreSQL are given below:

Avoid complicated joins.

Parsing of JSON data is quite easier and faster execution.

Compatible with various database management systems.

Javascript Notation Objects are faster and very easy to read and understand.

The data within the JSON object is separated by a comma, making it easily understandable.

JSON is lightweight for data exchange.

Conclusion

From the above article, we hope you understand how to use the PostgreSQL JSON data type and how the PostgreSQL JSON data type works to store the data in key-value pair. Also, we have added some examples of PostgreSQL JSON to understand it in detail.

Recommended Articles

We hope that this EDUCBA information on “PostgreSQL JSON” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Queue Works In Rust With Examples?

Definition on Rust Queue

Rust queue is a data structure that is used to store the elements, queue in Rust works in an FIO manner that means first in first out. This standard queue is available inside the rust collection library, and the queue is a linear data structure. Queue provides us with several operations that can be performed on it to made manipulation on it. We can add any number of elements inside it, all the implementation is based on the vector data structure in Rust. In rust, we have multiple varieties of a queue which can be used per the chúng tôi next section will cover the queue data structure in rust in detail for better understanding and its implementation while programming for better usage.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

A linear data structure is used to store and manipulate data elements. Here is a detailed syntax for implementing it in programming.

In the above syntax, we create a queue using the ‘Queue’ keyword as the variable type. We can specify the size of the queue and give it a custom name. This is a beginner-friendly syntax example for better understanding. We shall examine its internal operations in more detail in the section that follows.

e.g. :

In this way, we can create it.

How Queue works in Rust?

As we know, the queue is a linear data structure used to store elements. It is accessible as a collection in the standard library of the Rust computer language. But queue works the same way as in another programming language. In Rust, the queue follows the principle of FIFO (first in, first out). As a result, the queue will take out the first item that was put in, followed by the subsequent items in the order of their addition. For instance, we can take the example of a ticketing system, the person who comes first will get the ticket first, and out from the queue, it works in the same way.

Also, we have one more example, which is email queue processing, while drafting an email to multiple persons, it will follow the first email id mentioned, and so on. In this section, we will discuss the various types and methods available in rust, Let’s get started for more information, see below;

We have several types of a queue available in rust which is mentioned below;

Now let’s explore the different operations that we can perform on the queue in Rust, allowing us to manipulate it effectively. We have below mentioned different methods available in Rust for queue see below;

1) peek: The peek method allows us to retrieve the next element in the queue without removing it.

2) add: In Rust, we use the add method to add new element to the queue object. In Rust, we can also refer to this method as push or enqueue.

3) remove: This method removes elements from the queue. But as we already know, that queue works in a FIFO manner, so it always removes the oldest element from the queue. In Rust, we can also refer to this method as pop or dequeue.

Now we will see the following steps to use the queue inside the program in rust see below;

1) To use a queue inside our program, we must first include its dependency inside it. for this, we can add the below-mentioned dependency inside our chúng tôi file in rust, see below;

queues = "1.0.2"

2) After using this, we have to include or import this dependency in our file to use it, mentioned below the line of code inside the file. This is the official documentation of rust see below;

extern crate queues; use queues::*;

3) After this, you can create the queue object and assign it value inside your project. To create the queue object, follow the below line of code:

Example

1) In this example, we are trying to add the element inside the queue by using the add() method in the queue. Also, remember one point this example will run in a fully configured environment only. It will not go running by using any rust online compiler because we added dependency inside it. So first try to set up the configuration, then run it.

Code:

#[macro_use] extern crate queues; use queues::*; fn main() { println!("Demo pragrma to show queue in rust !!"); demoqueue.add(200); demoqueue.add(300); demoqueue.add(400); demoqueue.add(500); demoqueue.add(600); println!(" value inside the queue is {}", demoqueue ); }

Output:

Conclusion

We can store the elements inside by using a queue in rust. Programmers use this data structure to store and manipulate data using the various operations discussed in the tutorial. To utilize these functionalities in programming, programmers need to add the external library to the dependency file. Without doing so, the program will not compile or function properly.

Recommended Articles

We hope that this EDUCBA information on “Rust Queue” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Learn How @Bottom Works In Css With Examples

Introduction to CSS @bottom

CSS Bottom is defined as the bottom property specifies the vertical position of an element added with the position property. It gives the offset at the bottom edge of the reference elements box in any browser window, an element that is altered from the bottom of the viewport. The bottom property does not affect the static position. In this topic, we are going to learn about CSS @bottom.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax and Parameters

Here is the general Syntax as follows:

.container { bottom: value; }

Parameters

length: The value specified in px or em, either negative or positive values

percentage: This value specifies the percentage of the box element height.

auto: It’s a default value and treats height as a value.

inherit: This value inherits its parent container value.

sample example

bottom: 4px         /* length */ bottom: 1.4em bottom: 20%         / *<percentages */ bottom: auto bottom: inherit

When a value is assigned a positive and negative value moves towards it, the element moves away from a given side. For instance, if the bottom: -15 px, This sets the paragraph below the bottom edge of a window.

How @bottom works in CSS?

Let’s see how this property works by its effect on different positioned elements.

Relatively positioned: When the position is set to this property, the bottom adds a respective offset to the bottom edge, which moves its position from its original form to its top. Generally, a top property overrides the bottom property in many aspects. An offset based on the bottom values is applied to the element itself.

Absolute position: With this, the element would move toward the nearest parent. Understanding this example is given in the next section.

Static: This is the default value and does not affect any element.

In the case of JavaScript, the Syntax given as follows

Object.style.bottom="50px"; Examples

Let’s see how this bottom property works in action with an example:

Example #1

Let’s take an example – the effect on the absolute property.

Code:

p { width: 220px; position: absolute; bottom: 100px; padding: 22px; font: bold 16px algerian; background: LightBlue; } h1 { color : red; }

Output:

Example #1a

We can place an image in the bottom property with the same pattern.

Code:

img { position:absolute; bottom:0px } h1 { color: aqua; }

Output:

Example #2

With a position set to relative and using the value ‘Length’.

Code:

div.square { width: 12rem; height: 12rem; display: flex; justify-content: center; align-items: center; background-color: solid purple; position: relative; bottom: 60px; } div.outborder { display: inline-block; border: 3px dashed yellow; margin: 30px 0 1 30px; }

When a bottom is set on the element with respect to the relative position, the element moves up from the original placement of the document. Assigning the bottom to 60px, it shift its positions to the top.

Output:

Example #3

Setting a default value for the bottom property.

Code:

This property makes a paragraph content to be auto adjusted from the margin of bottom page.

Output:

Example #4

Code:

CSS bottom Property- Demo div{ position: relative; width: 100px; height: 110px; font-size: 20px; } #length { bottom: -100px; border: 4px solid purple; } #emvalue { bottom: -20em; border: 4px solid aqua; } #autovalue { bottom: auto; border: 4px solid darkviolet; } #initdefault{ bottom: initial; border: 7px solid yellow ; } h1{ text-align: center; }

Output:

Example #5

An example is demonstrating the bottom property on the Static element.

Code:

.main-b { position: static; right: 20px; bottom: -20px; background-color: blue; padding: 12px; } .derived-b { padding: 12px; background-color: Orange; } inner element. the main element. SUb-element.

The code above shows static in which if I had happened to change the value of the right, bottom we could see the unchanged output.

Output:

Example #6

Code:

div { font-family: Algeria; font-size: 22px; } .A { border: 12px solid yellow; position: relative; } div.abc, chúng tôi { background-color: red; border: 2px solid orange; } div.abc { bottom: 15%; position: absolute; } div.xyz { bottom: 0; position: absolute; }

Output:

Conclusion

Therefore, coming to an end, this CSS article explains how to use the Property called Bottom with their working and examples. Here we have seen a well-organized explanation with many examples of how to use this in CSS. This property, along with attributes like left-right, helps to display exact positions.

Recommended Articles

We hope that this EDUCBA information on “CSS @bottom” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Do I Write Json In Python?

In this article, we will learn different types of methods to write JSON in python.

Conversion Rules

When converting a Python object to JSON data, the dump() method follows the conversion rules listed below −

Writing Dictionary into a JSON File

The function of json.dump() is to arrange a Python object into a JSON formatted stream into the specified file.

Syntax dump(obj, fp, *, skipkeys=False, check_circular=True, allow_nan=True, indent=None, separators=None, default=None, sort_keys=False, **kw) Parameters

obj − obj is known as object that arranges as a JSON formatted stream.

fp −the fp also know as file object will store JSON data.

skipkeys − The default value is False. It ignores the Keys of dict that are not of a basic type. Orelse, it will throw a TypeError.

check_circular − It’s default value is True. It’s main task is to perform circular reference check for container types. This sometimes get the output result in an OverflowError.

allow_nan − It’s e default value is True. If false, serializing out-of-range float values will result in a chúng tôi uses JavaScript equivalents like -NaN, Infinity, -Infinity by default.

indent − It is used for good printing with a specified order.

separators − These are the ones used in the JSON.

default − this function is called when an object fails to serialized. It either returns object’s JSON-encoded version or throw a TypeError. If no type is given, a TypeError is defaulty thrown.

sort_keys − It’s default value is False. If true, the dictionaries’ output will be ordered/sorted by key.

Example

The following program converts the given dictionary to a JSON file using the json.dump() function −

# importing json module import json # creating a dictionary inputDict = { "website": "Tutorialspoint", "authorName": "xyz", "Age": 25, "Address": "hyderabad", "pincode":"503004" } # opening a JSON file in write mode with open('outputfile.json', 'w') as json_file: # writing the dictionary data into the corresponding JSON file json.dump(inputDict, json_file) Output

On executing, the above program will generate the following output −

{"website": "Tutorialspoint", "authorName": "xyz", "Age": 25, "Address": "hyderabad", "pincode": "503004"}

A file named outputfile.json is created containing the above dictionary data.

Using the Indent Parameter

Use the indent parameter of the method dump() for attractive printing.

Example

The following program converts the given dictionary to a pretty JSON file with indentation using the json.dump() function and indent argument −

# importing JSON module import json # creating a dictionary inputDict = { "website": "Tutorialspoint", "authorName": "xyz", "Age": 25, "Address": "hyderabad", "pincode":"503004" } # opening a JSON file in write mode with open('outputfile.json', 'w') as json_file: # writing the dictionary data into the corresponding JSON file # by adding indent parameter to make it attractive with proper indentation json.dump(inputDict, json_file, indent=5) Output

On executing, the above program will generate the following output −

{ "website": "Tutorialspoint", "authorName": "xyz", "Age": 25, "Address": "hyderabad", "pincode": "503004" }

A file named outputfile.json is created containing the above dictionary data with a proper indentation for making it more pretty.

Sorting the Keys in JSON

We can sort the keys of a dictionary alphabetically using the sort_keys = True parameter.

The following program converts the given dictionary to a sorted JSON file with indentation using the json.dump() function and sort_keys argument−

# importing JSON module import json # creating a dictionary inputDict = { "website": "Tutorialspoint", "authorName": "xyz", "Age": 25, "Address": "hyderabad", "pincode":"503004" } # opening a JSON file in write mode with open('outputfile.json', 'w') as json_file: # writing the dictionary data into the corresponding JSON file # indent parameter- to make it attractive with proper indentation # sort_keys- sorts the dictionary keys alphabetically json.dump(inputDict, json_file, indent=5, sort_keys=True) Output { "Address": "hyderabad", "Age": 25, "authorName": "xyz", "pincode": "503004", "website": "Tutorialspoint" }

The keys are now sorted alphabetically, as seen above.

Separators are an additional argument that can be used. In this, you can use any separator you like (“, “, “: “, “,”, “:”).

Converting Python List to JSON Example

The following program converts the python list to JSON string using dumps() function −

# importing JSON module import json # input list inputList = [2, 4, 6, 7] # converting input list into JSON string using dumps() function jsonString = json.dumps(inputList) # printing the resultant JSON string print(jsonString) # printing the type of resultant JSON string print(type(jsonString)) Output [2, 4, 6, 7] Converting Directories Python List to JSON Example

The following program converts the Directories python list to JSON string. using dumps() function −

# importing json module import json # input list of dictionaries list_dict = [{'x':10, 'y':20, 'z':30}, {'p':40, 'q':50}] # converting list of dictionaries into json string jsonData = json.dumps(list_dict) # printing the JSON data print(jsonData) Output [{"x": 10, "y": 20, "z": 30}, {"p": 40, "q": 50}] Converting Python List of Lists to JSON Example

The following program converts the Python List of Lists to JSON string using dumps() function −

# importing JSON module import json # input list of lists list_of_list = [[{'x':10, 'y':20, 'z':30}], [{'p':40, 'q':50}]] # converting a list of list into JSON string jsonString = json.dumps(list_of_list) # printing the resultant JSON string print(jsonString) Output

[[{"x": 10, "y": 20, "z": 30}], [{"p": 40, "q": 50}]]

Conclusion

This article contains a variety of techniques for converting various data formats to JSON files, JSON strings, etc. json.dumps(), which is used to convert any form of iterable to JSON, has also been covered in depth.

How Does Url_For Work In Flask With Examples?

Definition of Flask url_for

Flask url_for is defined as a function that enables developers to build and generate URLs on a Flask application. As a best practice, it is the url_for function that is required to be used, as hard coding the URL in templates and view function of the Flask application tends to utilize more time during modification. If we are using hard coding, and in case we would need to change our URL by inserting another element in the URL, we would have to visit each and every template or form in the code library and make the modifications and will lead to overkill. The url_for function is capable of changing this with just a snap of fingers!

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

It is time now for us to look into different syntax that is present to url_for function before we even dive into learning the working of url_for. This will help us map the syntaxes to the working methodology so that the learning is more practical and easier to grasp. So, without much further ado, let us get straight into the syntax!

Creating dynamic URL with no key passed:

Note: We need to make sure that the function name doesn’t carry any argument, else it might lead to an error.

Creating a dynamic URL with a key and corresponding value passed:

Redirect to a URL using Flask (assuming we are passing key and value pair):

How does url_for work in Flask?

In this section let us go through the working of url_for in Flask, but before that, it is very much required to know about the need for building URLs using the reversing function url_for( ). The concept of reversing function is to use meaningful URLs to help users. If the web application is able to create a meaningful URL that consists of inputs from users, users may remember the inputs used and will enhance the return to the same page again. Not only this there are other pointers that we will discuss below which signifies the importance of using a dynamic URL, keeping in mind the inputs of the user, instead of hard coding the URL.

Developers can change the content of the URL in one shot, and there is no dependency on remembering locations to manually change the hard-coded URLs.

The process of reversing is more descriptive than hard coding.

The special characters and Unicode data are efficiently handled in case of using dynamic URLs.

This is the easy way to avoid unexpected behavior of relative paths in browsers by allocating absolute paths to the generated URLs.

In the case of an application placed outside URL root, the url_for( ) function is capable of handling such scenarios.

Now that we have an understanding of why url_for( ) is so widely appreciated, we would need to understand the types of View responses, as one of these responses relates to the work of url_for( ). The big 3 ways of route logic, an act of mapping the URLs to their specific actions, are namely generating a page template, providing a response, and redirecting the user to a specified location. The working of url_for( ) falls under the category of redirecting.

The method of redirecting accepts a string and this string is nothing but the path that the user is directed to. For the same, the routes are referred to by their names and not by their URL patterns. In the process of creating this input for the redirect function, we use url_for( ). The function url_for( ) takes the name of the view function as an input and creates an output of the provided view. With the change of route URLs, there will be no broken links between pages. Now, when a view is registered with the @app.route decorator, the endpoint name is determined and is ready to be stored with the route registration. This stored route registration is then used to find all routes which link to the registration with the name along with the parameters passed and then execute them to reveal the output.

One important thing to be kept in mind is that, in case we have registered 2 different functions under the same name, we are bound to get an AssertionError and for the same, we can take the help of the endpoint variable and specify the needful. With this, we complete the working of the url_for( ) function in terms of URL routing.

It’s now time for us to look at the implementation of url_for in a Flask application!

Examples

Now that we have complete knowledge about the implementation of url_for and the working methodology along with a complete view on syntax, in this section, we will try using them in practice so that it is easier to learn them by knowing what the practical output will look like! In the examples, we would look at using test_request_context( ) so that we can realize it on the python shell on what URL the particular command is routed to.

Example #1

Creating dynamic URL with no key passed (Run it on console)

from flask import url_for, Flask appFlask = Flask(__name__) @appFlask.route('/home') def home(): return 'We are in Home Page!' with appFlask.test_request_context(): print(url_for('login'))

Output:

Example #2

Creating a dynamic URL with a key and corresponding value passed

Syntax:

from flask import url_for, Flask appFlask = Flask(__name__) def profile(authorname): return f'{authorname}'s profile' with appFlask.test_request_context(): print(url_for('profile', authorname='EduCBA')) print(url_for('profile', authorname='EduCBAPremium'))

Output:

Here, we can easily see the distinction when 2 different values are passed using parameters

Example #3

Syntax:

from flask import Flask, redirect, url_for appFlask = Flask(__name__) def accountType(Type): return 'This is a %s account' % Type def userType(name): if name =='premium': return redirect(url_for('accountType',Type = name)) else: return redirect(url_for('accountType',Type = name)) if __name__ == '__main__': appFlask.run(debug = True)

Output:

When the type is Premium account type:

When the type is basic account type:

Conclusion

Herewith in this article, we have got an essence of how URL routing happens and what dynamic URL can bring to the table. With this, we encourage our readers to experiment with notes in the article and build an exciting Flask application!

Recommended Articles

This is a guide to Flask url_for. Here we discuss the definition, How does url_for work in Flask? and examples with code implementation. You may also have a look at the following articles to learn more –

Update the detailed information about How Json Works In Redshift With Examples? on the Moimoishop.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!