API和APP Flask

时间:2017-08-01 15:43:34

标签: python rest api flask

我正在尝试用烧瓶进行Api Rest,以及访问API的GUI。 Api将添加,删除和返回有关CARDS ID的信息。 GUI将会这样做,但是使用Web界面。

我测试了我的Api,它有效。但是,当我尝试GUI时,不起作用。 我不知道向我自己的Api发出请求是否有问题,我也不想重复代码。

我的英语不好,所以,如果你需要,我可以尝试更好地解释我的问题。

#
# Setup the API
#
api_bp = Blueprint('api', __name__)
api = Api(api_bp)

parser = reqparse.RequestParser()
parser.add_argument('card_id')

CARDS = {}

def abort_if_card_id_doesnt_exist(card_id):
    if card_id not in CARDS:
        logging.error("Card {} doesn't exist".format(card_id))
        abort(404, message="Card {} doesn't exist".format(card_id))


# Card
# shows a single card item and lets you delete a card item
class Card(Resource):
    def get(self, card_id):
        abort_if_card_id_doesnt_exist(card_id)

        logging.debug("GET /card/%s " % card_id)
        return CARDS[card_id]

    def delete(self, card_id):
        abort_if_card_id_doesnt_exist(card_id)
        del CARDS[card_id]

        logging.debug("DELETE /card/%s " % card_id)
        return '', 204

    def put(self, card_id):
        abort_if_card_id_doesnt_exist(card_id)
        card = {card_id: ''}
        CARDS[card_id] = card

        logging.debug("PUT /card/%s " % card_id)
        return card, 201


# Cards
# shows a list of all cards, and lets you POST to add new card
class Cards(Resource):
    def post(self):
        args = parser.parse_args()
        card_id = args['card_id']
        CARDS.update({card_id: ''})
        logging.debug("POST /cards %s " % card_id)
        return card_id, 201

    def get(self):
        logging.debug("GET /cards ")
        return CARDS, 201

api.add_resource(Card, '/card/<card_id>')
api.add_resource(Cards, '/cards')

#
# Setup the App
#
app = Flask(__name__)
app.register_blueprint(api_bp)

URL = '192.168.99.100'


@app.route("/")
def index():
    return render_template('index.html')


@app.route("/list", methods=['GET'])
def list():
    r = requests.get('http://%s:5000/cards' % URL)
    return r.content


@app.route("/save", methods=['POST'])
def save():
    data = {'card_id': request.form['card_id']}
    r = requests.post('http://%s:5000/cards' % URL, data)
    return r.status_code


@app.route("/remove", methods=['GET'])
def remove():
    return requests.get('http://%s:5000/cards' % URL).content


@app.route("/validate", methods=['GET'])
def validate():
    return requests.get('http://%s:5000/cards' % URL).content


if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0')

0 个答案:

没有答案