Set up a simple Web services – Flask framework

    • What is WSGI?
    • Build a simple Web service
    • Three, extension,
    • Request to add parameters
    • Install the flask

What is WSGI?

Wsgi acts as a communication bridge between WebServer and Application.

Build a simple Web service

# coding:utf-8# Step: # setup service # Listen actionwhileLoop every few seconds to see if a request has been sent # handler # returns data to the socket, generating a response object from wsGIREF.simple_server import make_server


def app(env, make_reponse)Make_reponse (status code: header) make_reponse("200 ok", [('content-type'.'text/plain')])
    return [b"hello,hanhanwang"] # b = server = make_server("".8000, app)
server.serve_forever(a)Copy the code

Operating conditions :(same as below!)

Three, extension,

  1. Define 3 urls, ‘/ ‘home page,’ register ‘, and ‘/login ‘
  2. Respond to three urls
  3. Exception handling: If access is not in the specified three RULS, a 404 error is reported.
# coding:utf-8# Step: # setup service # Listen actionwhileLoop every few seconds to see if a request has been sent # handler # returns data to the socket, generating a response object from wsGIREF.simple_server import make_server


def index(a):
    return "hello,I'm index!"

def register():
    return "hello,please register!"

def login():
    return "hello,please login!"Def app(env, start_resp): # start_resp(status code: header) if env."PATH_INFO") == "/":
        start_resp("200 ok", [('content-type'.'text/plain')])
        soresponse = index(a)return [soresponse.encode()]

    elif env.get("PATH_INFO") = ="/register":
        start_resp("200 ok", [('content-type'.'text/plain')])
        soresponse = register(a)return [soresponse.encode()]

    elif env.get("PATH_INFO") = ="/login":
        start_resp("200 ok", [('content-type'.'text/plain')])
        soresponse = login(a)return [soresponse.encode()]

    else:
        start_resp("404 not found", [('content-type'.'text/plain')])
        return [b"sorry! page not found!"]  # b is byte


server = make_server("".8001, app)
server.serve_forever(a)Copy the code

If a lot of conditional branches are ==, use a dictionary to wrap them. (Advantages: more flexibility, easy to modify and add)

Code simplification:

# coding:utf-8# Step: # setup service # Listen actionwhileLoop every few seconds to see if a request has been sent # handler # returns data to the socket, generating a response object from wsGIREF.simple_server import make_server


def index(a):
    return "hello,I'm index!"


def register():
    return "hello,please register!"


def login():
    return "hello,please login!"This is a centralized route management pattern (a bit like the Django framework) {
    "/": index,
    "/register": register."/login": login,
}


def app(env, start_resp)# start_resp(status code: header) URL = env.get("PATH_INFO")
    if (url is None) or (url not in patterns.keys()) :start_resp("404 not found", [('content-type'.'text/plain')])
        return [b"sorry! page not found!"]  # b is byte

    start_resp("200 ok", [('content-type'.'text/plain')])
    respon = patterns.get(url)
    if respon is None:
        start_resp("404 not found", [('content-type'.'text/plain')])
        return [b"sorry! page not found!"]  # b is byte

    return [respon().encode()]


server = make_server("".8001, app)
server.serve_forever(a)Copy the code

Blog.csdn.net/hanhanwangh… Treasure Girl welcomes your attention! Welcome to wechat public account: Treasure girl’s growing diary if reproduced, please indicate the source (if not indicated, the thief will investigate)

Request to add parameters

# coding:utf-8# Step: # setup service # Listen actionwhileLoop every few seconds to see if a request has been sent. The handler returns data to the socket and generates a response objectimport json
from wsgiref.simple_server import make_server


def index(request): return request def register(request): return request def login(request): Return Request # This is a centrally managed route (a bit like the Django framework) Patterns = {
    "/": index,
    "/register": register."/login": login,
}


def app(env, start_resp)Flask core object # env Fetch relevant data -- environment variable # start_RESp (status code: header) URL = env.get("PATH_INFO")
    params = env.get("QUERY_STRING")
    if (url is None) or (url not in patterns.keys()) : #start_resp("404 not found", [('content-type'.'text/plain')])
        # return [b"sorry! page not found!"] # b is of type byte

        # start_resp("404 not found", [('content-type'.'text/html'If you want to return HTML, you can change it to ()'content-type'.'text/html')
        # return [b"

sorry! page not found!

"
] # b is of type byte
start_resp("404 not found", [('content-type'.'application/json')]) result = json.dumps({"msg": "page is not found"}) return [result.encode()] start_resp("200 ok", [('content-type'.'text/plain')]) respon = patterns.get(url) if respon is None: start_resp("404 not found", [('content-type'.'text/plain')]) return [b"sorry! page not found!"] # b is byte return [respon(params).encode()] server = make_server("".8002, app) server.serve_forever(a)Copy the code

We don’t like Flask because we use Django (which is much more efficient than Flask), but we learn Flask to dig holes and understand Web frameworks better, and when we run into problems with Django, it’s easier to handle.

Install the flask

pip install flask
Copy the code

As shown in figure:

Flask framework combat points will be recorded in detail next, continue to be more bo! I’m still a flask, if you see me, I’ll be grateful for your advice!

Blog.csdn.net/hanhanwangh… Welcome to pay attention to this super invincible lovely person duck, have any question message private message all can, see will return! Creation is not easy, if there is a reprint, please indicate the source