Web development with python #3 : Get method, Query parameter and Navigate Routing

in #utopian-io5 years ago (edited)

Repository

https://github.com/python

What Will I Learn?

  • Get method and Query parameter
  • Navigate routing and access static files

Requirements

  • Basic Python
  • Install Python 3
  • Install Flask

Resources

Difficulty

Basic

Tutorial Content

This tutorial is a continuation of the previous tutorial series, so for those of you who want to start, I suggest you look at the curriculum below. in the previous tutorial, we discussed the POST method, in this tutorial, we will discuss the GET method and the things we can do by templating jinja2, we will do the logic in the jinja2 template. let's just start the following tutorial.

GET Method

In previous tutorial, We have used the POST method to take the value from the post method. of course, we can also take the values in the GET method, with the get method we can use queries parameter to take a value. We can give an example if the following parameter query /profile?username=milleaduski. username is key and milleaduski is value.

  • USE Request.args

to retrieve values from the GET method, we can use the function of the request method, namely request.args.get(). for more details, we can see the following code:

URL: '/profile?username=milleaduski'

app.py

@app.route('/profile')
def profFunc():
    user = request.args.get('username')
    if not search:
        return render_template('index.html')

    return 'The query params is '+ user
  • We can create a new routing to make a test. I made a URL /profile.

  • We will take the value from the query parameter with the key username. to take the value we can use the method request.args.get(). The result of request.args.get() is not a string but a dictionary.

  • We can test by displaying the value in the user variable, If there is no error then we can see the results as below:

ezgif.com-video-to-gif (4).gif

Logic on jinja2

When we create an HTML template in a view, we often want to use the same template but in different conditions to be able to use the same template with slightly different content, for that we need to do some logic in our template, in this tutorial we will give the logic of the jinja2 template. to separate logic templates and HTML scripts we can use {%%}. we will pass values through routing as follows:

app.py

@app.route('/profile')
def profFunc():
    user = request.args.get('username')
    return render_template('index.html', user = user)

as we have learned in the previous tutorial we can pass a value to the template in this way render_template('index.html', user = user).

after we pass the value we can use it in the index.html template. We can see how to use it as an example below:

<!DOCTYPE html>
<html>
<head>
    <title>Template Jinja2</title>
</head>

<body>
    <h1 style="color:blue;">Welcome to my profile</h1>
    {% if not user%}
        <h2>This is profile page</h2>
    {% else %}
        <h2>This is page of {{user}}</h2>
    {% endif%}
</body>
</html>

by using {%%} we can separate HTML scripts with jinja2 logic. Now, we can make logic if as usual, we will choose what element is rendered in the template when we do the GET method. If there is no error then we can see the results as shown below:

ezgif.com-video-to-gif.gif

as we saw in the picture above we can get the value of the parameter query using the function request.args.get()

Directory asset in Flask

We have learned the GET and POST methods, then we will learn how to directory systems on Flask. in a website, of course, we need to load static assets, such as CSS, Javascript, and other files. Now how to do this in the Flask framework. to do that we can use the url_for() method. url_for() is used for matters relating to URLs. in this section we will see its use in our application:

  • Use Url_for() to access static files

We will see an example of Url_for() to access static files like CSS or javascript. We can see an example of its use in the code below:

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Template Jinja2</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css')}}">
</head>
<body>
    <h1 class="title">Welcome to my profile</h1>
    {% if not user%}
        <h2 class="sub-title">This is profile page</h2>
    {% else %}
        <h2 class="sub-title">This is page of {{user}}</h2>
    {% endif %}
</body>
</html>
  • We can access our css file using url for like this href="{{ url_for('static', filename='styles.css')}}", static is the folder name, static is a provision so you cannot change it and then we can set the file that we rendered in HTML, that is styles.css. We can see in the image below url_for will be rendered in HTML like this:

  • Screenshot_3.png

styles.css

The following is the contents of styles.css. here I will make a simple CSS file just as an example:

.title {
    color: red;
}
.sub-title {
    color: green;
}

and we can see the results like the following, please note there will be a little cache when we edit your CSS file, you should use CTRL + F5 to refresh the page and Cmnd + F5 on Mac OS.

ezgif.com-video-to-gif (1).gif

We see in the example above, there is a little cache when we load the CSS but this can be overcome with CTRL + F5. now we have connected our static file with the page. we'll see another example of using url_for.

  • Use url_for() for navigation links

We can use url_for to navigate the links on our application web, we will see an example like the code below:

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Template Jinja2</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css')}}">
</head>
<body>
    <a href="{{ url_for('homeFunction')}}">Home</a>
    <a href="{{ url_for('profFunc')}}">Profile</a>
    <a href="{{ url_for('login')}}">Login</a>
    <h1 class="title">Welcome to my profile</h1>
    {% if not user%}
        <h2 class="sub-title">This is profile page</h2>
    {% else %}
        <h2 class="sub-title">This is page of {{user}}</h2>
    {% endif %}
</body>
</html>

in the index.html file I made 3 links that point to different URLs, to use url_for() for navigating links, we can write it like this <a href="{{ url_for('homeFunction')}}">Home</a>. The parameter that we pass is not the routing but the function of the routing. the following is the routing function, We can see what will be rendered in the HTML element in the following image:

Screenshot_4.png

homeFunction()

@app.route('/welcome')
def homeFunction():
        return render_template('index.html')

homeFunction() is a function that is run in routing /welcome, so when we go to routing it urlfor will look for the name of the function that represents the routing. If there is no error then we can see the results as shown below:

ezgif.com-video-to-gif (2).gif

We can see in the picture above we managed to make the navigation link using ulr_for and we also learn how to capture parameter queries on the GET method, this tutorial is your basis for building web applications and gives you an idea of how to start ?, I hope you get lessons that you can use to create your web application using Flask, thank you for following this tutorial.

Curriculum

Web developement with python #1 : Flask initialization and Routing system

Web development with python #2 : Templating jinja2 and Method POST on routing system

Proof of work done

https://github.com/milleaduski/python-web-app

Sort:  

Thank you for your contribution @duski.harahap.

  • We really like your tutorial to show screen captures with the results of what you are explaining. This helps a lot the reader.

  • We suggest you improve your writing of your tutorial. It is very important to have the text without errors.

  • Be careful with the punctuation of the text.

Thanks for your work on developing this tutorial. We are waiting for more tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.26
TRX 0.11
JST 0.033
BTC 63869.25
ETH 3055.04
USDT 1.00
SBD 3.88