Python S2E2 : Flask – Pass Data via URL dynamically

Python S2E2 : Flask – Pass Data via URL dynamically



Language :
Rating : No ratings yet.




Introduction

Flask is a web framework that allows us easily build websites and web applications using Python programming language. Most of the time we develop web apps using frameworks because it's easier and more productive as it allows us avoid re-inventing the wheel.
In this simple tutorial, we see how to pass data via urls to our python code. Fist we route our app urls to specific functions using app.route() decorator on our functions. This maps those urls to their corresponding functions such that when the user browses a specific url, its corresponding function gets executed. The data passed via urls gets passed to the functions as parameters.

Install Flask using the following commands:
$ pip install Flask

You can find detailed installation guide of Flask here.

Tools Used

Language : Python, HTML
Platform : Backend and Fronted Web
Backend: Flask
Fontend: Materializecss
IDE : PyCharm
Topics : Object Oriented Python, Flask install,Flask Routing,Flask URL Data Passing

Questions this Project answers.

  • Flask Routing.
  • Flask web development example
  • Flask Data passing via url example

Libraries Used

These are the third party CSS and JS used in this project.

  • Flask - Is the web framework we use.
  • Materializecss - Is the material design frontend framework we use.

Screenshot

  • Here's the screenshot of the project.

Project Structure

  • Here's the structure of the project.

Source Code

Lets have a look at the source code.

index.htmlmain.pyVideo TutorialDownload
  • Our template.
  • Contains both jinja expressions and html code
  • Data passed from backend will be rendered here.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ site_title }}</title>
    <!-- CSS  -->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="{{ url_for('static',filename='css/materialize.min.css') }}" type="text/css" rel="stylesheet" media="screen,projection"/>
    <link href="{{ url_for('static',filename='css/style.css') }}" type="text/css" rel="stylesheet" media="screen,projection"/>
</head>
<body>
<!--NAVIGATION BAR-->
<nav class="light-blue lighten-1" role="navigation">
    <div class="nav-wrapper container"><a id="logo-container" href="" class="brand-logo">{{ site_title }}</a>
        <ul class="right hide-on-med-and-down">
            <li><a href="">Home</a></li>
            <li><a href="">About</a></li>
        </ul>
        <a href="" data-activates="nav-mobile" class="button-collapse"><i class="material-icons">menu</i></a>
    </div>
</nav>
<!--CONTAINER-->
<div class="container">
    <h1 class="header center orange-text">{{ header }}</h1>
    <h4 class="center light-blue-text">{{ sub_header }}</h4>
<h5 class="center">{{ description }}</h5>
</div>
<br>
<br>
<br>
<br>
<br>
<!--FOOTER-->
<footer class="page-footer orange">
    <div class="container">
        <div class="row">
            <div class="col l6 s12">
                <h5 class="white-text">Company Bio</h5>
                <p class="grey-text text-lighten-4">We are a team of college students working on this project like it's
                    our full time job.</p>
            </div>
            <div class="col l3 s12">
                <h5 class="white-text">Languages</h5>
                <ul>
                    <li><a class="white-text" href="#!">Javascript</a></li>
                    <li><a class="white-text" href="#!">PHP</a></li>
                    <li><a class="white-text" href="#!">Java</a></li>
                    <li><a class="white-text" href="#!">C#</a></li>
                </ul>
            </div>
            <div class="col l3 s12">
                <h5 class="white-text">Connect</h5>
                <ul>
                    <li><a class="white-text" href="#!">Facebook</a></li>
                    <li><a class="white-text" href="#!">Twitter</a></li>
                    <li><a class="white-text" href="#!">Google Plus</a></li>
                    <li><a class="white-text" href="#!">LinkedIn</a></li>
                </ul>
            </div>
        </div>
    </div>
</footer>
</body>
</html>

 

  •  Our main.py file.
  • First import falsk,render_template, redirect and url_for.
  • We initialize flask passing in the name of the current source file.
  • We will ur render_template to render our jinja template.
  • Redirect will help us redirect to specific urls.
  • url_for will build us a url from a function.
# import flask
from flask import Flask, render_template, redirect, url_for
# initialize flask
app = Flask(__name__)
# homepage
@app.route('/')
def index():
    return render_template('index.html', site_title="Camposha.info", header="Dynamic URLS",
                           sub_header="Passing Variables Via URLS ",
                           description="Camposha.info is a programming portal site with hundreds of example projects.")
@app.route('/404')
def page_not_found():
    return render_template('index.html', site_title="Camposha.info", header="404 Error", sub_header="Page Not Found",
                           description="We cannot find the requested page on this server")
# build and redirect
@app.route('/user/<name>')
def login(name):
    # check for admin
    if name == 'admin':
        return render_template('index.html', site_title="Camposha.info", header="Welcome " + name,
                               sub_header="Get Started Below",
                               description="Hello " + name + " how do you do?")
        # check for guest
    elif name == 'guest':
        return render_template('index.html', site_title="Camposha.info", header="Welcome " + name,
                               sub_header="You are Guest.",
                               description="Hello " + name + " how do you do?")
        # check for others
    else:
        return redirect(url_for('page_not_found'))
# run flask
if __name__ == '__main__':
    app.run(debug=True)

 

  • We have a youtube channel with over 600 video tutorials as of now. We add videos almost on a daily basis and we explain everything in details.We take a practical approach instead of so much theory. So please subscribe to stay tuned.
  • Otherwise below is the detailed video version of this tutorial.

Python S2E2 : Flask - Pass Data via URL dynamically

  • Download the Project below:
Download

Conclusion

So that's it guys. Please remember to subscribe to our YouTube channel we are adding tutorial regularly.

How to Download and Run.

  1. Download the project above.
  2. You'll get a zipped file,extract it.
  3. Extract and import into your IDE and run.

More

  • Visit our channel for more examples like these.
  • Lets share tips and ideas in our Facebook Page.

Oclemy,Cheers.



Rating :

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    ten − two =

    COMMENTS