【发布时间】:2017-03-07 15:58:46
【问题描述】:
我的服务器必须通过从客户端接收带有 API 密钥的请求来确保连接性。我发现很难使用 Flask 装饰器来合并它。
我们向客户端提供了 API 密钥,用于接收请求。
每次发出请求时,我们都会检查并验证客户端以将更新发布到我们的数据库中。
Swagger API 定义中有 API key 参数位于 Header 中,需要使用 Flask Decorator 和对应函数来实现。
我编写了以下 Flask 应用程序代码。并且当涉及到在标头中接收 API 时,我无法纠正此服务器错误。
from flask import Flask, render_template, url_for, request, session, redirect,jsonify
from flask_pymongo import PyMongo
import json
from bson.json_util import dumps
import bcrypt
import os
from binascii import hexlify
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'demo'
app.config['MONGO_URI'] = 'mongodb://xxxx:xxxx@xxxxxxx.mlab.com:57158/demo'
mongo = PyMongo(app)
@app.route('/addapi')
def addapi():
users = mongo.db.users
api_key=users.insert({"name":"apikey","X-API-Key":"69222c9b-7858-4eef-a218-039c8cd2bc6e"})
return 'API Key stored'
@app.route('/test/<string:apikey_given_by_user_in_the_header>',methods=['GET'])
"""I have a doubt in the above line that How Can I receive the API Key in the header and check if that is available in my database. This is for testing the connectivity using the Valid API Key."""
def test(apikey_given_by_user_in_the_header):
users=mongo.db.users
api_record=users.find_one({'name':"apikey"})
actual_API_key=api_record['X-API-Key']
if actual_API_key==apikey_given_by_user_in_the_header
return "API is available"
return "Invalid API Key"
Parameter 的 Swagger API 定义如下:
"parameters": [
{
"name": "X-API-Key",
"in": "header",
"required": true,
"type": "string"
},
您能否建议我如何合并此 API 密钥身份验证,其中客户端必须输入我的服务器需要检查和身份验证的 API 密钥?谢谢。
【问题讨论】: