[Python Flask+Nginx] Implement HTTP and WS (two-step implementation, simple and easy to understand)

Table of contents

1. Create a Flask application 

2. Deploy Nginx

2.1 Download Nginx 

2.2 Modify Nginx configuration file

2.3 Start Nginx

3. Test


1. Create a Flask application 

        First, I wrote the following Demo based on Flask. The Demo contains two interfaces, one is the HTTP interface (http://127.0.0.1:5000) and the other is the Websocket interface (ws://127.0.0.1:5000/test)

If the HTTP interface is called, a json data will be returned:  

{"msg":"ok"}

 If you call Websocket, a time will be returned every 1s:

 Flask application Demo source code:

import time
from flask_sockets import Sockets
from gevent import monkey
from flask import Flask, jsonify
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler

monkey.patch_all()

app = Flask(__name__)
sockets = Sockets(app)

#  ws接口
@sockets.route('/test')  # 指定路由
def echo_socket(ws):
    while not ws.closed:
        ws.send(str(time.asctime()))  # 给clicent传时间

# http接口
@app.route('/')
def hello():
    return jsonify(msg="ok")


if __name__ == "__main__":
    server = pywsgi.WSGIServer(('0.0.0.0', 5000), app, handler_class=WebSocketHandler)
    print('server start')
    server.serve_forever()

2. Deploy Nginx

2.1 Download Nginx 

First go to the official website to download Nginx (official website download address: nginx: download )

141914_eVJV_1455020.png 

 After downloading, the directory is as follows:

2.2 Modify Nginx configuration file

Open the configuration file:

 Mainly modify the following marked area content:

        listen: port behind proxy

        servername: You can fill in IP or domain name

        proxy_pass: corresponds to the web address after the flask program is started.

copy and paste: 

listen       9900;
server_name  localhost;

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

2.3 Start Nginx

First start cmd as administrator, then cd to the directory containing nginx.exe

Start command: 

start nginx

 Close command:

nginx -s quit

3. Test

1. First run the Flask application:

 

2. Start Nginx:

 

 3. Test the http interface:

4. Test the websocket interface: (Test address: websocket online test )

 OK, everything is fine~, call it a day

 

Guess you like

Origin blog.csdn.net/ChaoChao66666/article/details/132489646