網頁

2020年3月18日 星期三

https on nginx and python flask

建立 python flask 的網頁伺服器
$ cat server.py
@app.route('/api/PostTime', methods=['POST'])
def post_time():
    print(request.headers)
    print(request.json)
    result = '\n'.join([request.json['updDate'],
            request.json['camera']])
    print(result)
    return str(result)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port="5000", debug=True,
            # 下兩行可以啟動 https
            #ssl_context=("/home/user1/Data/webapi/openssl/web1/server.crt",
            #    "/home/user1/Data/webapi/openssl/web1/server.key")
            )

$ python3 server.py

$ cat PostTime.py
import requests
import os

data = {
    'updDate': '2019-01-02T15:10:11',
    'camera': 'A001',
}

os.environ['REQUESTS_CA_BUNDLE'] = '/home/user1/Data/webapi/openssl/ca/cacert.pem'
#url = 'https://127.0.0.1:5000/api/PostTime'
url = 'https://127.0.0.1:8443/api/PostTime'
headers = {'Content-Type': 'application/json'}
response = requests.post(url=url,
        headers=headers,
        #verify=False,
        json=data)
if response.ok:
    print("PostTime ok")
    print(response.status_code)
    print(response.text)
else:
    print(response.status_code)
    print(response.text)

$ python3 PostTime.py

# cat /etc/nginx/sites-available/config
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        listen 8443 ssl default_server;
        listen [::]:8443 ssl default_server;
        ssl_certificate /home/user1/Data/webapi/openssl/web1/server.crt;
        ssl_certificate_key /home/user1/Data/webapi/openssl/web1/server.key;
        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location ^~ /api/ {
                # 當 https 由 nginx 管控,python flask 就要走一般的 http
                proxy_pass http://127.0.0.1:5000;
                proxy_set_header Host $host;
        }
        # 設定上傳限制
        client_max_body_size 10M;
}

重新啟動 nginx
# sudo nginx -s reload

沒有留言:

張貼留言