【问题标题】:Testing connectivity using API key in the header using Flask and PyMongo使用 Flask 和 PyMongo 在标头中使用 API 密钥测试连接性
【发布时间】:2017-03-07 15:58:46
【问题描述】:

我的服务器必须通过从客户端接收带有 API 密钥的请求来确保连接性。我发现很难使用 Flask 装饰器来合并它。

  1. 我们向客户端提供了 API 密钥,用于接收请求。

  2. 每次发出请求时,我们都会检查并验证客户端以将更新发布到我们的数据库中。

  3. 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 密钥?谢谢。

【问题讨论】:

    标签: rest api flask pymongo


    【解决方案1】:

    要访问传入的请求数据,您可以使用全局请求对象。

    当客户端发送带有您需要的标头的请求时,您可以访问传入的请求标头request.headers,标头是类似于对象的字典:

    from flask import request
    
    @app.route('/api')
    def home():
        key = request.headers.get('API-Key')
        print(key)
        return 'Got %s key'%key
    

    使用 curl 或 httpie 进行测试

    $ http get localhost:port/api API-Key:key-goes-here12458
    $ curl -H "API-Key:key-goes-here12458" localhost:port/api
    

    【讨论】:

    • 非常感谢,您的指导帮助了我很多,节省了很多工作时间。
    猜你喜欢
    • 1970-01-01
    • 2023-02-08
    • 2017-04-11
    • 2021-08-01
    • 2020-11-10
    • 2019-02-25
    • 2020-05-31
    • 2017-12-23
    相关资源
    最近更新 更多