flask开发RESTful架构的api–部署到nginx

本文仅介绍怎么将flask 开发的 restful api部署到Nginx

环境配置:python2.7 + linux
安装gunicorn: pip install gunicorn
安装nginx::参考http://www.runoob.com/linux/nginx-install-setup.html


  1. 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!"

参考:
参考1
参考2

你可能感兴趣的:(学习笔记)