如何在Flask中处理多个WSGI应用程序?

时间:2017-03-01 16:13:57

标签: python flask flask-restful

我是Flask的新手,想知道如何实现 Flask API http://www.flaskapi.org/)以及主网站,例如主网站(/),访问API (/ API /)。实际上,这给了我一个内部服务器错误。

谢谢。

from flask import Flask, request, url_for
from flask.ext.api import FlaskAPI, status, exceptions

# the all-important app variable:
app = Flask(__name__)
app2 = FlaskAPI(__name__)

@app.route("/")
def hello():
    return "Oh, Hello Worldaa"

notes = {
    0: 'do the shopping',
    1: 'build the codez',
    2: 'paint the door',
}

def note_repr(key):
    return {
        'url': request.host_url.rstrip('/api/') + url_for('notes_detail', key=key),
        'text': notes[key]
}


@app2.route("/api/", methods=['GET', 'POST'])
def notes_list():
    """
        List or create notes.
        """
    if request.method == 'POST':
        note = str(request.data.get('text', ''))
        idx = max(notes.keys()) + 1
        notes[idx] = note
        return note_repr(idx), status.HTTP_201_CREATED

    # request.method == 'GET'
    return [note_repr(idx) for idx in sorted(notes.keys())]


@app2.route("/api/<int:key>/", methods=['GET', 'PUT', 'DELETE'])
def notes_detail(key):
    """
        Retrieve, update or delete note instances.
        """
    if request.method == 'PUT':
        note = str(request.data.get('text', ''))
        notes[key] = note
        return note_repr(key)

    elif request.method == 'DELETE':
        notes.pop(key, None)
        return '', status.HTTP_204_NO_CONTENT

    # request.method == 'GET'
    if key not in notes:
        raise exceptions.NotFound()
    return note_repr(key)

if __name__ == "__main__":
    app.run(debug=True)
    app2.run(debug=True)

1 个答案:

答案 0 :(得分:0)

您可以在Flask的文档中查看Blueprint

例如:

main = Blueprint(__name__)

@main.route("/")
def index():
    return "Hello, World."

api = Blurprint(__name__)

@api.route("/test")
def test():
    return jsonify(dict(test="test")})

app = Flask(__name__)

app.register_blueprint(main)

app.register_blueprint(api, url_prefix="/api")

然后,您按http://example.com访问索引页,通过http://example.com/api/test访问api