flask開發RESTful架構的api–部署到nginx
阿新 • • 發佈:2019-01-31
本文僅介紹怎麼將flask 開發的 restful api部署到Nginx
環境配置:python2.7 + linux
安裝gunicorn: pip install gunicorn
安裝nginx::參考http://www.runoob.com/linux/nginx-install-setup.html
- restful api檔案
#app.py
from flask import Flask, request, jsonify
from flask_restful import reqparse, Resource, Api
app = Flask(__name__)
api = Api(app)
class Airing(Resource):
def get(self):
return "hello world!"
api.add_resource(Airing,'/airing/')
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8000)
2.建立wsgi.py檔案
#wsgi.py,與app.py在同一個目錄下
from app import app
if __name__ == "__main__":
app.run()
可以試著啟動一下:
gunicorn --bind 127.0.0.1:8000 wsgi:app
訪問:http://127.0.0.1:8000/airing
返回:"hello world!"
3.配置nginx
#修改nginx.conf,相應部分替換為以下內容,參考[這裡](http://python.jobbole.com/85008/)
server {
listen 80;
server_name 本機ip,如10.10.34.31; # 外部地址
location / {
proxy_pass http://127.0.0.1:8000;
proxy_redirect off;
proxy_set _header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
nginx配置完後啟動:/usr/local/webserver/nginx/sbin/nginx
此時可通過外網訪問
訪問:http://10.10.34.31:80/airing
返回:"hello world!"