Run! Rookie! with Web-API!

Date: Feb. 10th, 2020

Lecturer: NIghT cAt

Outline

  • I am a rookie with web api
  • I'm trying to know about MVC
  • Prepare the environment
  • Fla~sk

I am a rookie with web api

First, we'll try to realize about api.

Application Programming Interface

  • let developers integrate any two parts of an application or any different applications together.

API

Request

Response

Server

Client

Request

Response

Server

Client

Get

Post

Request

Response

Server

Client

Receive Request

Find Corresponding Function

Search

Database

Representation Function

I'm trying to know about MVC

Framework?

an abstraction in which software providing generic functionality can be selectively changed by additional user-written code.

Framework?

Key Distinguishing Feature in Normal Libraries:

  • Inversion of control
  • extensibility
  • non-modifiable framework code

MVC?

Model

View

Controller

The central component of the patter, it directory manages the data, logic, and rules of the application.

Any representation of information.

Accepts any input and converts it into command for the model or view.

MVC?

And that's what we are going to realize by hands, but before it...

Prepared the environment

Step by Step

Step. 1

New a project directory

Step. 2

Create a virtual environment

Step. 2

Create a virtual environment

We're going to use pipenv which can manage dependencies for an application

1. Use it, we don't need to use pip and venv repectively

2. Generate and update Pipfile, Pipfile.lock

3. Can load different environment parameters through .env file

[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]

[packages]
flask = "*"
line-bot-sdk = "*"
beautifulsoup4 = "*"
requests = "*"
lxml = "*"
python-dotenv = "*"

[requires]
python_version = "3.7"
{
    "_meta": {
        "hash": {
            "sha256": "700e4ebe9f2dbcfb36b51afda233ab0fa894eba97e6e1b86c13362800b5dd10c"
        },
        "pipfile-spec": 6,
        "requires": {
            "python_version": "3.7"
        },
        "sources": [
            {
                "name": "pypi",
                "url": "https://pypi.org/simple",
                "verify_ssl": true
            }
        ]
    },
    "default": {
        "beautifulsoup4": {
            "hashes": [
                "sha256:05fd825eb01c290877657a56df4c6e4c311b3965bda790c613a3d6fb01a5462a",
                "sha256:9fbb4d6e48ecd30bcacc5b63b94088192dcda178513b2ae3c394229f8911b887",
                "sha256:e1505eeed31b0f4ce2dbb3bc8eb256c04cc2b3b72af7d551a4ab6efd5cbe5dae"
            ],
            "index": "pypi",
            "version": "==4.8.2"
        },
        "certifi": {
            "hashes": [
                "sha256:017c25db2a153ce562900032d5bc68e9f191e44e9a0f762f373977de9df1fbb3",
                "sha256:25b64c7da4cd7479594d035c08c2d809eb4aab3a26e5a990ea98cc450c320f1f"
            ],
            "version": "==2019.11.28"
        },
# ...

if OS == "OS X":

brew install pipenv	# Download the pipenv
cd [Project_Directory]	# Change the directory
pipenv --three		# Create the virtual environment

elif OS == "Windows":

pip install pipenv	# Download the pipenv
cd [Project_Directory]	# Change the directory
pipenv --three		# Create the virtual environment

Step. 3

Start up the virtual environment

pipenv shell

Leave the virtual environment

exit	# or "Ctrl + D"

Fla~sk

  • The microframe wrote by Python
  • Based on WSGI、Werkzeug、Jinja2
  • Use simple kernel, and extend other functions by extensions

Still Step by Step

Follow from the Head

Step. 1

Install the package

Warning: YOU SHOULD START UP THE VIRTUAL ENVIRONMENT BEFORE

pipenv install flask

Step. 2

Create a file with the name you like

Warning again:

WITH THE FILE EXTENSION ".py"

Anyway, we use "app.py" as example

Step. 3

Fill it up

from flask import Flask

app = Flask(__name__)

Every Flask web api should have an app instance.

Step. 4

Fill it up again

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "ハロー・ワールド"	# Hello, world

Step. 4-1

What is decorator?

Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it.

def print_func_name(func):
    def wrap():
        print("Now use function '{}'".format(func.__name__))
        func()
    return wrap

def dog_bark():
    print("Bark !!!")

def cat_meow():
    print("Meow ~~~")

if __name__ == "__main__":
    print_func_name(dog_bark)()
    print_func_name(cat_meow)()
def print_func_name(func):
    def wrap():
        print("Now use function '{}'".format(func.__name__))
        func()
    return wrap

@print_func_name
def dog_bark():
    print("Bark!!!")

@print_func_name
def cat_meow():
    print("Meow~~~")

if __name__ == "__main__":
    dog_bark()
    cat_meow()

Syntax Candy

To simplified the Syntax that the function can be presented by simple symbol or few codes.

Step. 5

Run flask

export FLASK_APP=app.py
flask run

if OS == "OS X":

set FLASK_APP=app.py
flask run

if OS == "Windows":

Step. 5

Browse it

Open your browser whatever it is, input the url - 127.0.0.1:5000

You will see the result.

Step. 6

Fill it up again and again

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "ハロー・ワールド"	# Hello, world
  
@app.route("/hello")
def hello:
    return "Hi, stranger~"

Step. 6-1

What is route?

  • http://140.136.251.210/student/
  • http://140.136.251.210/student/Account/Login
  • C:/Program File(x86)
  • usr/local/bin
  • bin/bash
  • etc/passwd

Step. 7

Run it and browse it again

Use 127.0.0.1:5000/hello

References

Run! Rookie! with Web-API!

By Иo1lz

Run! Rookie! with Web-API!

  • 148