Flask is a very popular Web framework in Python that is easy to learn. This article mainly explains how Flask is used through two practical cases. The first example is to implement an interface service that calls the bus arrival information. The second example is to display all test reports through the interface.

Flask installation

  1. Install python
  2. pip install flask
Flask installation

Flask Start service

from flask import Flask

app = Flask(__name__)

app.run()
Copy the code

In three lines of code, you can start a Flask service.

  1. First line, import
  2. The second line creates the Flask program instance
  3. Third line, start the service by instance

Running this code, which can be accessed locally on port 5000, results in a 404 page that cannot be found:

flask running.gif

Add interfaces for the Flask program

At this point, I see a 404 error when I visit http://localhost:5000 because the interface is not defined. A URL address corresponding to a handler can form an interface. You can add an interface to the previous code by using the following code:

@app.route('/')
def index(a):
    return {
        "msg": "success"."data": "welcome to use flask."
    }
Copy the code

After the interface is added, visit http://localhost:5000 again and you can see the normal response data:

image.png

If you need to define additional interfaces, just follow the example above. For example, implementing a registration interface:

@app.route('/user/<u_id>')
def user_info(u_id):
    return {
        "msg": "success"."data": {
            "id": u_id,
            "username": 'yuz'."age": 18}}Copy the code

/user/3 = /user/3

image.png

Flask Implements the bus information query service

Flask is perfectly capable for medium to large projects, but that’s not its goal. If you want to do a complete Web project, Django is recommended. Flask is best used for small projects, such as when you are performing computing tasks and want to provide data services or display services to users via the Web. You dont need to maintain as many modules as Django does.

Let me give you an example. I have now written a program to calculate which buses will pass sanyuan Li in the next period of time. The results can be presented to others in a variety of ways:

  1. Console output

  2. Put it in the database

  3. Show it to the API

  4. Show it on the mobile app

  5. Display it on the Web page

I can now create an API through Flask to present this data to the user. But be aware that presenting data is a small function, the core program should be how I calculate the information of the bus stop, this is the real value of the program, I can show it in any of the above ways, not just web development form. Because the logic shown is very simple, there is no need to use a huge framework like Django.

The real bus information calculation program is very complex, here I use a simple program to simulate the process of calculating bus data. The program randomly generates 10 sets of bus data and stores them in a list.

import random

def get_bus_info(station):
    info = []
    for random_bus in range(10):
        bus_name = f"W{random.randint(1.100)}"
        bus_arrival_time = random.randint(1.30)
        bus_info = f"{bus_name}There are{bus_arrival_time}minutes{station}"
        info.append({bus_name: bus_info})
    return info
Copy the code

Call this function directly to get the relevant bus data:

for bus in get_bus_info('Three miles'):
    print(bus)
Copy the code

The output you can get on the console looks something like this:

image.png

I can now use Flask to create an API that makes my data available to all users and other service providers who want it,

Whether they read it directly or display it on a page, whatever, that’s not my concern. I just do the math, and then I provide the data, and if it’s really good, I can charge for that data, and the user has to pay for the interface THAT I provide.

Next I’m going to create a /bus/

interface. When I type the name of the station bus station into the URL, the interface will return me the bus information for that bus station.

Define the interface:

@app.route('/bus/<station>')
def bus_info(station):
    import bus
    info = bus.get_bus_info(station)
    return {
        "msg": "success"."data": info
    }
Copy the code

Access /bus/ Tian ‘anmen interface to get data:

image.png

Flask implements the test reporting service

In the last example, I provided an API for displaying bus operation data via Flask. Let’s take a look at the functionality of the API that Flask provides with an example showing test reports.

Writing code often requires testing, and the test report data generated after testing is done is usually stored locally. There are many forms of storage:

  1. TXT text
  2. The XML file
  3. The HTML file
  4. Json file
  5. Yaml files.

Here is an example of an HTML file. Write a test program to generate an HTML test report:

import pytest
from datetime import datetime

def test_add(a):
    assert 1= =2

def gen_report_name(a):
    prefix = 'Test Report'
    ts = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
    return prefix + ts + '.html'

if __name__ == '__main__':
    report_name = gen_report_name()
    pytest.main([f'--html=output/{report_name}'])
Copy the code

The test report is generated in the Output directory after each run of the test case program. These reports are prefixed with test reports and the current time is the file name:

pytest-reports-fs8.png

Now I’m going to design an API with the address /report/

. When I enter report/ test report 2020-04-28-13-53-42.html, I can view the content of this test report:

flask check test report

To do this, simply add the corresponding program to the api.py file. This program opens the test report file in the output directory and returns it to the front end:

@app.route('/report/<file_name>')
def get_report(file_name):
    """ Get test report based on file name." ""
    import pathlib
    file_path = pathlib.Path(__file__).parent / 'output' / file_name
    f = open(file_path, encoding='utf-8')
    report = f.read()
    f.close()
    return Response(report)
Copy the code

Flask looks at all the test report links

Now, although I can view the test report through the API, I need to know the name of the test report in advance to enter the corresponding URL. And if they’re going to give it to somebody else, they don’t know what they’re called.

I can now design another API/Reports that will get all the test report addresses directly when the user accesses this interface. Then, copy these addresses to view each test report:

flask check reports

To implement this interface, I will first write a function to automatically collect all test reports from the output directory, as a file with the suffix.html:

def discover_reports(a):
    """ Find all test reports """
    import pathlib
    report_dir = pathlib.Path(__file__).parent / 'output'
    reports = [f.name for f in report_dir.iterdir() if f.suffix == '.html']
    return reports
Copy the code

When I call this function, I return all the test report names in the output directory:

Next, I add the corresponding interface to api.py and call the discover_report function:

@app.route('/reports')
def get_reports(a):
    import test_helper
    report_names = test_helper.discover_reports()
    return {
        "msg": "success"."data": [f"http://localhost:5000/report/{name}"
                 for name in report_names
                 ]
    }
Copy the code

Take a final look to see how all test reports perform:

flask check all reports

conclusion

Flask is a very freewheeling frame. If you want to use Flask, you don’t need to know everything about it, learn it as you go. In the above application that calculates the bus station information, the Web shows only seven lines of code, while the application that simulates the bus data has nine lines.

My understanding of Flask is that the Web is just a way to present data, not a goal. In real life, too many companies or developers treat the Web as their whole life. This is a difference in design philosophy.

If you like minimalism, you should really try it.