Flask Introduction to Python

Source: Internet
Author: User

Flask Introduction of knowledge points
    • Micro-framework, WSGI, template engine concepts
    • Use Flask to do web apps
    • Use of templates
    • Return a specific page based on a URL
Experiment Step 1. What is Flask?

Flask is a web framework. This means that Flask provides you with tools, libraries, and techniques to allow you to build a Web application. This wdb application can make some Web pages, blogs, wikis, web-based calendar apps, or commercial web sites.

Flask belongs to the micro-framework (micro-framework) category, and microarchitecture is often a small framework that does not depend on external libraries. This has both advantages and disadvantages, the advantage is that the framework is lightweight, less dependent on updates, and focused on security bugs, the downside is that you have to do more work by yourself, or add your own dependency list by adding plugins. The Flask relies on the following:

    • Werkzeug a WSGI Toolkit
    • JINJA2 Template engine

Introduction to Wikipedia WSGI:

The Web server gateway Interface (Python Interface, abbreviated as WSGI) is a simple and common interface between a Web server and a Web application or framework defined for the Python language. Similar interfaces have appeared in many other languages since Wsgi was developed.

2. What is a template engine?

Have you built a website? Have you ever faced the problem of keeping your website style consistent, and have you had to write the same text multiple times? Have you ever tried to change the style of this website?

If your site contains only a few pages, changing the style of the website will take you some time, which is really doable. However, if you have a lot of pages (such as a list of items sold in your store), this task can be daunting.

Using a template you can set the basic layout of your page and mention which element will change. This way you can define your page header and make it consistent across all pages of your site, and if you need to change the page header, you only need to update one place.

Creating/updating/Maintaining your app with the template engine will save you a lot of time.

3. "Hello World" app

We will use flask to complete a very basic application.

    • Installing flask
$ sudo pip3 install flask
    • Create a project structure
$ mkdir -p hello_flask/{templates,static}

This is the basic structure of your Web app:

$ tree hello_flask/hello_flask|-- static`-- templates2 directories, 0 files

templatesFolders are places where templates are stored, and static folders hold static files (images, CSS, JavaScript) required for Web applications.

    • Create an app file
cd hello_flask$ vim hello_flask.py

The following code is written in the hello_flask.py file:

#!/usr/bin/env pythonimport flask# Create the application.APP = flask.Flask(__name__)@APP.route(‘/‘)def index(): """ 显示可在 ‘/‘ 访问的 index 页面 """ return flask.render_template(‘index.html‘)if __name__ == ‘__main__‘: APP.debug=True APP.run()
    • Create a template fileindex.html
$ vim templates/index.html

The contents of the index.html file are as follows:

<! DOCTYPE html><Htmllang=' En ' ><Head><meta charset=  "utf-8"/> <title>hello world!< Span class= "Hljs-tag" ></title> < Link type= "text/css" rel=" stylesheet "href=" {{url_for (' static ', Filename= ' Hello.css ')}} "/></head><< Span class= "Hljs-name" >body>it works! </body></ HTML>             
    • Running the Flask application
$ python3 hello_flask.py

To access the http://127.0.0.1:5000/, this should just show the "It works!" text on the black-word white background, such as:

4. Parameters used in Flask

In this section we will see how to return a Web page based on the URL used by the user.

To do this we update the hello_flask.py file.

    • Add the following entry in the hello_flask.py file
@APP.route(‘/hello/<name>/‘)def hello(name): """ Displays the page greats who ever comes to visit it. """ return flask.render_template(‘hello.html‘, name=name)
    • Create the following template hello.html
<! DOCTYPE html><Htmllang=' En ' ><Head><meta charset=  "utf-8"/> <title>hello</title> <link type= "text/css" rel=  "stylesheet" href= "{{url_for (' Static ', filename= ' Hello.css ')}} "/></head><body> Hello {{Name}}</ body></HTML>    
    • Running Flask Applications
$ python3 hello_flask.py

To access the http://127.0.0.1:5000/, this should just show the "It works!" text on the black Word white bottom.

Visit Http://127.0.0.1:5000/hello/you, which should return the text "Hello You", see:

Whatever you fill out in the URL /hello/ , it will appear in the returned page.

This is the first time you have used a template, and we have created a variable in hello_flask.py name (see the return line of the Hello function). Through syntax {{name}} , the name variable displays itself in the page.

5. Additional work 5.1. Using templates

Currently, for each page we have created a template, in fact it is not good practice, we should do is to create a master template and use it on each page.

    • Create a template file master.html.
<! DOCTYPE html><Htmllang=' En ' ><Head><meta charset= "utf-8"/> <title>{% block title%}{% endblock%}-Hello flask! </title> <link type= "text/css" rel=  "stylesheet" href= "{{url_for (' Static ', filename= ' Hello.css ')}} "/></head><body>{% block body%}{% endblock%}</body></HTML>      
    • Adjust the template index.html.
{% extends "master.html" %}{% block title %}Home{% endblock %}{% block body %}It works!{% endblock %}

As you can see, in the master.html template we define two parts, named title and body blocks .

In template index.html, we declare that this template extends from the master.html template, and then we define the content to be placed in these two sections (blocks). In the first block title we placed the Home word, and in the second block body we defined what we wanted in the body of the page.

    • As an exercise, change the other template hello.html and use master.html as well.
    • Add the home link on the Hello page.

Adjust the template hello.html, add the link to the homepage.

<a href="{{ url_for(‘index‘) }}"><button>Home</button></a>
    • As your task, add a link to the Hello page on the homepage.
Summarize

In this experiment, we understand the concepts of micro-framework, WSGI, template engine, and learn to use Flask as a Web application, in which we use templates. When the user accesses the server with the correct URL, the server returns a different Web page. Finally, we have left a small task, I hope you can complete.

Here are just a few of the Flask that are interested in learning about Flask's official documentation.

Flask Introduction to Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.